matrix-js-sdk 42.1.0 → 42.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/@types/beacon.d.ts +1 -1
  3. package/lib/@types/beacon.js +1 -1
  4. package/lib/@types/beacon.js.map +1 -1
  5. package/lib/@types/extensible_events.d.ts.map +1 -1
  6. package/lib/@types/extensible_events.js.map +1 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/browser-index.js.map +1 -1
  9. package/lib/client.d.ts +12 -5
  10. package/lib/client.d.ts.map +1 -1
  11. package/lib/client.js +23 -26
  12. package/lib/client.js.map +1 -1
  13. package/lib/common-crypto/key-passphrase.js +1 -1
  14. package/lib/common-crypto/key-passphrase.js.map +1 -1
  15. package/lib/crypto/store/indexeddb-crypto-store-backend.js +2 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  17. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +1 -1
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  21. package/lib/embedded.d.ts +16 -0
  22. package/lib/embedded.d.ts.map +1 -1
  23. package/lib/embedded.js +19 -6
  24. package/lib/embedded.js.map +1 -1
  25. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  26. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  27. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  28. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  29. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  30. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  31. package/lib/matrixrtc/utils.d.ts +0 -1
  32. package/lib/matrixrtc/utils.d.ts.map +1 -1
  33. package/lib/matrixrtc/utils.js +0 -1
  34. package/lib/matrixrtc/utils.js.map +1 -1
  35. package/lib/models/event-timeline-set.js +3 -3
  36. package/lib/models/event-timeline-set.js.map +1 -1
  37. package/lib/models/event.d.ts.map +1 -1
  38. package/lib/models/event.js.map +1 -1
  39. package/lib/models/invites-ignorer.js.map +1 -1
  40. package/lib/models/poll.js.map +1 -1
  41. package/lib/models/read-receipt.js.map +1 -1
  42. package/lib/models/relations-container.d.ts +10 -0
  43. package/lib/models/relations-container.d.ts.map +1 -1
  44. package/lib/models/relations-container.js +39 -17
  45. package/lib/models/relations-container.js.map +1 -1
  46. package/lib/models/relations.js +1 -1
  47. package/lib/models/relations.js.map +1 -1
  48. package/lib/models/room.js +3 -3
  49. package/lib/models/room.js.map +1 -1
  50. package/lib/models/thread.d.ts +3 -0
  51. package/lib/models/thread.d.ts.map +1 -1
  52. package/lib/models/thread.js +36 -3
  53. package/lib/models/thread.js.map +1 -1
  54. package/lib/oauth/authorize.js +1 -1
  55. package/lib/oauth/authorize.js.map +1 -1
  56. package/lib/oauth/index.js +4 -2
  57. package/lib/oauth/index.js.map +1 -1
  58. package/lib/pollingCachedValue.d.ts +77 -0
  59. package/lib/pollingCachedValue.d.ts.map +1 -0
  60. package/lib/pollingCachedValue.js +160 -0
  61. package/lib/pollingCachedValue.js.map +1 -0
  62. package/lib/pushprocessor.js.map +1 -1
  63. package/lib/receipt-accumulator.d.ts.map +1 -1
  64. package/lib/receipt-accumulator.js.map +1 -1
  65. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  66. package/lib/rendezvous/MSC4108SignInWithQR.js +2 -3
  67. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  68. package/lib/rtcTransportsCachedValue.d.ts +9 -0
  69. package/lib/rtcTransportsCachedValue.d.ts.map +1 -0
  70. package/lib/rtcTransportsCachedValue.js +38 -0
  71. package/lib/rtcTransportsCachedValue.js.map +1 -0
  72. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  73. package/lib/rust-crypto/backup.d.ts +2 -3
  74. package/lib/rust-crypto/backup.d.ts.map +1 -1
  75. package/lib/rust-crypto/backup.js.map +1 -1
  76. package/lib/rust-crypto/index.d.ts +10 -4
  77. package/lib/rust-crypto/index.d.ts.map +1 -1
  78. package/lib/rust-crypto/index.js +20 -3
  79. package/lib/rust-crypto/index.js.map +1 -1
  80. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  81. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  82. package/lib/sliding-sync-sdk.js.map +1 -1
  83. package/lib/sliding-sync.js.map +1 -1
  84. package/lib/store/indexeddb-local-backend.js +1 -1
  85. package/lib/store/indexeddb-local-backend.js.map +1 -1
  86. package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
  87. package/lib/store/indexeddb-store-worker.js +1 -0
  88. package/lib/store/indexeddb-store-worker.js.map +1 -1
  89. package/lib/sync.d.ts.map +1 -1
  90. package/lib/sync.js.map +1 -1
  91. package/lib/utils.d.ts +1 -1
  92. package/lib/utils.d.ts.map +1 -1
  93. package/lib/utils.js +1 -0
  94. package/lib/utils.js.map +1 -1
  95. package/lib/webrtc/call.js.map +1 -1
  96. package/lib/webrtc/groupCall.js.map +1 -1
  97. package/lib/webrtc/mediaHandler.js.map +1 -1
  98. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  99. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  100. package/lib/wellKnownCachedValue.d.ts +8 -0
  101. package/lib/wellKnownCachedValue.d.ts.map +1 -0
  102. package/lib/wellKnownCachedValue.js +34 -0
  103. package/lib/wellKnownCachedValue.js.map +1 -0
  104. package/package.json +4 -4
  105. package/src/@types/beacon.ts +1 -1
  106. package/src/@types/extensible_events.ts +3 -4
  107. package/src/autodiscovery.ts +2 -2
  108. package/src/browser-index.ts +1 -1
  109. package/src/client.ts +48 -40
  110. package/src/common-crypto/key-passphrase.ts +1 -1
  111. package/src/crypto/store/indexeddb-crypto-store-backend.ts +2 -1
  112. package/src/crypto/store/indexeddb-crypto-store.ts +1 -3
  113. package/src/crypto/store/memory-crypto-store.ts +1 -1
  114. package/src/embedded.ts +34 -11
  115. package/src/matrixrtc/MatrixRTCSession.ts +3 -3
  116. package/src/matrixrtc/MembershipManager.ts +1 -1
  117. package/src/matrixrtc/MembershipManagerActionScheduler.ts +1 -1
  118. package/src/matrixrtc/RTCEncryptionManager.ts +2 -2
  119. package/src/matrixrtc/ToDeviceKeyTransport.ts +3 -3
  120. package/src/matrixrtc/membershipData/rtc.ts +1 -1
  121. package/src/matrixrtc/utils.ts +0 -2
  122. package/src/models/event-timeline-set.ts +3 -3
  123. package/src/models/event.ts +7 -10
  124. package/src/models/invites-ignorer.ts +1 -1
  125. package/src/models/poll.ts +1 -1
  126. package/src/models/read-receipt.ts +1 -1
  127. package/src/models/relations-container.ts +55 -19
  128. package/src/models/relations.ts +1 -1
  129. package/src/models/room.ts +9 -9
  130. package/src/models/thread.ts +49 -4
  131. package/src/oauth/authorize.ts +1 -1
  132. package/src/oauth/index.ts +2 -2
  133. package/src/pollingCachedValue.ts +184 -0
  134. package/src/pushprocessor.ts +3 -3
  135. package/src/receipt-accumulator.ts +1 -2
  136. package/src/rendezvous/MSC4108SignInWithQR.ts +3 -4
  137. package/src/rtcTransportsCachedValue.ts +40 -0
  138. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
  139. package/src/rust-crypto/backup.ts +1 -5
  140. package/src/rust-crypto/index.ts +23 -25
  141. package/src/rust-crypto/libolm_migration.ts +1 -1
  142. package/src/rust-crypto/rust-crypto.ts +3 -3
  143. package/src/sliding-sync-sdk.ts +1 -1
  144. package/src/sliding-sync.ts +1 -1
  145. package/src/store/indexeddb-local-backend.ts +1 -1
  146. package/src/store/indexeddb-store-worker.ts +1 -0
  147. package/src/sync.ts +4 -3
  148. package/src/utils.ts +3 -2
  149. package/src/webrtc/call.ts +6 -6
  150. package/src/webrtc/groupCall.ts +7 -7
  151. package/src/webrtc/mediaHandler.ts +1 -1
  152. package/src/webrtc/stats/callStatsReportGatherer.ts +2 -2
  153. package/src/webrtc/stats/transportStatsBuilder.ts +1 -1
  154. package/src/wellKnownCachedValue.ts +34 -0
@@ -1 +1 @@
1
- {"version":3,"file":"poll.js","names":[],"sources":["../../src/models/poll.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START } from \"matrix-events-sdk\";\n\nimport { M_POLL_END, M_POLL_RESPONSE } from \"../@types/polls.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { type PollStartEvent } from \"../extensible_events_v1/PollStartEvent.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { Relations } from \"./relations.ts\";\nimport { type Room } from \"./room.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum PollEvent {\n New = \"Poll.new\",\n End = \"Poll.end\",\n Update = \"Poll.update\",\n Responses = \"Poll.Responses\",\n Destroy = \"Poll.Destroy\",\n UndecryptableRelations = \"Poll.UndecryptableRelations\",\n}\n\nexport type PollEventHandlerMap = {\n [PollEvent.Update]: (event: MatrixEvent, poll: Poll) => void;\n [PollEvent.Destroy]: (pollIdentifier: string) => void;\n [PollEvent.End]: () => void;\n [PollEvent.Responses]: (responses: Relations) => void;\n [PollEvent.UndecryptableRelations]: (count: number) => void;\n};\n\nconst filterResponseRelations = (\n relationEvents: MatrixEvent[],\n pollEndTimestamp: number,\n): {\n responseEvents: MatrixEvent[];\n} => {\n const responseEvents = relationEvents.filter((event) => {\n if (event.isDecryptionFailure()) {\n return;\n }\n return (\n M_POLL_RESPONSE.matches(event.getType()) &&\n // From MSC3381:\n // \"Votes sent on or before the end event's timestamp are valid votes\"\n event.getTs() <= pollEndTimestamp\n );\n });\n\n return { responseEvents };\n};\n\nexport class Poll extends TypedEventEmitter<Exclude<PollEvent, PollEvent.New>, PollEventHandlerMap> {\n public readonly roomId: string;\n public readonly pollEvent: PollStartEvent;\n private _isFetchingResponses = false;\n private relationsNextBatch: string | undefined;\n private responses: null | Relations = null;\n private endEvent: MatrixEvent | undefined;\n /**\n * Keep track of undecryptable relations\n * As incomplete result sets affect poll results\n */\n private undecryptableRelationEventIds = new Set<string>();\n\n public constructor(\n public readonly rootEvent: MatrixEvent,\n private matrixClient: MatrixClient,\n private room: Room,\n ) {\n super();\n if (!this.rootEvent.getRoomId() || !this.rootEvent.getId()) {\n throw new Error(\"Invalid poll start event.\");\n }\n this.roomId = this.rootEvent.getRoomId()!;\n this.pollEvent = this.rootEvent.unstableExtensibleEvent as unknown as PollStartEvent;\n }\n\n public get pollId(): string {\n return this.rootEvent.getId()!;\n }\n\n public get endEventId(): string | undefined {\n return this.endEvent?.getId();\n }\n\n public get isEnded(): boolean {\n return !!this.endEvent;\n }\n\n public get isFetchingResponses(): boolean {\n return this._isFetchingResponses;\n }\n\n public get undecryptableRelationsCount(): number {\n return this.undecryptableRelationEventIds.size;\n }\n\n public async getResponses(): Promise<Relations> {\n // if we have already fetched some responses\n // just return them\n if (this.responses) {\n return this.responses;\n }\n\n // if there is no fetching in progress\n // start fetching\n if (!this.isFetchingResponses) {\n await this.fetchResponses();\n }\n // return whatever responses we got from the first page\n return this.responses!;\n }\n\n /**\n *\n * @param event - event with a relation to the rootEvent\n * @returns void\n */\n public onNewRelation(event: MatrixEvent): void {\n if (M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) {\n this.endEvent = event;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n // wait for poll responses to be initialised\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n const { responseEvents } = filterResponseRelations([event], pollEndTimestamp);\n\n this.countUndecryptableEvents([event]);\n\n if (responseEvents.length) {\n responseEvents.forEach((event) => {\n this.responses!.addEvent(event);\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n }\n\n private async fetchResponses(): Promise<void> {\n this._isFetchingResponses = true;\n\n // we want:\n // - stable and unstable M_POLL_RESPONSE\n // - stable and unstable M_POLL_END\n // so make one api call and filter by event type client side\n const allRelations = await this.matrixClient.relations(\n this.roomId,\n this.rootEvent.getId()!,\n \"m.reference\",\n undefined,\n {\n from: this.relationsNextBatch || undefined,\n },\n );\n\n await Promise.all(allRelations.events.map((event) => this.matrixClient.decryptEventIfNeeded(event)));\n\n const responses =\n this.responses ||\n new Relations(\"m.reference\", M_POLL_RESPONSE.name, this.matrixClient, [M_POLL_RESPONSE.altName!]);\n\n const pollEndEvent = allRelations.events.find((event) => M_POLL_END.matches(event.getType()));\n\n if (this.validateEndEvent(pollEndEvent)) {\n this.endEvent = pollEndEvent;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n const pollCloseTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n\n const { responseEvents } = filterResponseRelations(allRelations.events, pollCloseTimestamp);\n\n responseEvents.forEach((event) => {\n responses.addEvent(event);\n });\n\n this.relationsNextBatch = allRelations.nextBatch ?? undefined;\n this.responses = responses;\n this.countUndecryptableEvents(allRelations.events);\n\n // while there are more pages of relations\n // fetch them\n if (this.relationsNextBatch) {\n // don't await\n // we want to return the first page as soon as possible\n this.fetchResponses();\n } else {\n // no more pages\n this._isFetchingResponses = false;\n }\n\n // emit after updating _isFetchingResponses state\n this.emit(PollEvent.Responses, this.responses);\n }\n\n /**\n * Only responses made before the poll ended are valid\n * Refilter after an end event is recieved\n * To ensure responses are valid\n */\n private refilterResponsesOnEnd(): void {\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n this.responses.getRelations().forEach((event) => {\n if (event.getTs() > pollEndTimestamp) {\n this.responses?.removeEvent(event);\n }\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n\n private countUndecryptableEvents = (events: MatrixEvent[]): void => {\n const undecryptableEventIds = events\n .filter((event) => event.isDecryptionFailure())\n .map((event) => event.getId()!);\n\n const previousCount = this.undecryptableRelationsCount;\n this.undecryptableRelationEventIds = new Set([...this.undecryptableRelationEventIds, ...undecryptableEventIds]);\n\n if (this.undecryptableRelationsCount !== previousCount) {\n this.emit(PollEvent.UndecryptableRelations, this.undecryptableRelationsCount);\n }\n };\n\n private validateEndEvent(endEvent?: MatrixEvent): boolean {\n if (!endEvent) {\n return false;\n }\n /**\n * Repeated end events are ignored -\n * only the first (valid) closure event by origin_server_ts is counted.\n */\n if (this.endEvent && this.endEvent.getTs() < endEvent.getTs()) {\n return false;\n }\n\n /**\n * MSC3381\n * If a m.poll.end event is received from someone other than the poll creator or user with permission to redact\n * others' messages in the room, the event must be ignored by clients due to being invalid.\n */\n const roomCurrentState = this.room.currentState;\n const endEventSender = endEvent.getSender();\n return (\n !!endEventSender &&\n (endEventSender === this.rootEvent.getSender() ||\n roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender))\n );\n }\n}\n\n/**\n * Tests whether the event is a start, response or end poll event.\n *\n * @param event - Event to test\n * @returns true if the event is a poll event, else false\n */\nexport const isPollEvent = (event: MatrixEvent): boolean => {\n const eventType = event.getType();\n return M_POLL_START.matches(eventType) || M_POLL_RESPONSE.matches(eventType) || M_POLL_END.matches(eventType);\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,QAAQ,mBAAmB;AAEhD,SAAS,UAAU,EAAE,eAAe,QAAQ,oBAAoB;AAIhE,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,iBAAiB,QAAQ,0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AI,UAAU,CAAC,OAAO,CAAC,SAAS,CAAC;AACjH,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"poll.js","names":[],"sources":["../../src/models/poll.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START } from \"matrix-events-sdk\";\n\nimport { M_POLL_END, M_POLL_RESPONSE } from \"../@types/polls.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { type PollStartEvent } from \"../extensible_events_v1/PollStartEvent.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { Relations } from \"./relations.ts\";\nimport { type Room } from \"./room.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum PollEvent {\n New = \"Poll.new\",\n End = \"Poll.end\",\n Update = \"Poll.update\",\n Responses = \"Poll.Responses\",\n Destroy = \"Poll.Destroy\",\n UndecryptableRelations = \"Poll.UndecryptableRelations\",\n}\n\nexport type PollEventHandlerMap = {\n [PollEvent.Update]: (event: MatrixEvent, poll: Poll) => void;\n [PollEvent.Destroy]: (pollIdentifier: string) => void;\n [PollEvent.End]: () => void;\n [PollEvent.Responses]: (responses: Relations) => void;\n [PollEvent.UndecryptableRelations]: (count: number) => void;\n};\n\nconst filterResponseRelations = (\n relationEvents: MatrixEvent[],\n pollEndTimestamp: number,\n): {\n responseEvents: MatrixEvent[];\n} => {\n const responseEvents = relationEvents.filter((event) => {\n if (event.isDecryptionFailure()) {\n return;\n }\n return (\n M_POLL_RESPONSE.matches(event.getType()) &&\n // From MSC3381:\n // \"Votes sent on or before the end event's timestamp are valid votes\"\n event.getTs() <= pollEndTimestamp\n );\n });\n\n return { responseEvents };\n};\n\nexport class Poll extends TypedEventEmitter<Exclude<PollEvent, PollEvent.New>, PollEventHandlerMap> {\n public readonly roomId: string;\n public readonly pollEvent: PollStartEvent;\n private _isFetchingResponses = false;\n private relationsNextBatch: string | undefined;\n private responses: null | Relations = null;\n private endEvent: MatrixEvent | undefined;\n /**\n * Keep track of undecryptable relations\n * As incomplete result sets affect poll results\n */\n private undecryptableRelationEventIds = new Set<string>();\n\n public constructor(\n public readonly rootEvent: MatrixEvent,\n private matrixClient: MatrixClient,\n private room: Room,\n ) {\n super();\n if (!this.rootEvent.getRoomId() || !this.rootEvent.getId()) {\n throw new Error(\"Invalid poll start event.\");\n }\n this.roomId = this.rootEvent.getRoomId()!;\n this.pollEvent = this.rootEvent.unstableExtensibleEvent as unknown as PollStartEvent;\n }\n\n public get pollId(): string {\n return this.rootEvent.getId()!;\n }\n\n public get endEventId(): string | undefined {\n return this.endEvent?.getId();\n }\n\n public get isEnded(): boolean {\n return !!this.endEvent;\n }\n\n public get isFetchingResponses(): boolean {\n return this._isFetchingResponses;\n }\n\n public get undecryptableRelationsCount(): number {\n return this.undecryptableRelationEventIds.size;\n }\n\n public async getResponses(): Promise<Relations> {\n // if we have already fetched some responses\n // just return them\n if (this.responses) {\n return this.responses;\n }\n\n // if there is no fetching in progress\n // start fetching\n if (!this.isFetchingResponses) {\n await this.fetchResponses();\n }\n // return whatever responses we got from the first page\n return this.responses!;\n }\n\n /**\n *\n * @param event - event with a relation to the rootEvent\n * @returns void\n */\n public onNewRelation(event: MatrixEvent): void {\n if (M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) {\n this.endEvent = event;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n // wait for poll responses to be initialised\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n const { responseEvents } = filterResponseRelations([event], pollEndTimestamp);\n\n this.countUndecryptableEvents([event]);\n\n if (responseEvents.length) {\n responseEvents.forEach((event) => {\n this.responses!.addEvent(event);\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n }\n\n private async fetchResponses(): Promise<void> {\n this._isFetchingResponses = true;\n\n // we want:\n // - stable and unstable M_POLL_RESPONSE\n // - stable and unstable M_POLL_END\n // so make one api call and filter by event type client side\n const allRelations = await this.matrixClient.relations(\n this.roomId,\n this.rootEvent.getId()!,\n \"m.reference\",\n undefined,\n {\n from: this.relationsNextBatch || undefined,\n },\n );\n\n await Promise.all(allRelations.events.map((event) => this.matrixClient.decryptEventIfNeeded(event)));\n\n const responses =\n this.responses ||\n new Relations(\"m.reference\", M_POLL_RESPONSE.name, this.matrixClient, [M_POLL_RESPONSE.altName]);\n\n const pollEndEvent = allRelations.events.find((event) => M_POLL_END.matches(event.getType()));\n\n if (this.validateEndEvent(pollEndEvent)) {\n this.endEvent = pollEndEvent;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n const pollCloseTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n\n const { responseEvents } = filterResponseRelations(allRelations.events, pollCloseTimestamp);\n\n responseEvents.forEach((event) => {\n responses.addEvent(event);\n });\n\n this.relationsNextBatch = allRelations.nextBatch ?? undefined;\n this.responses = responses;\n this.countUndecryptableEvents(allRelations.events);\n\n // while there are more pages of relations\n // fetch them\n if (this.relationsNextBatch) {\n // don't await\n // we want to return the first page as soon as possible\n this.fetchResponses();\n } else {\n // no more pages\n this._isFetchingResponses = false;\n }\n\n // emit after updating _isFetchingResponses state\n this.emit(PollEvent.Responses, this.responses);\n }\n\n /**\n * Only responses made before the poll ended are valid\n * Refilter after an end event is recieved\n * To ensure responses are valid\n */\n private refilterResponsesOnEnd(): void {\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n this.responses.getRelations().forEach((event) => {\n if (event.getTs() > pollEndTimestamp) {\n this.responses?.removeEvent(event);\n }\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n\n private countUndecryptableEvents = (events: MatrixEvent[]): void => {\n const undecryptableEventIds = events\n .filter((event) => event.isDecryptionFailure())\n .map((event) => event.getId()!);\n\n const previousCount = this.undecryptableRelationsCount;\n this.undecryptableRelationEventIds = new Set([...this.undecryptableRelationEventIds, ...undecryptableEventIds]);\n\n if (this.undecryptableRelationsCount !== previousCount) {\n this.emit(PollEvent.UndecryptableRelations, this.undecryptableRelationsCount);\n }\n };\n\n private validateEndEvent(endEvent?: MatrixEvent): boolean {\n if (!endEvent) {\n return false;\n }\n /**\n * Repeated end events are ignored -\n * only the first (valid) closure event by origin_server_ts is counted.\n */\n if (this.endEvent && this.endEvent.getTs() < endEvent.getTs()) {\n return false;\n }\n\n /**\n * MSC3381\n * If a m.poll.end event is received from someone other than the poll creator or user with permission to redact\n * others' messages in the room, the event must be ignored by clients due to being invalid.\n */\n const roomCurrentState = this.room.currentState;\n const endEventSender = endEvent.getSender();\n return (\n !!endEventSender &&\n (endEventSender === this.rootEvent.getSender() ||\n roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender))\n );\n }\n}\n\n/**\n * Tests whether the event is a start, response or end poll event.\n *\n * @param event - Event to test\n * @returns true if the event is a poll event, else false\n */\nexport const isPollEvent = (event: MatrixEvent): boolean => {\n const eventType = event.getType();\n return M_POLL_START.matches(eventType) || M_POLL_RESPONSE.matches(eventType) || M_POLL_END.matches(eventType);\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,QAAQ,mBAAmB;AAEhD,SAAS,UAAU,EAAE,eAAe,QAAQ,oBAAoB;AAIhE,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,iBAAiB,QAAQ,0BAA0B;AAE5D,WAAY,SAAS,0BAAT,SAAS;EAAT,SAAS;EAAT,SAA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]}
@@ -1 +1 @@
1
- {"version":3,"file":"read-receipt.js","names":[],"sources":["../../src/models/read-receipt.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type CachedReceipt,\n MAIN_ROOM_TIMELINE,\n type Receipt,\n type ReceiptCache,\n ReceiptType,\n type WrappedReceipt,\n} from \"../@types/read_receipts.ts\";\nimport { type ListenerMap, TypedEventEmitter } from \"./typed-event-emitter.ts\";\nimport { isSupportedReceiptType } from \"../utils.ts\";\nimport { MatrixEvent } from \"./event.ts\";\nimport { EventType } from \"../@types/event.ts\";\nimport { type EventTimelineSet } from \"./event-timeline-set.ts\";\nimport { MapWithDefault } from \"../utils.ts\";\nimport { NotificationCountType } from \"./room.ts\";\nimport { logger } from \"../logger.ts\";\nimport { inMainTimelineForReceipt, threadIdForReceipt } from \"../client.ts\";\n\n/**\n * Create a synthetic receipt for the given event\n * @param userId - The user ID if the receipt sender\n * @param event - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n * @param unthreaded - the receipt is unthreaded\n * @returns a new event with the synthetic receipt in it\n */\nexport function synthesizeReceipt(\n userId: string,\n event: MatrixEvent,\n receiptType: ReceiptType,\n unthreaded = false,\n): MatrixEvent {\n return new MatrixEvent({\n content: {\n [event.getId()!]: {\n [receiptType]: {\n [userId]: {\n ts: event.getTs(),\n ...(!unthreaded && { thread_id: threadIdForReceipt(event) }),\n },\n },\n },\n },\n type: EventType.Receipt,\n room_id: event.getRoomId(),\n });\n}\n\nconst ReceiptPairRealIndex = 0;\nconst ReceiptPairSyntheticIndex = 1;\n\nexport abstract class ReadReceipt<\n Events extends string,\n Arguments extends ListenerMap<Events>,\n SuperclassArguments extends ListenerMap<any> = Arguments,\n> extends TypedEventEmitter<Events, Arguments, SuperclassArguments> {\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n // Map: receipt type → user Id → receipt\n private receipts = new MapWithDefault<\n string,\n Map<string, [realReceipt: WrappedReceipt | null, syntheticReceipt: WrappedReceipt | null]>\n >(() => new Map());\n private receiptCacheByEventId: ReceiptCache = new Map();\n\n public abstract getUnfilteredTimelineSet(): EventTimelineSet;\n public abstract get timeline(): MatrixEvent[];\n\n /**\n * Gets the latest receipt for a given user in the room\n * @param userId - The id of the user for which we want the receipt\n * @param ignoreSynthesized - Whether to ignore synthesized receipts or not\n * @param receiptType - Optional. The type of the receipt we want to get\n * @returns the latest receipts of the chosen type for the chosen user\n */\n public getReadReceiptForUserId(\n userId: string,\n ignoreSynthesized = false,\n receiptType = ReceiptType.Read,\n ): WrappedReceipt | null {\n const [realReceipt, syntheticReceipt] = this.receipts.get(receiptType)?.get(userId) ?? [null, null];\n if (ignoreSynthesized) {\n return realReceipt;\n }\n\n return syntheticReceipt ?? realReceipt;\n }\n\n private compareReceipts(a: WrappedReceipt, b: WrappedReceipt): number {\n // Try compare them in our unfiltered timeline set order, falling back to receipt timestamp which should be\n // relatively sane as receipts are set only by the originating homeserver so as long as its clock doesn't\n // jump around then it should be valid.\n return this.getUnfilteredTimelineSet().compareEventOrdering(a.eventId, b.eventId) ?? a.data.ts - b.data.ts;\n }\n\n /**\n * Get the ID of the event that a given user has read up to, or null if:\n * - we have received no read receipts for them, or\n * - the receipt we have points at an event we don't have, or\n * - the thread ID in the receipt does not match the thread root of the\n * referenced event.\n *\n * (The event might not exist if it is not loaded, and the thread ID might\n * not match if the event has moved thread because it was redacted.)\n *\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest existing event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized = false): string | null {\n // Find what the latest receipt says is the latest event we have read\n const latestReceipt = this.getLatestReceipt(userId, ignoreSynthesized);\n\n if (!latestReceipt) {\n return null;\n }\n\n return this.receiptPointsAtConsistentEvent(latestReceipt) ? latestReceipt.eventId : null;\n }\n\n /**\n * Returns true if the event pointed at by this receipt exists, and its\n * threadRootId is consistent with the thread information in the receipt.\n */\n private receiptPointsAtConsistentEvent(receipt: WrappedReceipt): boolean {\n const event = this.findEventById(receipt.eventId);\n if (!event) {\n // If the receipt points at a non-existent event, we have multiple\n // possibilities:\n //\n // 1. We don't have the event because it's not loaded yet - probably\n // it's old and we're best off ignoring the receipt - we can just\n // send a new one when we read a new event.\n //\n // 2. We have a bug e.g. we misclassified this event into the wrong\n // thread.\n //\n // 3. The referenced event moved out of this thread (e.g. because it\n // was deleted.)\n //\n // 4. The receipt had the incorrect thread ID (due to a bug in a\n // client, or malicious behaviour).\n\n // This receipt is not \"valid\" because it doesn't point at an event\n // we have. We want to pretend it doesn't exist.\n return false;\n }\n\n if (!receipt.data?.thread_id) {\n // If this is an unthreaded receipt, it could point at any event, so\n // there is no need to validate further - this receipt is valid.\n return true;\n }\n // Otherwise it is a threaded receipt...\n\n if (receipt.data.thread_id === MAIN_ROOM_TIMELINE) {\n // The receipt is for the main timeline: we check that the event is\n // in the main timeline.\n\n // Check if the event is in the main timeline\n const eventIsInMainTimeline = inMainTimelineForReceipt(event);\n\n if (eventIsInMainTimeline) {\n // The receipt is for the main timeline, and so is the event, so\n // the receipt is valid.\n return true;\n }\n } else {\n // The receipt is for a different thread (not the main timeline)\n\n if (event.threadRootId === receipt.data.thread_id) {\n // If the receipt and event agree on the thread ID, the receipt\n // is valid.\n return true;\n }\n }\n\n // The receipt thread ID disagrees with the event thread ID. There are 2\n // possibilities:\n //\n // 1. The event moved to a different thread after the receipt was\n // created. This can happen if the event was redacted because that\n // moves it to the main timeline.\n //\n // 2. There is a bug somewhere - either we put the event into the wrong\n // thread, or someone sent an incorrect receipt.\n //\n // In many cases, we won't get here because the call to findEventById\n // would have already returned null. We include this check to cover\n // cases when `this` is a room, meaning findEventById will find events\n // in any thread, and to be defensive against unforeseen code paths.\n logger.warn(\n `Ignoring receipt because its thread_id (${receipt.data.thread_id}) disagrees ` +\n `with the thread root (${event.threadRootId}) of the referenced event ` +\n `(event ID = ${receipt.eventId})`,\n );\n\n // This receipt is not \"valid\" because it disagrees with us about what\n // thread the event is in. We want to pretend it doesn't exist.\n return false;\n }\n\n private getLatestReceipt(userId: string, ignoreSynthesized: boolean): WrappedReceipt | null {\n // XXX: This is very very ugly and I hope I won't have to ever add a new\n // receipt type here again. IMHO this should be done by the server in\n // some more intelligent manner or the client should just use timestamps\n\n const publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);\n const privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);\n\n // If we have both, compare them\n let comparison: number | null | undefined;\n if (publicReadReceipt?.eventId && privateReadReceipt?.eventId) {\n comparison = this.compareReceipts(publicReadReceipt, privateReadReceipt);\n }\n\n // The public receipt is more likely to drift out of date so the private\n // one has precedence\n if (!comparison) return privateReadReceipt ?? publicReadReceipt ?? null;\n\n // If public read receipt is older, return the private one\n return (comparison < 0 ? privateReadReceipt : publicReadReceipt) ?? null;\n }\n\n public addReceiptToStructure(\n eventId: string,\n receiptType: ReceiptType,\n userId: string,\n receipt: Receipt,\n synthetic: boolean,\n ): void {\n const receiptTypesMap = this.receipts.getOrCreate(receiptType);\n let pair = receiptTypesMap.get(userId);\n\n if (!pair) {\n pair = [null, null];\n receiptTypesMap.set(userId, pair);\n }\n\n let existingReceipt = pair[ReceiptPairRealIndex];\n if (synthetic) {\n existingReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n }\n\n const wrappedReceipt: WrappedReceipt = {\n eventId,\n data: receipt,\n };\n\n if (existingReceipt) {\n // We only want to add this receipt if we think it is later than the one we already have.\n // This is managed server-side, but because we synthesize RRs locally we have to do it here too.\n const ordering = this.compareReceipts(existingReceipt, wrappedReceipt);\n if (ordering >= 0) {\n return;\n }\n }\n\n const realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt;\n const syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex];\n\n let ordering: number | null = null;\n if (realReceipt && syntheticReceipt) {\n ordering = this.getUnfilteredTimelineSet().compareEventOrdering(\n realReceipt.eventId,\n syntheticReceipt.eventId,\n );\n }\n\n const preferSynthetic = ordering === null || ordering < 0;\n\n // we don't bother caching just real receipts by event ID as there's nothing that would read it.\n // Take the current cached receipt before we overwrite the pair elements.\n const cachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n\n if (synthetic && preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = wrappedReceipt;\n } else if (!synthetic) {\n pair[ReceiptPairRealIndex] = wrappedReceipt;\n\n if (!preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = null;\n }\n }\n\n const newCachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n if (cachedReceipt === newCachedReceipt) return;\n\n // clean up any previous cache entry\n if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) {\n const previousEventId = cachedReceipt.eventId;\n // Remove the receipt we're about to clobber out of existence from the cache\n this.receiptCacheByEventId.set(\n previousEventId,\n this.receiptCacheByEventId.get(previousEventId)!.filter((r) => {\n return r.type !== receiptType || r.userId !== userId;\n }),\n );\n\n if (this.receiptCacheByEventId.get(previousEventId)!.length < 1) {\n this.receiptCacheByEventId.delete(previousEventId); // clean up the cache keys\n }\n }\n\n // cache the new one\n if (!this.receiptCacheByEventId.get(eventId)) {\n this.receiptCacheByEventId.set(eventId, []);\n }\n this.receiptCacheByEventId.get(eventId)!.push({\n userId: userId,\n type: receiptType as ReceiptType,\n data: receipt,\n });\n }\n\n /**\n * Get a list of receipts for the given event.\n * @param event - the event to get receipts for\n * @returns A list of receipts with a userId, type and data keys or\n * an empty list.\n */\n public getReceiptsForEvent(event: MatrixEvent): CachedReceipt[] {\n return this.receiptCacheByEventId.get(event.getId()!) || [];\n }\n\n public abstract addReceipt(event: MatrixEvent, synthetic: boolean): void;\n\n public abstract setUnread(type: NotificationCountType, count: number): void;\n\n /**\n * Look in this room/thread's timeline to find an event. If `this` is a\n * room, we look in all threads, but if `this` is a thread, we look only\n * inside this thread.\n */\n public abstract findEventById(eventId: string): MatrixEvent | undefined;\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * Retrieves the read receipt for the logged in user and checks if it matches\n * the last event in the room and whether that event originated from the logged\n * in user.\n * Under those conditions we can consider the context as read. This is useful\n * because we never send read receipts against our own events\n * @param userId - the logged in user\n */\n public fixupNotifications(userId: string): void {\n const receipt = this.getReadReceiptForUserId(userId, false);\n\n const lastEvent = this.timeline[this.timeline.length - 1];\n if (lastEvent && receipt?.eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n this.setUnread(NotificationCountType.Total, 0);\n this.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n\n /**\n * Add a temporary local-echo receipt to the room to reflect in the\n * client the fact that we've sent one.\n * @param userId - The user ID if the receipt sender\n * @param e - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n * @param unthreaded - the receipt is unthreaded\n */\n public addLocalEchoReceipt(userId: string, e: MatrixEvent, receiptType: ReceiptType, unthreaded = false): void {\n this.addReceipt(synthesizeReceipt(userId, e, receiptType, unthreaded), true);\n }\n\n /**\n * Get a list of user IDs who have <b>read up to</b> the given event.\n * @param event - the event to get read receipts for.\n * @returns A list of user IDs.\n */\n public getUsersReadUpTo(event: MatrixEvent): string[] {\n return this.getReceiptsForEvent(event)\n .filter(function (receipt) {\n return isSupportedReceiptType(receipt.type);\n })\n .map(function (receipt) {\n return receipt.userId;\n });\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public abstract hasUserReadEvent(userId: string, eventId: string): boolean;\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n *\n * @deprecated use `hasUserReadEvent` or `getEventReadUpTo` instead\n */\n public abstract getLastUnthreadedReceiptFor(userId: string): Receipt | undefined;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEI,kBAAkB,EAGlB,WAAW,QAER,4BAA4B;AACnC,SAA2B,iBAAiB,QAAQ,0BAA0B;AAC9E,SAAS,sBAAsB,QAAQ,aAAa;AACpD,SAAS,WAAW,QAAQ,YAAY;AACxC,SAAS,SAAS,QAAQ,oBAAoB;AAE9C,SAAS,cAAc,QAAQ,aAAa;AAC5C,SAAS,qBAAqB,QAAQ,WAAW;AACjD,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,wBAAwB,EAAE,kBAAkB,QAAQ,cAAc;;AAE3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,iBAAiB,CAC7B,MAAc,EACd,KAAkB,EAClB,WAAwB,EACxB,UAAU,GAAG,KAAK,EACP;EACX,OAAO,IAAI,WAAW,CAAC;IACnB,OAAO,EAAE;MACL,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,GAAI;QACd,CAAC,WAAW,GAAG;UACX,CAAC,MAAM;YACH,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC;UAAC,GACb,CAAC,UAAU,IAA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BAAqB,CAAC,KAAK,EAAE,CAAC,CAAC;MAC9C,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAAC,SAAS,EAAE,CAAC,CAAC;IACtD;EACJ;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACW,mBAAmB,CAAC,MAAc,EAAE,CAAc,EAAE,WAAwB,EAAE,UAAU,GAAG,KAAK,EAAQ;IAC3G,IAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,MAAM,EAAE,CAAC,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE,IAAI,CAAC;EAChF;;EAEA;AACJ;AACA;AACA;AACA;EACW,gBAAgB,CAAC,KAAkB,EAAY;IAClD,OAAO,IAAI,CAAC,mBAAmB,CAAC,KAAK,CAAC,CACjC,MAAM,CAAC,UAAU,OAAO,EAAE;MACvB,OAAO,sBAAsB,CAAC,OAAO,CAAC,IAAI,CAAC;IAC/C,CAAC,CAAC,CACD,GAAG,CAAC,UAAU,OAAO,EAAE;MACpB,OAAO,OAAO,CAAC,MAAM;IACzB,CAAC,CAAC;EACV;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;EAGI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA","ignoreList":[]}
1
+ {"version":3,"file":"read-receipt.js","names":[],"sources":["../../src/models/read-receipt.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type CachedReceipt,\n MAIN_ROOM_TIMELINE,\n type Receipt,\n type ReceiptCache,\n ReceiptType,\n type WrappedReceipt,\n} from \"../@types/read_receipts.ts\";\nimport { type ListenerMap, TypedEventEmitter } from \"./typed-event-emitter.ts\";\nimport { isSupportedReceiptType } from \"../utils.ts\";\nimport { MatrixEvent } from \"./event.ts\";\nimport { EventType } from \"../@types/event.ts\";\nimport { type EventTimelineSet } from \"./event-timeline-set.ts\";\nimport { MapWithDefault } from \"../utils.ts\";\nimport { NotificationCountType } from \"./room.ts\";\nimport { logger } from \"../logger.ts\";\nimport { inMainTimelineForReceipt, threadIdForReceipt } from \"../client.ts\";\n\n/**\n * Create a synthetic receipt for the given event\n * @param userId - The user ID if the receipt sender\n * @param event - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n * @param unthreaded - the receipt is unthreaded\n * @returns a new event with the synthetic receipt in it\n */\nexport function synthesizeReceipt(\n userId: string,\n event: MatrixEvent,\n receiptType: ReceiptType,\n unthreaded = false,\n): MatrixEvent {\n return new MatrixEvent({\n content: {\n [event.getId()!]: {\n [receiptType]: {\n [userId]: {\n ts: event.getTs(),\n ...(!unthreaded && { thread_id: threadIdForReceipt(event) }),\n },\n },\n },\n },\n type: EventType.Receipt,\n room_id: event.getRoomId(),\n });\n}\n\nconst ReceiptPairRealIndex = 0;\nconst ReceiptPairSyntheticIndex = 1;\n\nexport abstract class ReadReceipt<\n Events extends string,\n Arguments extends ListenerMap<Events>,\n SuperclassArguments extends ListenerMap<any> = Arguments,\n> extends TypedEventEmitter<Events, Arguments, SuperclassArguments> {\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n // Map: receipt type → user Id → receipt\n private receipts = new MapWithDefault<\n string,\n Map<string, [realReceipt: WrappedReceipt | null, syntheticReceipt: WrappedReceipt | null]>\n >(() => new Map());\n private receiptCacheByEventId: ReceiptCache = new Map();\n\n public abstract getUnfilteredTimelineSet(): EventTimelineSet;\n public abstract get timeline(): MatrixEvent[];\n\n /**\n * Gets the latest receipt for a given user in the room\n * @param userId - The id of the user for which we want the receipt\n * @param ignoreSynthesized - Whether to ignore synthesized receipts or not\n * @param receiptType - Optional. The type of the receipt we want to get\n * @returns the latest receipts of the chosen type for the chosen user\n */\n public getReadReceiptForUserId(\n userId: string,\n ignoreSynthesized = false,\n receiptType = ReceiptType.Read,\n ): WrappedReceipt | null {\n const [realReceipt, syntheticReceipt] = this.receipts.get(receiptType)?.get(userId) ?? [null, null];\n if (ignoreSynthesized) {\n return realReceipt;\n }\n\n return syntheticReceipt ?? realReceipt;\n }\n\n private compareReceipts(a: WrappedReceipt, b: WrappedReceipt): number {\n // Try compare them in our unfiltered timeline set order, falling back to receipt timestamp which should be\n // relatively sane as receipts are set only by the originating homeserver so as long as its clock doesn't\n // jump around then it should be valid.\n return this.getUnfilteredTimelineSet().compareEventOrdering(a.eventId, b.eventId) ?? a.data.ts - b.data.ts;\n }\n\n /**\n * Get the ID of the event that a given user has read up to, or null if:\n * - we have received no read receipts for them, or\n * - the receipt we have points at an event we don't have, or\n * - the thread ID in the receipt does not match the thread root of the\n * referenced event.\n *\n * (The event might not exist if it is not loaded, and the thread ID might\n * not match if the event has moved thread because it was redacted.)\n *\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest existing event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized = false): string | null {\n // Find what the latest receipt says is the latest event we have read\n const latestReceipt = this.getLatestReceipt(userId, ignoreSynthesized);\n\n if (!latestReceipt) {\n return null;\n }\n\n return this.receiptPointsAtConsistentEvent(latestReceipt) ? latestReceipt.eventId : null;\n }\n\n /**\n * Returns true if the event pointed at by this receipt exists, and its\n * threadRootId is consistent with the thread information in the receipt.\n */\n private receiptPointsAtConsistentEvent(receipt: WrappedReceipt): boolean {\n const event = this.findEventById(receipt.eventId);\n if (!event) {\n // If the receipt points at a non-existent event, we have multiple\n // possibilities:\n //\n // 1. We don't have the event because it's not loaded yet - probably\n // it's old and we're best off ignoring the receipt - we can just\n // send a new one when we read a new event.\n //\n // 2. We have a bug e.g. we misclassified this event into the wrong\n // thread.\n //\n // 3. The referenced event moved out of this thread (e.g. because it\n // was deleted.)\n //\n // 4. The receipt had the incorrect thread ID (due to a bug in a\n // client, or malicious behaviour).\n\n // This receipt is not \"valid\" because it doesn't point at an event\n // we have. We want to pretend it doesn't exist.\n return false;\n }\n\n if (!receipt.data?.thread_id) {\n // If this is an unthreaded receipt, it could point at any event, so\n // there is no need to validate further - this receipt is valid.\n return true;\n }\n // Otherwise it is a threaded receipt...\n\n if (receipt.data.thread_id === MAIN_ROOM_TIMELINE) {\n // The receipt is for the main timeline: we check that the event is\n // in the main timeline.\n\n // Check if the event is in the main timeline\n const eventIsInMainTimeline = inMainTimelineForReceipt(event);\n\n if (eventIsInMainTimeline) {\n // The receipt is for the main timeline, and so is the event, so\n // the receipt is valid.\n return true;\n }\n } else {\n // The receipt is for a different thread (not the main timeline)\n\n if (event.threadRootId === receipt.data.thread_id) {\n // If the receipt and event agree on the thread ID, the receipt\n // is valid.\n return true;\n }\n }\n\n // The receipt thread ID disagrees with the event thread ID. There are 2\n // possibilities:\n //\n // 1. The event moved to a different thread after the receipt was\n // created. This can happen if the event was redacted because that\n // moves it to the main timeline.\n //\n // 2. There is a bug somewhere - either we put the event into the wrong\n // thread, or someone sent an incorrect receipt.\n //\n // In many cases, we won't get here because the call to findEventById\n // would have already returned null. We include this check to cover\n // cases when `this` is a room, meaning findEventById will find events\n // in any thread, and to be defensive against unforeseen code paths.\n logger.warn(\n `Ignoring receipt because its thread_id (${receipt.data.thread_id}) disagrees ` +\n `with the thread root (${event.threadRootId}) of the referenced event ` +\n `(event ID = ${receipt.eventId})`,\n );\n\n // This receipt is not \"valid\" because it disagrees with us about what\n // thread the event is in. We want to pretend it doesn't exist.\n return false;\n }\n\n private getLatestReceipt(userId: string, ignoreSynthesized: boolean): WrappedReceipt | null {\n // XXX: This is very very ugly and I hope I won't have to ever add a new\n // receipt type here again. IMHO this should be done by the server in\n // some more intelligent manner or the client should just use timestamps\n\n const publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);\n const privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);\n\n // If we have both, compare them\n let comparison: number | null | undefined;\n if (publicReadReceipt?.eventId && privateReadReceipt?.eventId) {\n comparison = this.compareReceipts(publicReadReceipt, privateReadReceipt);\n }\n\n // The public receipt is more likely to drift out of date so the private\n // one has precedence\n if (!comparison) return privateReadReceipt ?? publicReadReceipt ?? null;\n\n // If public read receipt is older, return the private one\n return (comparison < 0 ? privateReadReceipt : publicReadReceipt) ?? null;\n }\n\n public addReceiptToStructure(\n eventId: string,\n receiptType: ReceiptType,\n userId: string,\n receipt: Receipt,\n synthetic: boolean,\n ): void {\n const receiptTypesMap = this.receipts.getOrCreate(receiptType);\n let pair = receiptTypesMap.get(userId);\n\n if (!pair) {\n pair = [null, null];\n receiptTypesMap.set(userId, pair);\n }\n\n let existingReceipt = pair[ReceiptPairRealIndex];\n if (synthetic) {\n existingReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n }\n\n const wrappedReceipt: WrappedReceipt = {\n eventId,\n data: receipt,\n };\n\n if (existingReceipt) {\n // We only want to add this receipt if we think it is later than the one we already have.\n // This is managed server-side, but because we synthesize RRs locally we have to do it here too.\n const ordering = this.compareReceipts(existingReceipt, wrappedReceipt);\n if (ordering >= 0) {\n return;\n }\n }\n\n const realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt;\n const syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex];\n\n let ordering: number | null = null;\n if (realReceipt && syntheticReceipt) {\n ordering = this.getUnfilteredTimelineSet().compareEventOrdering(\n realReceipt.eventId,\n syntheticReceipt.eventId,\n );\n }\n\n const preferSynthetic = ordering === null || ordering < 0;\n\n // we don't bother caching just real receipts by event ID as there's nothing that would read it.\n // Take the current cached receipt before we overwrite the pair elements.\n const cachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n\n if (synthetic && preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = wrappedReceipt;\n } else if (!synthetic) {\n pair[ReceiptPairRealIndex] = wrappedReceipt;\n\n if (!preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = null;\n }\n }\n\n const newCachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n if (cachedReceipt === newCachedReceipt) return;\n\n // clean up any previous cache entry\n if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) {\n const previousEventId = cachedReceipt.eventId;\n // Remove the receipt we're about to clobber out of existence from the cache\n this.receiptCacheByEventId.set(\n previousEventId,\n this.receiptCacheByEventId.get(previousEventId)!.filter((r) => {\n return r.type !== receiptType || r.userId !== userId;\n }),\n );\n\n if (this.receiptCacheByEventId.get(previousEventId)!.length < 1) {\n this.receiptCacheByEventId.delete(previousEventId); // clean up the cache keys\n }\n }\n\n // cache the new one\n if (!this.receiptCacheByEventId.get(eventId)) {\n this.receiptCacheByEventId.set(eventId, []);\n }\n this.receiptCacheByEventId.get(eventId)!.push({\n userId: userId,\n type: receiptType,\n data: receipt,\n });\n }\n\n /**\n * Get a list of receipts for the given event.\n * @param event - the event to get receipts for\n * @returns A list of receipts with a userId, type and data keys or\n * an empty list.\n */\n public getReceiptsForEvent(event: MatrixEvent): CachedReceipt[] {\n return this.receiptCacheByEventId.get(event.getId()!) || [];\n }\n\n public abstract addReceipt(event: MatrixEvent, synthetic: boolean): void;\n\n public abstract setUnread(type: NotificationCountType, count: number): void;\n\n /**\n * Look in this room/thread's timeline to find an event. If `this` is a\n * room, we look in all threads, but if `this` is a thread, we look only\n * inside this thread.\n */\n public abstract findEventById(eventId: string): MatrixEvent | undefined;\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * Retrieves the read receipt for the logged in user and checks if it matches\n * the last event in the room and whether that event originated from the logged\n * in user.\n * Under those conditions we can consider the context as read. This is useful\n * because we never send read receipts against our own events\n * @param userId - the logged in user\n */\n public fixupNotifications(userId: string): void {\n const receipt = this.getReadReceiptForUserId(userId, false);\n\n const lastEvent = this.timeline[this.timeline.length - 1];\n if (lastEvent && receipt?.eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n this.setUnread(NotificationCountType.Total, 0);\n this.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n\n /**\n * Add a temporary local-echo receipt to the room to reflect in the\n * client the fact that we've sent one.\n * @param userId - The user ID if the receipt sender\n * @param e - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n * @param unthreaded - the receipt is unthreaded\n */\n public addLocalEchoReceipt(userId: string, e: MatrixEvent, receiptType: ReceiptType, unthreaded = false): void {\n this.addReceipt(synthesizeReceipt(userId, e, receiptType, unthreaded), true);\n }\n\n /**\n * Get a list of user IDs who have <b>read up to</b> the given event.\n * @param event - the event to get read receipts for.\n * @returns A list of user IDs.\n */\n public getUsersReadUpTo(event: MatrixEvent): string[] {\n return this.getReceiptsForEvent(event)\n .filter(function (receipt) {\n return isSupportedReceiptType(receipt.type);\n })\n .map(function (receipt) {\n return receipt.userId;\n });\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public abstract hasUserReadEvent(userId: string, eventId: string): boolean;\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n *\n * @deprecated use `hasUserReadEvent` or `getEventReadUpTo` instead\n */\n public abstract getLastUnthreadedReceiptFor(userId: string): Receipt | und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AC,UAAU,OAAO,EAAE;MACvB,OAAO,sBAAsB,CAAC,OAAO,CAAC,IAAI,CAAC;IAC/C,CAAC,CAAC,CACD,GAAG,CAAC,UAAU,OAAO,EAAE;MACpB,OAAO,OAAO,CAAC,MAAM;IACzB,CAAC,CAAC;EACV;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;EAGI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA","ignoreList":[]}
@@ -40,5 +40,15 @@ export declare class RelationsContainer {
40
40
  * @param timelineSet - The event timeline set within which to search for the related event if any.
41
41
  */
42
42
  aggregateChildEvent(event: MatrixEvent, timelineSet?: EventTimelineSet): void;
43
+ /**
44
+ * Add a relation event using a known target that is not in the timeline yet.
45
+ *
46
+ * @param event - The new child event to be aggregated.
47
+ * @param timelineSet - The event timeline set within which to search for the related event.
48
+ * @param targetEvent - The known relation target.
49
+ * @returns A promise which resolves after aggregation.
50
+ */
51
+ aggregateChildEvent(event: MatrixEvent, timelineSet: EventTimelineSet, targetEvent: MatrixEvent): Promise<void>;
52
+ private aggregateChildEventInternal;
43
53
  }
44
54
  //# sourceMappingURL=relations-container.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"relations-container.d.ts","sourceRoot":"","sources":["../../src/models/relations-container.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAe,KAAK,WAAW,EAAoB,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,qBAAa,kBAAkB;IAMvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,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IACI,sBAAsB,CACzB,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,YAAY,GAAG,MAAM,EACnC,SAAS,EAAE,SAAS,GAAG,MAAM,GAC9B,SAAS,GAAG,SAAS,CAEvB;IAEM,yBAAyB,CAAC,aAAa,EAAE,MAAM,GAAG,WAAW,EAAE,CAUrE;IAED;;;;;;OAMG;IACI,oBAAoB,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CASpD;IAED;;;;;OAKG;IACI,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE,WAAW,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACrF;;;;;;;OAOG;IACI,mBAAmB,CACtB,KAAK,EAAE,WAAW,EAClB,WAAW,EAAE,gBAAgB,EAC7B,WAAW,EAAE,WAAW,GACzB,OAAO,CAAC,IAAI,CAAC,CAAC;IAYjB,OAAO,CAAC,2BAA2B;CAmEtC"}
@@ -17,6 +17,7 @@ limitations under the License.
17
17
 
18
18
  import { Relations } from "./relations.js";
19
19
  import { EventStatus, MatrixEventEvent } from "./event.js";
20
+ import { logger } from "../logger.js";
20
21
  export class RelationsContainer {
21
22
  constructor(client, room) {
22
23
  // A tree of objects to access a set of related children for an event, as in:
@@ -77,26 +78,42 @@ export class RelationsContainer {
77
78
  * @param event - The new child event to be aggregated.
78
79
  * @param timelineSet - The event timeline set within which to search for the related event if any.
79
80
  */
80
- aggregateChildEvent(event, timelineSet) {
81
+
82
+ /**
83
+ * Add a relation event using a known target that is not in the timeline yet.
84
+ *
85
+ * @param event - The new child event to be aggregated.
86
+ * @param timelineSet - The event timeline set within which to search for the related event.
87
+ * @param targetEvent - The known relation target.
88
+ * @returns A promise which resolves after aggregation.
89
+ */
90
+
91
+ aggregateChildEvent(event, timelineSet, targetEvent) {
92
+ const aggregation = this.aggregateChildEventInternal(event, timelineSet, targetEvent);
93
+ if (targetEvent) return aggregation;
94
+ void aggregation.catch(error => logger.error("Failed to aggregate child event: ", error));
95
+ }
96
+ aggregateChildEventInternal(event, timelineSet, targetEvent) {
81
97
  if (event.isRedacted() || event.status === EventStatus.CANCELLED) {
82
- return;
98
+ return Promise.resolve();
83
99
  }
84
100
  const relation = event.getRelation();
85
- if (!relation) return;
86
- const onEventDecrypted = () => {
87
- if (event.isDecryptionFailure()) {
88
- // This could for example happen if the encryption keys are not yet available.
89
- // The event may still be decrypted later. Register the listener again.
90
- event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
91
- return;
92
- }
93
- this.aggregateChildEvent(event, timelineSet);
94
- };
101
+ if (!relation) return Promise.resolve();
95
102
 
96
103
  // If the event is currently encrypted, wait until it has been decrypted.
97
104
  if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
98
- event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
99
- return;
105
+ return new Promise((resolve, reject) => {
106
+ const onEventDecrypted = () => {
107
+ if (event.isDecryptionFailure()) {
108
+ // This could for example happen if the encryption keys are not yet available.
109
+ // The event may still be decrypted later. Register the listener again.
110
+ event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
111
+ return;
112
+ }
113
+ void this.aggregateChildEventInternal(event, timelineSet, targetEvent).then(resolve, reject);
114
+ };
115
+ event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
116
+ });
100
117
  }
101
118
  const {
102
119
  event_id: relatesToEventId,
@@ -114,16 +131,21 @@ export class RelationsContainer {
114
131
  relationsForEvent.set(relationType, relationsWithRelType);
115
132
  }
116
133
  let relationsWithEventType = relationsWithRelType.get(eventType);
134
+ const isNewRelationCollection = !relationsWithEventType;
135
+ let targetEventUpdate = Promise.resolve();
117
136
  if (!relationsWithEventType) {
118
137
  relationsWithEventType = new Relations(relationType, eventType, this.client);
119
138
  relationsWithRelType.set(eventType, relationsWithEventType);
139
+ }
140
+ if (isNewRelationCollection || targetEvent) {
120
141
  const room = this.room ?? timelineSet?.room;
121
- const relatesToEvent = timelineSet?.findEventById(relatesToEventId) ?? room?.findEventById(relatesToEventId) ?? room?.getPendingEvent(relatesToEventId);
142
+ const relatesToEvent = timelineSet?.findEventById(relatesToEventId) ?? room?.findEventById(relatesToEventId) ?? room?.getPendingEvent(relatesToEventId) ?? targetEvent;
122
143
  if (relatesToEvent) {
123
- relationsWithEventType.setTargetEvent(relatesToEvent);
144
+ targetEventUpdate = relationsWithEventType.setTargetEvent(relatesToEvent);
124
145
  }
125
146
  }
126
- relationsWithEventType.addEvent(event);
147
+ const addEventUpdate = relationsWithEventType.addEvent(event);
148
+ return Promise.all([targetEventUpdate, addEventUpdate]).then(() => undefined);
127
149
  }
128
150
  }
129
151
  //# sourceMappingURL=relations-container.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"relations-container.js","names":[],"sources":["../../src/models/relations-container.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Relations } from \"./relations.ts\";\nimport { type EventType, type RelationType } from \"../@types/event.ts\";\nimport { EventStatus, type MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { type EventTimelineSet } from \"./event-timeline-set.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { type Room } from \"./room.ts\";\n\nexport class RelationsContainer {\n // A tree of objects to access a set of related children for an event, as in:\n // this.relations.get(parentEventId).get(relationType).get(relationEventType)\n private relations = new Map<string, Map<RelationType | string, Map<EventType | string, Relations>>>();\n\n public constructor(\n private readonly client: MatrixClient,\n private readonly room?: Room,\n ) {}\n\n /**\n * Get a collection of child events to a given event in this timeline set.\n *\n * @param eventId - The ID of the event that you'd like to access child events for.\n * For example, with annotations, this would be the ID of the event being annotated.\n * @param relationType - The type of relationship involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @throws If `eventId</code>, <code>relationType</code> or <code>eventType`\n * are not valid.\n *\n * @returns\n * A container for relation events or undefined if there are no relation events for\n * the relationType.\n */\n public getChildEventsForEvent(\n eventId: string,\n relationType: RelationType | string,\n eventType: EventType | string,\n ): Relations | undefined {\n return this.relations.get(eventId)?.get(relationType)?.get(eventType);\n }\n\n public getAllChildEventsForEvent(parentEventId: string): MatrixEvent[] {\n const relationsForEvent =\n this.relations.get(parentEventId) ?? new Map<RelationType | string, Map<EventType | string, Relations>>();\n const events: MatrixEvent[] = [];\n for (const relationsRecord of relationsForEvent.values()) {\n for (const relations of relationsRecord.values()) {\n events.push(...relations.getRelations());\n }\n }\n return events;\n }\n\n /**\n * Set an event as the target event if any Relations exist for it already.\n * Child events can point to other child events as their parent, so this method may be\n * called for events which are also logically child events.\n *\n * @param event - The event to check as relation target.\n */\n public aggregateParentEvent(event: MatrixEvent): void {\n const relationsForEvent = this.relations.get(event.getId()!);\n if (!relationsForEvent) return;\n\n for (const relationsWithRelType of relationsForEvent.values()) {\n for (const relationsWithEventType of relationsWithRelType.values()) {\n relationsWithEventType.setTargetEvent(event);\n }\n }\n }\n\n /**\n * Add relation events to the relevant relation collection.\n *\n * @param event - The new child event to be aggregated.\n * @param timelineSet - The event timeline set within which to search for the related event if any.\n */\n public aggregateChildEvent(event: MatrixEvent, timelineSet?: EventTimelineSet): void {\n if (event.isRedacted() || event.status === EventStatus.CANCELLED) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) return;\n\n const onEventDecrypted = (): void => {\n if (event.isDecryptionFailure()) {\n // This could for example happen if the encryption keys are not yet available.\n // The event may still be decrypted later. Register the listener again.\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n return;\n }\n\n this.aggregateChildEvent(event, timelineSet);\n };\n\n // If the event is currently encrypted, wait until it has been decrypted.\n if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n return;\n }\n\n const { event_id: relatesToEventId, rel_type: relationType } = relation;\n const eventType = event.getType();\n\n let relationsForEvent = this.relations.get(relatesToEventId!);\n if (!relationsForEvent) {\n relationsForEvent = new Map<RelationType | string, Map<EventType | string, Relations>>();\n this.relations.set(relatesToEventId!, relationsForEvent);\n }\n\n let relationsWithRelType = relationsForEvent.get(relationType!);\n if (!relationsWithRelType) {\n relationsWithRelType = new Map<EventType | string, Relations>();\n relationsForEvent.set(relationType!, relationsWithRelType);\n }\n\n let relationsWithEventType = relationsWithRelType.get(eventType);\n if (!relationsWithEventType) {\n relationsWithEventType = new Relations(relationType!, eventType, this.client);\n relationsWithRelType.set(eventType, relationsWithEventType);\n\n const room = this.room ?? timelineSet?.room;\n const relatesToEvent =\n timelineSet?.findEventById(relatesToEventId!) ??\n room?.findEventById(relatesToEventId!) ??\n room?.getPendingEvent(relatesToEventId!);\n if (relatesToEvent) {\n relationsWithEventType.setTargetEvent(relatesToEvent);\n }\n }\n\n relationsWithEventType.addEvent(event);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,WAAW,EAAoB,gBAAgB,QAAQ,YAAY;AAK5E,OAAO,MAAM,kBAAkB,CAAC;EAKrB,WAAW,CACG,MAAoB,EACpB,IAAW,EAC9B;IAPF;IACA;IAAA,mCACoB,IAAI,GAAG,CAAyE,CAAC;IAAA,KAGhF,MAAoB,GAApB,MAAoB;IAAA,KACpB,IAAW,GAAX,IAAW;EAC7B;;EAEH;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,sBAAsB,CACzB,OAAe,EACf,YAAmC,EACnC,SAA6B,EACR;IACrB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC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I,CAAC,IAAI,IAAI,WAAW,EAAE,IAAI;MAC3C,MAAM,cAAc,GAChB,WAAW,EAAE,aAAa,CAAC,gBAAiB,CAAC,IAC7C,IAAI,EAAE,aAAa,CAAC,gBAAiB,CAAC,IACtC,IAAI,EAAE,eAAe,CAAC,gBAAiB,CAAC;MAC5C,IAAI,cAAc,EAAE;QAChB,sBAAsB,CAAC,cAAc,CAAC,cAAc,CAAC;MACzD;IACJ;IAEA,sBAAsB,CAAC,QAAQ,CAAC,KAAK,CAAC;EAC1C;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"relations-container.js","names":[],"sources":["../../src/models/relations-container.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Relations } from \"./relations.ts\";\nimport { type EventType, type RelationType } from \"../@types/event.ts\";\nimport { EventStatus, type MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { type EventTimelineSet } from \"./event-timeline-set.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { type Room } from \"./room.ts\";\nimport { logger } from \"../logger.ts\";\n\nexport class RelationsContainer {\n // A tree of objects to access a set of related children for an event, as in:\n // this.relations.get(parentEventId).get(relationType).get(relationEventType)\n private relations = new Map<string, Map<RelationType | string, Map<EventType | string, Relations>>>();\n\n public constructor(\n private readonly client: MatrixClient,\n private readonly room?: Room,\n ) {}\n\n /**\n * Get a collection of child events to a given event in this timeline set.\n *\n * @param eventId - The ID of the event that you'd like to access child events for.\n * For example, with annotations, this would be the ID of the event being annotated.\n * @param relationType - The type of relationship involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @throws If `eventId</code>, <code>relationType</code> or <code>eventType`\n * are not valid.\n *\n * @returns\n * A container for relation events or undefined if there are no relation events for\n * the relationType.\n */\n public getChildEventsForEvent(\n eventId: string,\n relationType: RelationType | string,\n eventType: EventType | string,\n ): Relations | undefined {\n return this.relations.get(eventId)?.get(relationType)?.get(eventType);\n }\n\n public getAllChildEventsForEvent(parentEventId: string): MatrixEvent[] {\n const relationsForEvent =\n this.relations.get(parentEventId) ?? new Map<RelationType | string, Map<EventType | string, Relations>>();\n const events: MatrixEvent[] = [];\n for (const relationsRecord of relationsForEvent.values()) {\n for (const relations of relationsRecord.values()) {\n events.push(...relations.getRelations());\n }\n }\n return events;\n }\n\n /**\n * Set an event as the target event if any Relations exist for it already.\n * Child events can point to other child events as their parent, so this method may be\n * called for events which are also logically child events.\n *\n * @param event - The event to check as relation target.\n */\n public aggregateParentEvent(event: MatrixEvent): void {\n const relationsForEvent = this.relations.get(event.getId()!);\n if (!relationsForEvent) return;\n\n for (const relationsWithRelType of relationsForEvent.values()) {\n for (const relationsWithEventType of relationsWithRelType.values()) {\n relationsWithEventType.setTargetEvent(event);\n }\n }\n }\n\n /**\n * Add relation events to the relevant relation collection.\n *\n * @param event - The new child event to be aggregated.\n * @param timelineSet - The event timeline set within which to search for the related event if any.\n */\n public aggregateChildEvent(event: MatrixEvent, timelineSet?: EventTimelineSet): void;\n /**\n * Add a relation event using a known target that is not in the timeline yet.\n *\n * @param event - The new child event to be aggregated.\n * @param timelineSet - The event timeline set within which to search for the related event.\n * @param targetEvent - The known relation target.\n * @returns A promise which resolves after aggregation.\n */\n public aggregateChildEvent(\n event: MatrixEvent,\n timelineSet: EventTimelineSet,\n targetEvent: MatrixEvent,\n ): Promise<void>;\n public aggregateChildEvent(\n event: MatrixEvent,\n timelineSet?: EventTimelineSet,\n targetEvent?: MatrixEvent,\n ): void | Promise<void> {\n const aggregation = this.aggregateChildEventInternal(event, timelineSet, targetEvent);\n if (targetEvent) return aggregation;\n\n void aggregation.catch((error) => logger.error(\"Failed to aggregate child event: \", error));\n }\n\n private aggregateChildEventInternal(\n event: MatrixEvent,\n timelineSet?: EventTimelineSet,\n targetEvent?: MatrixEvent,\n ): Promise<void> {\n if (event.isRedacted() || event.status === EventStatus.CANCELLED) {\n return Promise.resolve();\n }\n\n const relation = event.getRelation();\n if (!relation) return Promise.resolve();\n\n // If the event is currently encrypted, wait until it has been decrypted.\n if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n return new Promise<void>((resolve, reject) => {\n const onEventDecrypted = (): void => {\n if (event.isDecryptionFailure()) {\n // This could for example happen if the encryption keys are not yet available.\n // The event may still be decrypted later. Register the listener again.\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n return;\n }\n\n void this.aggregateChildEventInternal(event, timelineSet, targetEvent).then(resolve, reject);\n };\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n });\n }\n\n const { event_id: relatesToEventId, rel_type: relationType } = relation;\n const eventType = event.getType();\n\n let relationsForEvent = this.relations.get(relatesToEventId!);\n if (!relationsForEvent) {\n relationsForEvent = new Map<RelationType | string, Map<EventType | string, Relations>>();\n this.relations.set(relatesToEventId!, relationsForEvent);\n }\n\n let relationsWithRelType = relationsForEvent.get(relationType!);\n if (!relationsWithRelType) {\n relationsWithRelType = new Map<EventType | string, Relations>();\n relationsForEvent.set(relationType!, relationsWithRelType);\n }\n\n let relationsWithEventType = relationsWithRelType.get(eventType);\n const isNewRelationCollection = !relationsWithEventType;\n let targetEventUpdate = Promise.resolve();\n if (!relationsWithEventType) {\n relationsWithEventType = new Relations(relationType!, eventType, this.client);\n relationsWithRelType.set(eventType, relationsWithEventType);\n }\n\n if (isNewRelationCollection || targetEvent) {\n const room = this.room ?? timelineSet?.room;\n const relatesToEvent =\n timelineSet?.findEventById(relatesToEventId!) ??\n room?.findEventById(relatesToEventId!) ??\n room?.getPendingEvent(relatesToEventId!) ??\n targetEvent;\n if (relatesToEvent) {\n targetEventUpdate = relationsWithEventType.setTargetEvent(relatesToEvent);\n }\n }\n\n const addEventUpdate = relationsWithEventType.addEvent(event);\n return Promise.all([targetEventUpdate, addEventUpdate]).then(() => undefined);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,WAAW,EAAoB,gBAAgB,QAAQ,YAAY;AAI5E,SAAS,MAAM,QAAQ,cAAc;AAErC,OAAO,MAAM,kBAAkB,CAAC;EAKrB,WAAW,CACG,MAAoB,EACpB,IAAW,EAC9B;IAPF;IACA;IAAA,mCACoB,IAAI,GAAG,CAAyE,CAAC;IAAA,KAGhF,MAAoB,GAApB,MAAoB;IAAA,KACpB,IAAW,GAAX,IAAW;EAC7B;;EAEH;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,sBAAsB,CACzB,OAAe,EACf,YAAmC,EACnC,SAA6B,EACR;IACrB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,YAAY,CAAC,EAAE,GAAG,CAAC,SAAS,CAAC;EACzE;EAEO,yBAAyB,CAAC,aAAqB,EAAiB;IACnE,MAAM,iBAAiB,GACnB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,IAAI,GAAG,CAA4D,CAAC;IAC7G,MAAM,MAAqB,GAAG,EAAE;IAChC,KAAK,MAAM,eAAe,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC,EAAE;MACtD,KAAK,MAAM,SAAS,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC,EAAE;QAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC;MAC5C;IACJ;IACA,OAAO,MAAM;EACjB;;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,GAAG,IAAI,SAAS,CAAC,YAAY,EAAG,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC;MAC7E,oBAAoB,CAAC,GAAG,CAAC,SAAS,EAAE,sBAAsB,CAAC;IAC/D;IAEA,IAAI,uBAAuB,IAAI,WAAW,EAAE;MACxC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,WAAW,EAAE,IAAI;MAC3C,MAAM,cAAc,GAChB,WAAW,EAAE,aAAa,CAAC,gBAAiB,CAAC,IAC7C,IAAI,EAAE,aAAa,CAAC,gBAAiB,CAAC,IACtC,IAAI,EAAE,eAAe,CAAC,gBAAiB,CAAC,IACxC,WAAW;MACf,IAAI,cAAc,EAAE;QAChB,iBAAiB,GAAG,sBAAsB,CAAC,cAAc,CAAC,cAAc,CAAC;MAC7E;IACJ;IAEA,MAAM,cAAc,GAAG,sBAAsB,CAAC,QAAQ,CAAC,KAAK,CAAC;IAC7D,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,SAAS,CAAC;EACjF;AACJ","ignoreList":[]}
@@ -298,7 +298,7 @@ export class Relations extends TypedEventEmitter {
298
298
  * @param targetEvent - the event the relations are related to.
299
299
  */
300
300
  async setTargetEvent(event) {
301
- if (this.targetEvent) {
301
+ if (this.targetEvent === event) {
302
302
  return;
303
303
  }
304
304
  this.targetEvent = event;
@@ -1 +1 @@
1
- {"version":3,"file":"relations.js","names":[],"sources":["../../src/models/relations.ts"],"sourcesContent":["/*\nCopyright 2019, 2021, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventStatus, type IAggregatedRelation, type MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { logger } from \"../logger.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { Room } from \"./room.ts\";\nimport { type CryptoBackend } from \"../common-crypto/CryptoBackend.ts\";\n\nexport enum RelationsEvent {\n Add = \"Relations.add\",\n Remove = \"Relations.remove\",\n Redaction = \"Relations.redaction\",\n}\n\nexport type EventHandlerMap = {\n [RelationsEvent.Add]: (event: MatrixEvent) => void;\n [RelationsEvent.Remove]: (event: MatrixEvent) => void;\n [RelationsEvent.Redaction]: (event: MatrixEvent) => void;\n};\n\nconst matchesEventType = (eventType: string, targetEventType: string, altTargetEventTypes: string[] = []): boolean =>\n [targetEventType, ...altTargetEventTypes].includes(eventType);\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends TypedEventEmitter<RelationsEvent, EventHandlerMap> {\n private relationEventIds = new Set<string>();\n private relations = new Set<MatrixEvent>();\n private annotationsByKey: Record<string, Set<MatrixEvent>> = {};\n private annotationsBySender: Record<string, Set<MatrixEvent>> = {};\n private sortedAnnotationsByKey: [string, Set<MatrixEvent>][] = [];\n private targetEvent: MatrixEvent | null = null;\n private creationEmitted = false;\n private replacementUpdateId = 0;\n private readonly client: MatrixClient;\n\n /**\n * @param relationType - The type of relation involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @param client - The client which created this instance. For backwards compatibility also accepts a Room.\n * @param altEventTypes - alt event types for relation events, for example to support unstable prefixed event types\n */\n public constructor(\n public readonly relationType: RelationType | string,\n public readonly eventType: string,\n client: MatrixClient | Room,\n public readonly altEventTypes?: string[],\n ) {\n super();\n this.client = client instanceof Room ? client.client : client;\n }\n\n /**\n * Add relation events to this collection.\n *\n * @param event - The new relation event to be added.\n */\n public async addEvent(event: MatrixEvent): Promise<void> {\n if (this.relationEventIds.has(event.getId()!)) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || !matchesEventType(eventType, this.eventType, this.altEventTypes)) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n // If the event is in the process of being sent, listen for cancellation\n // so we can remove the event from the collection.\n if (event.isSending()) {\n event.on(MatrixEventEvent.Status, this.onEventStatus);\n }\n\n this.relations.add(event);\n this.relationEventIds.add(event.getId()!);\n\n if (this.relationType === RelationType.Annotation) {\n this.addAnnotationToAggregation(event);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n event.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Add, event);\n\n this.maybeEmitCreated();\n }\n\n /**\n * Remove relation event from this collection.\n *\n * @param event - The relation event to remove.\n */\n public async removeEvent(event: MatrixEvent): Promise<void> {\n if (!this.relations.has(event)) {\n return;\n }\n\n this.relations.delete(event);\n\n if (this.relationType === RelationType.Annotation) {\n this.removeAnnotationFromAggregation(event);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n this.emit(RelationsEvent.Remove, event);\n }\n\n /**\n * Listens for event status changes to remove cancelled events.\n *\n * @param event - The event whose status has changed\n * @param status - The new status\n */\n private onEventStatus = (event: MatrixEvent, status: EventStatus | null): void => {\n if (!event.isSending()) {\n // Sending is done, so we don't need to listen anymore\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n return;\n }\n if (status !== EventStatus.CANCELLED) {\n return;\n }\n // Event was cancelled, remove from the collection\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n this.removeEvent(event);\n };\n\n /**\n * Get all relation events in this collection.\n *\n * These are currently in the order of insertion to this collection, which\n * won't match timeline order in the case of scrollback.\n * TODO: Tweak `addEvent` to insert correctly for scrollback.\n *\n * Relation events in insertion order.\n */\n public getRelations(): MatrixEvent[] {\n return [...this.relations];\n }\n\n private addAnnotationToAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n let eventsForKey = this.annotationsByKey[key];\n if (!eventsForKey) {\n eventsForKey = this.annotationsByKey[key] = new Set();\n this.sortedAnnotationsByKey.push([key, eventsForKey]);\n }\n // Add the new event to the set for this key\n eventsForKey.add(event);\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n\n const sender = event.getSender()!;\n let eventsFromSender = this.annotationsBySender[sender];\n if (!eventsFromSender) {\n eventsFromSender = this.annotationsBySender[sender] = new Set();\n }\n // Add the new event to the set for this sender\n eventsFromSender.add(event);\n }\n\n private removeAnnotationFromAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n const eventsForKey = this.annotationsByKey[key];\n if (eventsForKey) {\n eventsForKey.delete(event);\n\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n }\n\n const sender = event.getSender()!;\n const eventsFromSender = this.annotationsBySender[sender];\n if (eventsFromSender) {\n eventsFromSender.delete(event);\n }\n }\n\n /**\n * For relations that have been redacted, we want to remove them from\n * aggregation data sets and emit an update event.\n *\n * To do so, we listen for `Event.beforeRedaction`, which happens:\n * - after the server accepted the redaction and remote echoed back to us\n * - before the original event has been marked redacted in the client\n *\n * @param redactedEvent - The original relation event that is about to be redacted.\n */\n private onBeforeRedaction = async (redactedEvent: MatrixEvent): Promise<void> => {\n if (!this.relations.has(redactedEvent)) {\n return;\n }\n\n this.relations.delete(redactedEvent);\n\n if (this.relationType === RelationType.Annotation) {\n // Remove the redacted annotation from aggregation by key\n this.removeAnnotationFromAggregation(redactedEvent);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n redactedEvent.removeListener(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Redaction, redactedEvent);\n };\n\n /**\n * Get all events in this collection grouped by key and sorted by descending\n * event count in each group.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An array of [key, events] pairs sorted by descending event count.\n * The events are stored in a Set (which preserves insertion order).\n */\n public getSortedAnnotationsByKey(): [string, Set<MatrixEvent>][] | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.sortedAnnotationsByKey;\n }\n\n /**\n * Get all events in this collection grouped by sender.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An object with each relation sender as a key and the matching Set of\n * events for that sender as a value.\n */\n public getAnnotationsBySender(): Record<string, Set<MatrixEvent>> | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.annotationsBySender;\n }\n\n /**\n * Returns the most recent (and allowed) m.replace relation, if any.\n *\n * This is currently only supported for the m.replace relation type,\n * once the target event is known, see `addEvent`.\n */\n public async getLastReplacement(): Promise<MatrixEvent | null> {\n if (this.relationType !== RelationType.Replace) {\n // Aggregating on last only makes sense for this relation type\n return null;\n }\n if (!this.targetEvent) {\n // Don't know which replacements to accept yet.\n // This method shouldn't be called before the original\n // event is known anyway.\n return null;\n }\n\n // the all-knowning server tells us that the event at some point had\n // this timestamp for its replacement, so any following replacement should definitely not be less\n const replaceRelation = this.targetEvent.getServerAggregatedRelation<IAggregatedRelation>(RelationType.Replace);\n const minTs = replaceRelation?.origin_server_ts;\n\n const lastReplacement = this.getRelations().reduce<MatrixEvent | null>((last, event) => {\n if (event.getSender() !== this.targetEvent!.getSender()) {\n return last;\n }\n if (minTs && minTs > event.getTs()) {\n return last;\n }\n if (last && last.getTs() > event.getTs()) {\n return last;\n }\n return event;\n }, null);\n\n if (lastReplacement?.shouldAttemptDecryption() && this.client.getCrypto()) {\n // Dirty but we are expecting to pass the cryptoBackend which is not accessible here\n await lastReplacement.attemptDecryption(this.client.getCrypto() as CryptoBackend);\n } else if (lastReplacement?.isBeingDecrypted()) {\n await lastReplacement.getDecryptionPromise();\n }\n\n return lastReplacement;\n }\n\n /*\n * @param targetEvent - the event the relations are related to.\n */\n public async setTargetEvent(event: MatrixEvent): Promise<void> {\n if (this.targetEvent) {\n return;\n }\n this.targetEvent = event;\n\n if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n this.maybeEmitCreated();\n }\n\n /**\n * Updates the target event with the latest replacement.\n *\n * Multiple replacement updates can be triggered concurrently (for example\n * while edits are still being decrypted). A monotonic update counter guards\n * against older async resolutions overriding newer replacement selections.\n */\n private async updateTargetEventReplacement(): Promise<void> {\n if (!this.targetEvent || this.targetEvent.isState()) {\n return;\n }\n\n const targetEvent = this.targetEvent;\n const updateId = ++this.replacementUpdateId;\n const lastReplacement = await this.getLastReplacement();\n\n // If a newer update started while we were awaiting, discard this stale result.\n if (updateId !== this.replacementUpdateId || this.targetEvent !== targetEvent) {\n return;\n }\n\n // Avoid emitting Event.replaced when there is no replacement and none currently set.\n if (!lastReplacement && !targetEvent.replacingEvent()) {\n return;\n }\n\n targetEvent.makeReplaced(lastReplacement ?? undefined);\n }\n\n private maybeEmitCreated(): void {\n if (this.creationEmitted) {\n return;\n }\n // Only emit we're \"created\" once we have a target event instance _and_\n // at least one related event.\n if (!this.targetEvent || !this.relations.size) {\n return;\n }\n this.creationEmitted = true;\n this.targetEvent.emit(MatrixEventEvent.RelationsCreated, this.relationType, this.eventType);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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"file":"relations.js","names":[],"sources":["../../src/models/relations.ts"],"sourcesContent":["/*\nCopyright 2019, 2021, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventStatus, type IAggregatedRelation, type MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { logger } from \"../logger.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { Room } from \"./room.ts\";\nimport { type CryptoBackend } from \"../common-crypto/CryptoBackend.ts\";\n\nexport enum RelationsEvent {\n Add = \"Relations.add\",\n Remove = \"Relations.remove\",\n Redaction = \"Relations.redaction\",\n}\n\nexport type EventHandlerMap = {\n [RelationsEvent.Add]: (event: MatrixEvent) => void;\n [RelationsEvent.Remove]: (event: MatrixEvent) => void;\n [RelationsEvent.Redaction]: (event: MatrixEvent) => void;\n};\n\nconst matchesEventType = (eventType: string, targetEventType: string, altTargetEventTypes: string[] = []): boolean =>\n [targetEventType, ...altTargetEventTypes].includes(eventType);\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends TypedEventEmitter<RelationsEvent, EventHandlerMap> {\n private relationEventIds = new Set<string>();\n private relations = new Set<MatrixEvent>();\n private annotationsByKey: Record<string, Set<MatrixEvent>> = {};\n private annotationsBySender: Record<string, Set<MatrixEvent>> = {};\n private sortedAnnotationsByKey: [string, Set<MatrixEvent>][] = [];\n private targetEvent: MatrixEvent | null = null;\n private creationEmitted = false;\n private replacementUpdateId = 0;\n private readonly client: MatrixClient;\n\n /**\n * @param relationType - The type of relation involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @param client - The client which created this instance. For backwards compatibility also accepts a Room.\n * @param altEventTypes - alt event types for relation events, for example to support unstable prefixed event types\n */\n public constructor(\n public readonly relationType: RelationType | string,\n public readonly eventType: string,\n client: MatrixClient | Room,\n public readonly altEventTypes?: string[],\n ) {\n super();\n this.client = client instanceof Room ? client.client : client;\n }\n\n /**\n * Add relation events to this collection.\n *\n * @param event - The new relation event to be added.\n */\n public async addEvent(event: MatrixEvent): Promise<void> {\n if (this.relationEventIds.has(event.getId()!)) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || !matchesEventType(eventType, this.eventType, this.altEventTypes)) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n // If the event is in the process of being sent, listen for cancellation\n // so we can remove the event from the collection.\n if (event.isSending()) {\n event.on(MatrixEventEvent.Status, this.onEventStatus);\n }\n\n this.relations.add(event);\n this.relationEventIds.add(event.getId()!);\n\n if (this.relationType === RelationType.Annotation) {\n this.addAnnotationToAggregation(event);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n event.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Add, event);\n\n this.maybeEmitCreated();\n }\n\n /**\n * Remove relation event from this collection.\n *\n * @param event - The relation event to remove.\n */\n public async removeEvent(event: MatrixEvent): Promise<void> {\n if (!this.relations.has(event)) {\n return;\n }\n\n this.relations.delete(event);\n\n if (this.relationType === RelationType.Annotation) {\n this.removeAnnotationFromAggregation(event);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n this.emit(RelationsEvent.Remove, event);\n }\n\n /**\n * Listens for event status changes to remove cancelled events.\n *\n * @param event - The event whose status has changed\n * @param status - The new status\n */\n private onEventStatus = (event: MatrixEvent, status: EventStatus | null): void => {\n if (!event.isSending()) {\n // Sending is done, so we don't need to listen anymore\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n return;\n }\n if (status !== EventStatus.CANCELLED) {\n return;\n }\n // Event was cancelled, remove from the collection\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n this.removeEvent(event);\n };\n\n /**\n * Get all relation events in this collection.\n *\n * These are currently in the order of insertion to this collection, which\n * won't match timeline order in the case of scrollback.\n * TODO: Tweak `addEvent` to insert correctly for scrollback.\n *\n * Relation events in insertion order.\n */\n public getRelations(): MatrixEvent[] {\n return [...this.relations];\n }\n\n private addAnnotationToAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n let eventsForKey = this.annotationsByKey[key];\n if (!eventsForKey) {\n eventsForKey = this.annotationsByKey[key] = new Set();\n this.sortedAnnotationsByKey.push([key, eventsForKey]);\n }\n // Add the new event to the set for this key\n eventsForKey.add(event);\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n\n const sender = event.getSender()!;\n let eventsFromSender = this.annotationsBySender[sender];\n if (!eventsFromSender) {\n eventsFromSender = this.annotationsBySender[sender] = new Set();\n }\n // Add the new event to the set for this sender\n eventsFromSender.add(event);\n }\n\n private removeAnnotationFromAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n const eventsForKey = this.annotationsByKey[key];\n if (eventsForKey) {\n eventsForKey.delete(event);\n\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n }\n\n const sender = event.getSender()!;\n const eventsFromSender = this.annotationsBySender[sender];\n if (eventsFromSender) {\n eventsFromSender.delete(event);\n }\n }\n\n /**\n * For relations that have been redacted, we want to remove them from\n * aggregation data sets and emit an update event.\n *\n * To do so, we listen for `Event.beforeRedaction`, which happens:\n * - after the server accepted the redaction and remote echoed back to us\n * - before the original event has been marked redacted in the client\n *\n * @param redactedEvent - The original relation event that is about to be redacted.\n */\n private onBeforeRedaction = async (redactedEvent: MatrixEvent): Promise<void> => {\n if (!this.relations.has(redactedEvent)) {\n return;\n }\n\n this.relations.delete(redactedEvent);\n\n if (this.relationType === RelationType.Annotation) {\n // Remove the redacted annotation from aggregation by key\n this.removeAnnotationFromAggregation(redactedEvent);\n } else if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n redactedEvent.removeListener(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Redaction, redactedEvent);\n };\n\n /**\n * Get all events in this collection grouped by key and sorted by descending\n * event count in each group.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An array of [key, events] pairs sorted by descending event count.\n * The events are stored in a Set (which preserves insertion order).\n */\n public getSortedAnnotationsByKey(): [string, Set<MatrixEvent>][] | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.sortedAnnotationsByKey;\n }\n\n /**\n * Get all events in this collection grouped by sender.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An object with each relation sender as a key and the matching Set of\n * events for that sender as a value.\n */\n public getAnnotationsBySender(): Record<string, Set<MatrixEvent>> | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.annotationsBySender;\n }\n\n /**\n * Returns the most recent (and allowed) m.replace relation, if any.\n *\n * This is currently only supported for the m.replace relation type,\n * once the target event is known, see `addEvent`.\n */\n public async getLastReplacement(): Promise<MatrixEvent | null> {\n if (this.relationType !== RelationType.Replace) {\n // Aggregating on last only makes sense for this relation type\n return null;\n }\n if (!this.targetEvent) {\n // Don't know which replacements to accept yet.\n // This method shouldn't be called before the original\n // event is known anyway.\n return null;\n }\n\n // the all-knowning server tells us that the event at some point had\n // this timestamp for its replacement, so any following replacement should definitely not be less\n const replaceRelation = this.targetEvent.getServerAggregatedRelation<IAggregatedRelation>(RelationType.Replace);\n const minTs = replaceRelation?.origin_server_ts;\n\n const lastReplacement = this.getRelations().reduce<MatrixEvent | null>((last, event) => {\n if (event.getSender() !== this.targetEvent!.getSender()) {\n return last;\n }\n if (minTs && minTs > event.getTs()) {\n return last;\n }\n if (last && last.getTs() > event.getTs()) {\n return last;\n }\n return event;\n }, null);\n\n if (lastReplacement?.shouldAttemptDecryption() && this.client.getCrypto()) {\n // Dirty but we are expecting to pass the cryptoBackend which is not accessible here\n await lastReplacement.attemptDecryption(this.client.getCrypto() as CryptoBackend);\n } else if (lastReplacement?.isBeingDecrypted()) {\n await lastReplacement.getDecryptionPromise();\n }\n\n return lastReplacement;\n }\n\n /*\n * @param targetEvent - the event the relations are related to.\n */\n public async setTargetEvent(event: MatrixEvent): Promise<void> {\n if (this.targetEvent === event) {\n return;\n }\n this.targetEvent = event;\n\n if (this.relationType === RelationType.Replace) {\n await this.updateTargetEventReplacement();\n }\n\n this.maybeEmitCreated();\n }\n\n /**\n * Updates the target event with the latest replacement.\n *\n * Multiple replacement updates can be triggered concurrently (for example\n * while edits are still being decrypted). A monotonic update counter guards\n * against older async resolutions overriding newer replacement selections.\n */\n private async updateTargetEventReplacement(): Promise<void> {\n if (!this.targetEvent || this.targetEvent.isState()) {\n return;\n }\n\n const targetEvent = this.targetEvent;\n const updateId = ++this.replacementUpdateId;\n const lastReplacement = await this.getLastReplacement();\n\n // If a newer update started while we were awaiting, discard this stale result.\n if (updateId !== this.replacementUpdateId || this.targetEvent !== targetEvent) {\n return;\n }\n\n // Avoid emitting Event.replaced when there is no replacement and none currently set.\n if (!lastReplacement && !targetEvent.replacingEvent()) {\n return;\n }\n\n targetEvent.makeReplaced(lastReplacement ?? undefined);\n }\n\n private maybeEmitCreated(): void {\n if (this.creationEmitted) {\n return;\n }\n // Only emit we're \"created\" once we have a target event instance _and_\n // at least one related event.\n if (!this.targetEvent || !this.relations.size) {\n return;\n }\n this.creationEmitted = true;\n this.targetEvent.emit(MatrixEventEvent.RelationsCreated, this.relationType, this.eventType);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,WAAW,EAA8C,gBAAgB,QAAQ,YAAY;AACtG,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,YAAY,QAAQ,oBAAoB;AACjD,SAAS,iBAAiB,QAAQ,0BAA0B;AAE5D,SAAS,IAAI,QAAQ,WAAW;AAGhC,WAAY,cAAc,0BAAd,cAAc;EAAd,cAAc;EAAd,cAAc;EAAd,cAAc;EAAA,OAAd,cAAc;AAAA;AAY1B,MAAM,gBAAgB,GAAG,CAAC,SAAiB,EAAE,eAAuB,EAAE,mBAA6B,GAAG,EAAE,KACpG,CAAC,eAAe,EAAE,GAAG,mBAAmB,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC;;AAEjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,SAAS,SAAS,iBAAiB,CAAkC;EAW9E;AACJ;AACA;AACA;AACA;AACA;EACW,WAAW,CACE,YAAmC,EACnC,SAAiB,EACjC,MAA2B,EACX,aAAwB,EAC1C;IACE,KAAK,CAAC,CAAC;IAAC,0CAtBe,IAAI,GAAG,CAAS,CAAC;IAAA,mCACxB,IAAI,GAAG,CAAc,CAAC;IAAA,0CACmB,CAAC,CAAC;IAAA,6CACC,CAAC,CAAC;IAAA,gDACH,EAAE;IAAA,qCACvB,IAAI;IAAA,yCACpB,KAAK;IAAA,6CACD,CAAC;IAAA;IAsF/B;AACJ;AACA;AACA;AACA;AACA;IALI,uCAMwB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AAI,IAAI,CAAC,eAAe,EAAE;MACtB;IACJ;IACA;IACA;IACA,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;MAC3C;IACJ;IACA,IAAI,CAAC,eAAe,GAAG,IAAI;IAC3B,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,gBAAgB,CAAC,gBAAgB,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC;EAC/F;AACJ","ignoreList":[]}
@@ -863,7 +863,7 @@ export class Room extends ReadReceipt {
863
863
  if (rawMembersEvents === null || this.hasEncryptionStateEvent()) {
864
864
  fromServer = true;
865
865
  rawMembersEvents = await this.loadMembersFromServer();
866
- logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);
866
+ logger.log(`LL: got ${rawMembersEvents.length} members from server for room ${this.roomId}`);
867
867
  }
868
868
  const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());
869
869
  return {
@@ -917,7 +917,7 @@ export class Room extends ReadReceipt {
917
917
  inMemoryUpdate.then(fromServer => {
918
918
  if (fromServer) {
919
919
  const oobMembers = this.currentState.getMembers().filter(m => m.isOutOfBand()).map(m => m.events.member?.event);
920
- logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);
920
+ logger.log(`LL: telling store to write ${oobMembers.length} members for room ${this.roomId}`);
921
921
  const store = this.client.store;
922
922
  return store.setOutOfBandMembers(this.roomId, oobMembers)
923
923
  // swallow any IDB error as we don't want to fail
@@ -953,7 +953,7 @@ export class Room extends ReadReceipt {
953
953
  */
954
954
  cleanupAfterLeaving() {
955
955
  this.clearLoadedMembersIfNeeded().catch(err => {
956
- logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);
956
+ logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`);
957
957
  logger.log(err);
958
958
  });
959
959
  }