matrix-js-sdk 41.5.0 → 41.6.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 (204) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/ReEmitter.js +1 -1
  3. package/lib/ReEmitter.js.map +1 -1
  4. package/lib/ToDeviceMessageQueue.js +2 -2
  5. package/lib/ToDeviceMessageQueue.js.map +1 -1
  6. package/lib/autodiscovery.js +0 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/client.js +112 -165
  9. package/lib/client.js.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +0 -2
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/content-helpers.js +3 -5
  13. package/lib/content-helpers.js.map +1 -1
  14. package/lib/content-repo.js +7 -1
  15. package/lib/content-repo.js.map +1 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js +9 -11
  17. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +0 -2
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/localStorage-crypto-store.js +11 -9
  21. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  22. package/lib/crypto/store/memory-crypto-store.js +11 -9
  23. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  24. package/lib/crypto-api/index.js +58 -58
  25. package/lib/crypto-api/index.js.map +1 -1
  26. package/lib/embedded.js +29 -45
  27. package/lib/embedded.js.map +1 -1
  28. package/lib/extensible_events_v1/MessageEvent.js +15 -15
  29. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  30. package/lib/extensible_events_v1/PollEndEvent.js +8 -8
  31. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  32. package/lib/extensible_events_v1/PollResponseEvent.js +0 -1
  33. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  34. package/lib/extensible_events_v1/PollStartEvent.js +28 -28
  35. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  36. package/lib/feature.js +5 -1
  37. package/lib/feature.js.map +1 -1
  38. package/lib/filter-component.js +4 -1
  39. package/lib/filter-component.js.map +1 -1
  40. package/lib/filter.js +1 -3
  41. package/lib/filter.js.map +1 -1
  42. package/lib/http-api/errors.js +20 -16
  43. package/lib/http-api/errors.js.map +1 -1
  44. package/lib/http-api/fetch.js +4 -6
  45. package/lib/http-api/fetch.js.map +1 -1
  46. package/lib/http-api/refresh.js +10 -12
  47. package/lib/http-api/refresh.js.map +1 -1
  48. package/lib/interactive-auth.js +1 -11
  49. package/lib/interactive-auth.js.map +1 -1
  50. package/lib/logger.js +0 -2
  51. package/lib/logger.js.map +1 -1
  52. package/lib/matrixrtc/CallMembership.js +43 -57
  53. package/lib/matrixrtc/CallMembership.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.js +19 -24
  55. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  56. package/lib/matrixrtc/MatrixRTCSessionManager.js +2 -3
  57. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  58. package/lib/matrixrtc/MembershipManager.js +23 -30
  59. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  60. package/lib/matrixrtc/MembershipManagerActionScheduler.js +1 -2
  61. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  62. package/lib/matrixrtc/RTCEncryptionManager.js +8 -11
  63. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  64. package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
  65. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  66. package/lib/matrixrtc/utils.js +7 -1
  67. package/lib/matrixrtc/utils.js.map +1 -1
  68. package/lib/models/MSC3089TreeSpace.js +5 -7
  69. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  70. package/lib/models/beacon.js +5 -11
  71. package/lib/models/beacon.js.map +1 -1
  72. package/lib/models/device.js +0 -7
  73. package/lib/models/device.js.map +1 -1
  74. package/lib/models/event-context.js +1 -2
  75. package/lib/models/event-context.js.map +1 -1
  76. package/lib/models/event-timeline-set.js +16 -26
  77. package/lib/models/event-timeline-set.js.map +1 -1
  78. package/lib/models/event-timeline.js +8 -15
  79. package/lib/models/event-timeline.js.map +1 -1
  80. package/lib/models/event.js +20 -37
  81. package/lib/models/event.js.map +1 -1
  82. package/lib/models/invites-ignorer.js +8 -12
  83. package/lib/models/invites-ignorer.js.map +1 -1
  84. package/lib/models/poll.js +7 -13
  85. package/lib/models/poll.js.map +1 -1
  86. package/lib/models/read-receipt.js +8 -4
  87. package/lib/models/read-receipt.js.map +1 -1
  88. package/lib/models/related-relations.js +0 -2
  89. package/lib/models/related-relations.js.map +1 -1
  90. package/lib/models/relations-container.js +4 -6
  91. package/lib/models/relations-container.js.map +1 -1
  92. package/lib/models/relations.js +7 -10
  93. package/lib/models/relations.js.map +1 -1
  94. package/lib/models/room-member.js +2 -24
  95. package/lib/models/room-member.js.map +1 -1
  96. package/lib/models/room-receipts.js +25 -22
  97. package/lib/models/room-receipts.js.map +1 -1
  98. package/lib/models/room-state.js +2 -2
  99. package/lib/models/room-state.js.map +1 -1
  100. package/lib/models/room-sticky-events.js +20 -5
  101. package/lib/models/room-sticky-events.js.map +1 -1
  102. package/lib/models/room.js +82 -105
  103. package/lib/models/room.js.map +1 -1
  104. package/lib/models/thread.js +12 -57
  105. package/lib/models/thread.js.map +1 -1
  106. package/lib/models/user.js +1 -20
  107. package/lib/models/user.js.map +1 -1
  108. package/lib/oidc/authorize.js +23 -32
  109. package/lib/oidc/authorize.js.map +1 -1
  110. package/lib/oidc/tokenRefresher.js +8 -11
  111. package/lib/oidc/tokenRefresher.js.map +1 -1
  112. package/lib/pushprocessor.js +8 -5
  113. package/lib/pushprocessor.js.map +1 -1
  114. package/lib/receipt-accumulator.js +12 -3
  115. package/lib/receipt-accumulator.js.map +1 -1
  116. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  117. package/lib/rendezvous/MSC4108SignInWithQR.js +10 -23
  118. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  119. package/lib/rendezvous/channels/MSC4108SecureChannel.js +5 -10
  120. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  121. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +5 -15
  122. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  123. package/lib/room-hierarchy.js +7 -12
  124. package/lib/room-hierarchy.js.map +1 -1
  125. package/lib/rust-crypto/DehydratedDeviceManager.js +2 -3
  126. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  127. package/lib/rust-crypto/KeyClaimManager.js +1 -2
  128. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  129. package/lib/rust-crypto/OutgoingRequestProcessor.js +11 -4
  130. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  131. package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
  132. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  133. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +3 -5
  134. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  135. package/lib/rust-crypto/RoomEncryptor.js +6 -6
  136. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  137. package/lib/rust-crypto/backup.js +22 -16
  138. package/lib/rust-crypto/backup.js.map +1 -1
  139. package/lib/rust-crypto/device-converter.js +13 -4
  140. package/lib/rust-crypto/device-converter.js.map +1 -1
  141. package/lib/rust-crypto/index.js +1 -3
  142. package/lib/rust-crypto/index.js.map +1 -1
  143. package/lib/rust-crypto/libolm_migration.js +13 -15
  144. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  145. package/lib/rust-crypto/rust-crypto.js +52 -59
  146. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  147. package/lib/rust-crypto/verification.js +10 -10
  148. package/lib/rust-crypto/verification.js.map +1 -1
  149. package/lib/scheduler.js +2 -2
  150. package/lib/scheduler.js.map +1 -1
  151. package/lib/secret-storage.js +16 -10
  152. package/lib/secret-storage.js.map +1 -1
  153. package/lib/serverCapabilities.js +2 -5
  154. package/lib/serverCapabilities.js.map +1 -1
  155. package/lib/sliding-sync-sdk.js +4 -9
  156. package/lib/sliding-sync-sdk.js.map +1 -1
  157. package/lib/sliding-sync.js +4 -9
  158. package/lib/sliding-sync.js.map +1 -1
  159. package/lib/store/indexeddb-local-backend.js +13 -8
  160. package/lib/store/indexeddb-local-backend.js.map +1 -1
  161. package/lib/store/indexeddb-remote-backend.js +6 -7
  162. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  163. package/lib/store/indexeddb-store-worker.js +1 -2
  164. package/lib/store/indexeddb-store-worker.js.map +1 -1
  165. package/lib/store/indexeddb.js +4 -2
  166. package/lib/store/indexeddb.js.map +1 -1
  167. package/lib/store/memory.js +0 -4
  168. package/lib/store/memory.js.map +1 -1
  169. package/lib/sync-accumulator.js +2 -4
  170. package/lib/sync-accumulator.js.map +1 -1
  171. package/lib/sync.js +36 -43
  172. package/lib/sync.js.map +1 -1
  173. package/lib/timeline-window.js +2 -6
  174. package/lib/timeline-window.js.map +1 -1
  175. package/lib/utils/decryptAESSecretStorageItem.js +5 -1
  176. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  177. package/lib/utils/encryptAESSecretStorageItem.js +5 -1
  178. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  179. package/lib/utils.js +35 -20
  180. package/lib/utils.js.map +1 -1
  181. package/lib/webrtc/call.js +13 -45
  182. package/lib/webrtc/call.js.map +1 -1
  183. package/lib/webrtc/callEventHandler.js +0 -5
  184. package/lib/webrtc/callEventHandler.js.map +1 -1
  185. package/lib/webrtc/callFeed.js +0 -15
  186. package/lib/webrtc/callFeed.js.map +1 -1
  187. package/lib/webrtc/groupCall.js +82 -89
  188. package/lib/webrtc/groupCall.js.map +1 -1
  189. package/lib/webrtc/groupCallEventHandler.js +6 -7
  190. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  191. package/lib/webrtc/mediaHandler.js +8 -15
  192. package/lib/webrtc/mediaHandler.js.map +1 -1
  193. package/lib/webrtc/stats/callStatsReportGatherer.js +2 -5
  194. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  195. package/lib/webrtc/stats/connectionStatsReportBuilder.js +5 -1
  196. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  197. package/lib/webrtc/stats/groupCallStats.js +3 -4
  198. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  199. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  200. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  201. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
  202. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  203. package/package.json +3 -3
  204. package/src/rendezvous/MSC4108SignInWithQR.ts +2 -1
@@ -59,61 +59,15 @@ export class Thread extends ReadReceipt {
59
59
  // each Event in the thread adds a reemitter, so we could hit the listener limit.
60
60
  super();
61
61
  _this = this;
62
- this.id = id;
63
- this.rootEvent = rootEvent;
64
- /**
65
- * A reference to all the events ID at the bottom of the threads
66
- */
67
- _defineProperty(this, "timelineSet", void 0);
68
62
  _defineProperty(this, "_currentUserParticipated", false);
69
- _defineProperty(this, "reEmitter", void 0);
70
- /**
71
- * The last event in this thread, if we don't yet have this in the timeline.
72
- *
73
- * When we run {@link processRootEvent} (which I think happens during the
74
- * setting-up of the thread), we set this to the event pointed to by the
75
- * server in `latest_event` [1] that came through with the thread root.
76
- *
77
- * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships
78
- *
79
- * Later, when we have populated the timeline, this is set to undefined, so
80
- * that methods like {@link replyToEvent} fall through to use lastReply,
81
- * which looks in the timeline for the latest event that is a "thread reply"
82
- * i.e. directly refers to the thread root with an m.thread relation.
83
- *
84
- * So it looks like this is only really relevant when initialEventsFetched
85
- * is false, because as soon as the initial events have been fetched, we
86
- * should have a proper chunk of timeline from the pagination fetch.
87
- *
88
- * If all replies in this thread are redacted, this is set to the root
89
- * event. I'm not clear what the meaning of this is, since usually after the
90
- * initial events have been fetched, lastEvent should be undefined.
91
- * In fact, the whole usage inside onRedaction looks suspect - it may be
92
- * that we were thinking lastEvent always refers to the actual last event,
93
- * but it only does so before initialEventsFetched becomes true.
94
- *
95
- * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd
96
- * think we probably mean {@link replyToEvent} there - we are trying not to
97
- * echo a duplicate event, and we probably want that behaviour even after
98
- * initialEventsFetched has become true.
99
- *
100
- * -- andyb
101
- */
102
- _defineProperty(this, "lastEvent", void 0);
103
63
  _defineProperty(this, "replyCount", 0);
104
- _defineProperty(this, "lastPendingEvent", void 0);
105
64
  _defineProperty(this, "pendingReplyCount", 0);
106
- _defineProperty(this, "room", void 0);
107
- _defineProperty(this, "client", void 0);
108
- _defineProperty(this, "pendingEventOrdering", void 0);
109
- _defineProperty(this, "processRootEventPromise", void 0);
110
65
  /**
111
66
  * Whether or not we need to fetch the initial set of events for the thread. We can
112
67
  * only do this if the server has support for it, so if it doesn't we just pretend
113
68
  * that we've already fetched them.
114
69
  */
115
70
  _defineProperty(this, "initialEventsFetched", !Thread.hasServerSideSupport);
116
- _defineProperty(this, "initalEventFetchProm", void 0);
117
71
  /**
118
72
  * An array of events to add to the timeline once the thread has been initialised
119
73
  * with server suppport.
@@ -189,6 +143,8 @@ export class Thread extends ReadReceipt {
189
143
  return _ref3.apply(this, arguments);
190
144
  };
191
145
  }());
146
+ this.id = id;
147
+ this.rootEvent = rootEvent;
192
148
  this.setMaxListeners(1000);
193
149
  if (!(opts !== null && opts !== void 0 && opts.room)) {
194
150
  // Logging/debugging for https://github.com/vector-im/element-web/issues/22141
@@ -440,13 +396,12 @@ export class Thread extends ReadReceipt {
440
396
  */
441
397
  processReceipts() {
442
398
  var receipts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
443
- for (var {
444
- eventId,
445
- receiptType,
446
- userId,
447
- receipt,
448
- synthetic
449
- } of receipts) {
399
+ for (var _ref5 of receipts) {
400
+ var eventId = _ref5.eventId;
401
+ var receiptType = _ref5.receiptType;
402
+ var userId = _ref5.userId;
403
+ var receipt = _ref5.receipt;
404
+ var synthetic = _ref5.synthetic;
450
405
  this.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);
451
406
  }
452
407
  }
@@ -616,7 +571,7 @@ export class Thread extends ReadReceipt {
616
571
  events[_key] = _arguments[_key];
617
572
  }
618
573
  return Promise.all(events.filter(isAnEncryptedThreadMessage).map(/*#__PURE__*/function () {
619
- var _ref4 = _asyncToGenerator(function* (event) {
574
+ var _ref6 = _asyncToGenerator(function* (event) {
620
575
  try {
621
576
  var relations = yield _this8.client.relations(_this8.roomId, event.getId(), RelationType.Replace, event.getType(), {
622
577
  limit: 1
@@ -631,7 +586,7 @@ export class Thread extends ReadReceipt {
631
586
  }
632
587
  });
633
588
  return function (_x6) {
634
- return _ref4.apply(this, arguments);
589
+ return _ref6.apply(this, arguments);
635
590
  };
636
591
  }()));
637
592
  }
@@ -689,8 +644,8 @@ export class Thread extends ReadReceipt {
689
644
  * This might be a synthesized event, if so, it will not emit any events to listeners.
690
645
  */
691
646
  get replyToEvent() {
692
- var _ref5, _this$lastPendingEven;
693
- return (_ref5 = (_this$lastPendingEven = this.lastPendingEvent) !== null && _this$lastPendingEven !== void 0 ? _this$lastPendingEven : this.lastEvent) !== null && _ref5 !== void 0 ? _ref5 : this.lastReply();
647
+ var _ref7, _this$lastPendingEven;
648
+ return (_ref7 = (_this$lastPendingEven = this.lastPendingEvent) !== null && _this$lastPendingEven !== void 0 ? _this$lastPendingEven : this.lastEvent) !== null && _ref7 !== void 0 ? _ref7 : this.lastReply();
694
649
  }
695
650
 
696
651
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"thread.js","names":["PendingEventOrdering","TypedReEmitter","RelationType","MatrixEvent","MatrixEventEvent","Direction","EventTimeline","EventTimelineSet","RoomEvent","ServerControlledNamespacedValue","logger","ReadReceipt","ReceiptType","Feature","ServerSupport","ThreadEvent","FeatureSupport","determineFeatureSupport","stable","unstable","Stable","Experimental","None","Thread","constructor","id","rootEvent","opts","_this","_opts$pendingEventOrd","this","_defineProperty","hasServerSideSupport","_asyncToGenerator","processRootEventPromise","undefined","event","redaction","isRelation","THREAD_RELATION_TYPE","name","room","eventShouldLiveIn","threadId","getId","status","replyCount","updatePendingReplyCount","emit","Update","_ref2","threadRootId","threadEvent","timeline","clearEventMetadata","lastEvent","_currentUserParticipated","Delete","_this$lastEvent","getAssociatedId","updateThreadMetadata","_x","_x2","_x3","apply","arguments","toStartOfTimeline","sender","getSender","shouldSendLocalEchoReceipt","addLocalEchoReceipt","Read","onEcho","_ref3","NewReply","_x4","_x5","setMaxListeners","Error","client","pendingEventOrdering","Chronological","timelineSet","timelineSupport","pendingEvents","reEmitter","reEmit","Timeline","TimelineReset","on","BeforeRedaction","onBeforeRedaction","Redaction","onRedaction","LocalEchoUpdated","onLocalEcho","onTimelineReset","onTimelineEvent","processReceipts","receipts","setEventMetadata","fetchRootEvent","_this2","eventData","fetchRoomEvent","roomId","mapper","getEventMapper","e","error","processEvent","setServerSideSupport","FILTER_RELATED_BY_SENDERS","setPreferUnstable","FILTER_RELATED_BY_REL_TYPES","setServerSideListSupport","hasServerSideListSupport","setServerSideFwdPaginationSupport","hasServerSideFwdPaginationSupport","_this$client$canSuppo","recursionSupport","canSupport","get","RelationsRecursion","Unsupported","_this$getReadReceiptF","oldReceiptEventId","getReadReceiptForUserId","eventId","receiptEvent","findEventById","getTs","roomState","getLiveTimeline","getState","FORWARDS","addEventToTimeline","liveTimeline","fromCache","addToState","insertEventIntoTimeline","addEvents","events","forEach","ev","addEvent","length","lastReply","isNewestReply","localTimestamp","decryptEventIfNeeded","Annotation","Replace","addRelatedThreadEvent","fetchEditsWhereNeeded","initialEventsFetched","_this$replayEvents","replayEvents","push","_this$timelineSet$rel","relations","aggregateChildEvent","_this$client$canSuppo2","_this3","receiptType","userId","receipt","synthetic","addReceiptToStructure","getRootEventBundledRelationship","getServerAggregatedRelation","processRootEvent","_this4","bundledRelationship","count","current_user_participated","_objectSpread","latest_event","room_id","unfilteredPendingEvents","Detached","getPendingEvents","filter","_this$lastEvent2","lastPendingEvent","pendingReplyCount","resetLiveTimeline","backPaginationToken","forwardPaginationToken","_this5","oldLive","newLive","newBackward","oldForward","res","createMessagesRequest","Forward","end","Backward","start","getPaginationToken","setPaginationToken","updateThreadFromRootEvent","_this6","_this7","initalEventFetchProm","addEventsToTimeline","paginateEventTimeline","backwards","_arguments","_this8","_this8$client$canSupp","_len","Array","_key","Promise","all","isAnEncryptedThreadMessage","map","_ref4","getType","limit","editEvent","makeReplaced","_x6","setThread","_event$event","unsigned","matches","i","replyToEvent","_ref5","_this$lastPendingEven","getEvents","has","hasCurrentUserParticipated","getUnfilteredTimelineSet","addReceipt","getEventReadUpTo","ignoreSynthesized","isCurrentUser","getUserId","beforeFirstThreadedReceipt","getOldestThreadedReceiptTs","lastReplyId","readUpToId","unthreadedReceipt","getLastUnthreadedReceiptFor","_this$timeline","_ev$getId","ts","hasUserReadEvent","_this$lastReply$getTs","_this$lastReply","_this$room$getLastUnt","_this$room$getLastUnt2","_this$lastReply$getTs2","_this$lastReply2","unthreadedReceiptTs","beforeLastUnthreadedReceipt","setUnread","type","setThreadUnreadNotificationCount","isEncrypted","isThreadRoot","ThreadFilterType","threadFilterTypeToFilter","My"],"sources":["../../src/models/thread.ts"],"sourcesContent":["/*\nCopyright 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 { type MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { type IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { EventTimelineSet, type EventTimelineSetHandlerMap } from \"./event-timeline-set.ts\";\nimport { type NotificationCountType, type Room, RoomEvent } from \"./room.ts\";\nimport { type RoomState } from \"./room-state.ts\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.ts\";\nimport { logger } from \"../logger.ts\";\nimport { ReadReceipt } from \"./read-receipt.ts\";\nimport { type CachedReceiptStructure, type Receipt, ReceiptType } from \"../@types/read_receipts.ts\";\nimport { Feature, ServerSupport } from \"../feature.ts\";\n\nexport enum ThreadEvent {\n New = \"Thread.new\",\n Update = \"Thread.update\",\n NewReply = \"Thread.newReply\",\n ViewThread = \"Thread.viewThread\",\n Delete = \"Thread.delete\",\n}\n\nexport type ThreadEmittedEvents = Exclude<ThreadEvent, ThreadEvent.New> | RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type ThreadEventHandlerMap = {\n [ThreadEvent.Update]: (thread: Thread) => void;\n [ThreadEvent.NewReply]: (thread: Thread, event: MatrixEvent) => void;\n [ThreadEvent.ViewThread]: () => void;\n [ThreadEvent.Delete]: (thread: Thread) => void;\n} & EventTimelineSetHandlerMap;\n\ninterface IThreadOpts {\n room: Room;\n client: MatrixClient;\n pendingEventOrdering?: PendingEventOrdering;\n receipts?: CachedReceiptStructure[];\n}\n\nexport enum FeatureSupport {\n None = 0,\n Experimental = 1,\n Stable = 2,\n}\n\nexport function determineFeatureSupport(stable: boolean, unstable: boolean): FeatureSupport {\n if (stable) {\n return FeatureSupport.Stable;\n } else if (unstable) {\n return FeatureSupport.Experimental;\n } else {\n return FeatureSupport.None;\n }\n}\n\nexport class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEventHandlerMap> {\n public static hasServerSideSupport = FeatureSupport.None;\n public static hasServerSideListSupport = FeatureSupport.None;\n public static hasServerSideFwdPaginationSupport = FeatureSupport.None;\n\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public readonly timelineSet: EventTimelineSet;\n\n private _currentUserParticipated = false;\n\n private reEmitter: TypedReEmitter<ThreadEmittedEvents, ThreadEventHandlerMap>;\n\n /**\n * The last event in this thread, if we don't yet have this in the timeline.\n *\n * When we run {@link processRootEvent} (which I think happens during the\n * setting-up of the thread), we set this to the event pointed to by the\n * server in `latest_event` [1] that came through with the thread root.\n *\n * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships\n *\n * Later, when we have populated the timeline, this is set to undefined, so\n * that methods like {@link replyToEvent} fall through to use lastReply,\n * which looks in the timeline for the latest event that is a \"thread reply\"\n * i.e. directly refers to the thread root with an m.thread relation.\n *\n * So it looks like this is only really relevant when initialEventsFetched\n * is false, because as soon as the initial events have been fetched, we\n * should have a proper chunk of timeline from the pagination fetch.\n *\n * If all replies in this thread are redacted, this is set to the root\n * event. I'm not clear what the meaning of this is, since usually after the\n * initial events have been fetched, lastEvent should be undefined.\n * In fact, the whole usage inside onRedaction looks suspect - it may be\n * that we were thinking lastEvent always refers to the actual last event,\n * but it only does so before initialEventsFetched becomes true.\n *\n * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd\n * think we probably mean {@link replyToEvent} there - we are trying not to\n * echo a duplicate event, and we probably want that behaviour even after\n * initialEventsFetched has become true.\n *\n * -- andyb\n */\n private lastEvent: MatrixEvent | undefined;\n\n private replyCount = 0;\n private lastPendingEvent: MatrixEvent | undefined;\n private pendingReplyCount = 0;\n\n public readonly room: Room;\n public readonly client: MatrixClient;\n private readonly pendingEventOrdering: PendingEventOrdering;\n private processRootEventPromise?: Promise<void>;\n\n /**\n * Whether or not we need to fetch the initial set of events for the thread. We can\n * only do this if the server has support for it, so if it doesn't we just pretend\n * that we've already fetched them.\n */\n public initialEventsFetched = !Thread.hasServerSideSupport;\n private initalEventFetchProm: Promise<boolean> | undefined;\n\n /**\n * An array of events to add to the timeline once the thread has been initialised\n * with server suppport.\n */\n public replayEvents: MatrixEvent[] | null = [];\n\n public constructor(\n public readonly id: string,\n public rootEvent: MatrixEvent | undefined,\n opts: IThreadOpts,\n ) {\n super();\n\n // each Event in the thread adds a reemitter, so we could hit the listener limit.\n this.setMaxListeners(1000);\n\n if (!opts?.room) {\n // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n // Hope is that we end up with a more obvious stack trace.\n throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n }\n\n this.room = opts.room;\n this.client = opts.client;\n this.pendingEventOrdering = opts.pendingEventOrdering ?? PendingEventOrdering.Chronological;\n this.timelineSet = new EventTimelineSet(\n this.room,\n {\n timelineSupport: true,\n pendingEvents: true,\n },\n this.client,\n this,\n );\n this.reEmitter = new TypedReEmitter(this);\n\n this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n this.room.on(RoomEvent.Redaction, this.onRedaction);\n this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);\n this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n\n this.processReceipts(opts.receipts);\n\n // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n // gappy sync and a thread around this event may already exist.\n this.updateThreadMetadata();\n this.setEventMetadata(this.rootEvent);\n }\n\n private onTimelineReset = async (): Promise<void> => {\n // We hit a gappy sync, ask the server for an update\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n };\n\n private async fetchRootEvent(): Promise<void> {\n // Always fetch the root event, even if we already have it, so we can get the latest\n // state (via unsigned).\n try {\n const eventData = await this.client.fetchRoomEvent(this.roomId, this.id);\n const mapper = this.client.getEventMapper();\n this.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n } catch (e) {\n logger.error(\"Failed to fetch thread root to construct thread with\", e);\n }\n await this.processEvent(this.rootEvent);\n }\n\n public static setServerSideSupport(status: FeatureSupport): void {\n Thread.hasServerSideSupport = status;\n // XXX: This global latching behaviour is really unexpected and means that you can't undo when moving to a server without support\n if (status !== FeatureSupport.Stable) {\n FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n THREAD_RELATION_TYPE.setPreferUnstable(true);\n }\n }\n\n public static setServerSideListSupport(status: FeatureSupport): void {\n Thread.hasServerSideListSupport = status;\n }\n\n public static setServerSideFwdPaginationSupport(status: FeatureSupport): void {\n Thread.hasServerSideFwdPaginationSupport = status;\n }\n\n private onBeforeRedaction = (event: MatrixEvent, redaction: MatrixEvent): void => {\n if (\n event?.isRelation(THREAD_RELATION_TYPE.name) &&\n this.room.eventShouldLiveIn(event).threadId === this.id &&\n event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction\n !redaction.status // only respect it when it succeeds\n ) {\n this.replyCount--;\n this.updatePendingReplyCount();\n this.emit(ThreadEvent.Update, this);\n }\n };\n\n private onRedaction = async (event: MatrixEvent, room: Room, threadRootId?: string): Promise<void> => {\n if (threadRootId !== this.id) return; // ignore redactions for other timelines\n if (this.replyCount <= 0) {\n for (const threadEvent of this.timeline) {\n this.clearEventMetadata(threadEvent);\n }\n this.lastEvent = this.rootEvent;\n this._currentUserParticipated = false;\n this.emit(ThreadEvent.Delete, this);\n } else {\n if (this.lastEvent?.getId() === event.getAssociatedId()) {\n // XXX: If our last event got redacted we query the server for the last event once again\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n }\n await this.updateThreadMetadata();\n }\n };\n\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n ): void => {\n // Add a synthesized receipt when paginating forward in the timeline\n if (!toStartOfTimeline) {\n const sender = event.getSender();\n if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.replyCount++;\n }\n }\n this.onEcho(event, toStartOfTimeline ?? false);\n };\n\n private shouldSendLocalEchoReceipt(sender: string, event: MatrixEvent): boolean {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n // Normally we add a local receipt, but if we don't have\n // recursion support, then events may arrive out of order, so we\n // only create a receipt if it's after our existing receipt.\n const oldReceiptEventId = this.getReadReceiptForUserId(sender)?.eventId;\n if (oldReceiptEventId) {\n const receiptEvent = this.findEventById(oldReceiptEventId);\n if (receiptEvent && receiptEvent.getTs() > event.getTs()) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n private onLocalEcho = (event: MatrixEvent): void => {\n this.onEcho(event, false);\n };\n\n private onEcho = async (event: MatrixEvent, toStartOfTimeline: boolean): Promise<void> => {\n if (event.threadRootId !== this.id) return; // ignore echoes for other timelines\n if (this.lastEvent === event) return; // ignore duplicate events\n await this.updateThreadMetadata();\n if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n // Clear the lastEvent and instead start tracking locally using lastReply\n this.lastEvent = undefined;\n this.emit(ThreadEvent.NewReply, this, event);\n };\n\n public get roomState(): RoomState {\n return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n }\n\n private addEventToTimeline(event: MatrixEvent, toStartOfTimeline: boolean): void {\n if (!this.findEventById(event.getId()!)) {\n this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline,\n fromCache: false,\n roomState: this.roomState,\n addToState: false,\n });\n }\n }\n\n /**\n * TEMPORARY. Only call this when MSC3981 is not available, and we have some\n * late-arriving events to insert, because we recursively found them as part\n * of populating a thread. When we have MSC3981 we won't need it, because\n * they will all be supplied by the homeserver in one request, and they will\n * already be in the right order in that response.\n * This is a copy of addEventToTimeline above, modified to call\n * insertEventIntoTimeline so this event is inserted into our best guess of\n * the right place based on timestamp. (We should be using Sync Order but we\n * don't have it.)\n *\n * @internal\n */\n public insertEventIntoTimeline(event: MatrixEvent): void {\n const eventId = event.getId();\n if (!eventId) {\n return;\n }\n // If the event is already in this thread, bail out\n if (this.findEventById(eventId)) {\n return;\n }\n this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);\n }\n\n public addEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));\n this.updateThreadMetadata();\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event - The event to add\n * @param toStartOfTimeline - whether the event is being added\n * to the start (and not the end) of the timeline.\n * @param emit - whether to emit the Update event if the thread was updated or not.\n */\n public addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): void {\n // Modify this event to point at our room's state, and mark its thread\n // as this.\n this.setEventMetadata(event);\n\n // Decide whether this event is going to be added at the end of the timeline.\n const lastReply = this.lastReply();\n const isNewestReply = !lastReply || event.localTimestamp >= lastReply!.localTimestamp;\n\n if (!Thread.hasServerSideSupport) {\n // When there's no server-side support, just add it to the end of the timeline.\n this.addEventToTimeline(event, toStartOfTimeline);\n this.client.decryptEventIfNeeded(event);\n } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n this.addRelatedThreadEvent(event, toStartOfTimeline);\n return;\n } else if (!toStartOfTimeline && isNewestReply) {\n // When we've asked for the event to be added to the end,\n // and this event belongs at the end, add it.\n this.addEventToTimeline(event, false);\n this.fetchEditsWhereNeeded(event);\n } else {\n // Otherwise, we should add it, but we suspect it is out of order.\n // This may be because we've just created the thread object and are\n // still fetching events, in which case add it where we think is sensible\n // and it will be removed and replaced with the events from the pagination\n // request once that completes.\n if (toStartOfTimeline) {\n // If we're adding at the start of the timeline, it doesn't\n // matter that it's out of order.\n this.addEventToTimeline(event, toStartOfTimeline);\n } else {\n // We think this event might be out of order, because isNewestReply\n // is false (otherwise we would have gone into the earlier if\n // clause), so try to insert it in the right place based on\n // timestamp.\n this.insertEventIntoTimeline(event);\n }\n }\n\n if (\n event.getId() !== this.id &&\n event.isRelation(THREAD_RELATION_TYPE.name) &&\n !toStartOfTimeline &&\n isNewestReply\n ) {\n // Clear the last event as we have the latest end of the timeline\n this.lastEvent = undefined;\n }\n\n if (emit) {\n this.emit(ThreadEvent.NewReply, this, event);\n this.updateThreadMetadata();\n }\n }\n\n private addRelatedThreadEvent(event: MatrixEvent, toStartOfTimeline: boolean): void {\n // If this event is not a direct member of the thread, but is a\n // reference to something that is, then we have two cases:\n\n if (!this.initialEventsFetched) {\n // Case 1: we haven't yet fetched events from the server. In\n // this case, when we do, the events we get back might only be\n // the first-order ones, so this event (which is second-order -\n // a reference to something directly in the thread) needs to be\n // kept so we can replay it when the first-order ones turn up.\n\n /**\n * A thread can be fully discovered via a single sync response\n * And when that's the case we still ask the server to do an initialisation\n * as it's the safest to ensure we have everything.\n * However when we are in that scenario we might loose annotation or edits\n *\n * This fix keeps a reference to those events and replay them once the thread\n * has been initialised properly.\n */\n this.replayEvents?.push(event);\n\n // For annotations (reactions), aggregate immediately (pre-init) to keep\n // reaction counts/summary visible while the thread is still initialising.\n // Only aggregate as child: parent aggregation is unnecessary here.\n if (event.isRelation(RelationType.Annotation)) {\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\n }\n } else {\n // Case 2: this is happening later, and we have a timeline. In\n // this case, these events might be out-of order.\n //\n // Specifically, if the server doesn't support recursion, so we\n // only get these events through sync, they might be coming\n // later than the first-order ones, so we insert them based on\n // timestamp (despite the problems with this documented in\n // #3325).\n //\n // If the server does support recursion, we should have got all\n // the interspersed events from the server when we fetched the\n // initial events, so if they are coming via sync they should be\n // the latest ones, so we can add them as normal.\n //\n // (Note that both insertEventIntoTimeline and addEventToTimeline\n // do nothing if we have seen this event before.)\n\n const recursionSupport =\n this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n this.insertEventIntoTimeline(event);\n } else {\n this.addEventToTimeline(event, toStartOfTimeline);\n }\n // Aggregation is handled by EventTimelineSet when inserting/adding.\n }\n }\n\n public async processEvent(event: MatrixEvent | null | undefined): Promise<void> {\n if (event) {\n this.setEventMetadata(event);\n await this.fetchEditsWhereNeeded(event);\n }\n }\n\n /**\n * Processes the receipts that were caught during initial sync\n * When clients become aware of a thread, they try to retrieve those read receipts\n * and apply them to the current thread\n * @param receipts - A collection of the receipts cached from initial sync\n */\n private processReceipts(receipts: CachedReceiptStructure[] = []): void {\n for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) {\n this.addReceiptToStructure(eventId, receiptType as ReceiptType, userId, receipt, synthetic);\n }\n }\n\n private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {\n return rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>(THREAD_RELATION_TYPE.name);\n }\n\n private async processRootEvent(): Promise<void> {\n const bundledRelationship = this.getRootEventBundledRelationship();\n if (Thread.hasServerSideSupport && bundledRelationship) {\n this.replyCount = bundledRelationship.count;\n this._currentUserParticipated = !!bundledRelationship.current_user_participated;\n\n const mapper = this.client.getEventMapper();\n // re-insert roomId\n this.lastEvent = mapper({\n ...bundledRelationship.latest_event,\n room_id: this.roomId,\n });\n this.updatePendingReplyCount();\n await this.processEvent(this.lastEvent);\n }\n }\n\n private updatePendingReplyCount(): void {\n const unfilteredPendingEvents =\n this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n const pendingEvents = unfilteredPendingEvents.filter(\n (ev) =>\n ev.threadRootId === this.id &&\n ev.isRelation(THREAD_RELATION_TYPE.name) &&\n ev.status !== null &&\n ev.getId() !== this.lastEvent?.getId(),\n );\n this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n this.pendingReplyCount = pendingEvents.length;\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n * set new pagination tokens on the old and the new timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public async resetLiveTimeline(\n backPaginationToken?: string | null,\n forwardPaginationToken?: string | null,\n ): Promise<void> {\n const oldLive = this.liveTimeline;\n this.timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n const newLive = this.liveTimeline;\n\n // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n //\n // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n //\n // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n // /messages does not return new tokens on requests with a limit of 0.\n // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n // anyway.\n\n let newBackward: string | undefined;\n let oldForward: string | undefined;\n if (backPaginationToken) {\n const res = await this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, Direction.Forward);\n newBackward = res.end;\n }\n if (forwardPaginationToken) {\n const res = await this.client.createMessagesRequest(\n this.roomId,\n forwardPaginationToken,\n 1,\n Direction.Backward,\n );\n oldForward = res.start;\n }\n // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n // occur today, but if the above issue is resolved, we'd have to go down this path.\n if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n oldLive.setPaginationToken(oldForward ?? null, Direction.Forward);\n }\n if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n newLive.setPaginationToken(newBackward ?? null, Direction.Backward);\n }\n }\n\n private async updateThreadFromRootEvent(): Promise<void> {\n if (Thread.hasServerSideSupport) {\n // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n // don't want the thread preview to be empty if we can avoid it\n if (!this.initialEventsFetched && !this.lastEvent) {\n await this.processRootEvent();\n }\n await this.fetchRootEvent();\n }\n await this.processRootEvent();\n }\n\n private async updateThreadMetadata(): Promise<void> {\n this.updatePendingReplyCount();\n\n if (!this.processRootEventPromise) {\n // We only want to do this once otherwise we end up rolling back to the last unsigned summary we have for the thread\n this.processRootEventPromise = this.updateThreadFromRootEvent();\n }\n await this.processRootEventPromise;\n\n if (!this.initialEventsFetched) {\n if (this.initalEventFetchProm) {\n await this.initalEventFetchProm;\n } else {\n // fetch initial events to allow proper pagination\n try {\n // clear out any events that were added before the pagination request\n // completed (eg. from sync). They'll be replaced by those from the pagination.\n // Really, we should do this after the pagination request completes, but\n // paginateEventTimeline does the request and adds the events in one go, so\n // this would need a refactor in order to do. It's therefore possible there's\n // a remaining race where an event comes in while the pagination request is\n // happening.\n this.timelineSet.resetLiveTimeline();\n // if the thread has regular events, this will just load the last reply.\n // if the thread is newly created, this will load the root event.\n if (this.replyCount === 0 && this.rootEvent) {\n this.timelineSet.addEventsToTimeline([this.rootEvent], true, false, this.liveTimeline, null);\n this.liveTimeline.setPaginationToken(null, Direction.Backward);\n } else {\n this.initalEventFetchProm = this.client.paginateEventTimeline(this.liveTimeline, {\n backwards: true,\n });\n await this.initalEventFetchProm;\n }\n // We have now fetched the initial events, so set the flag. We need to do this before\n // we actually add the events, so `this.addEvents` knows that it can now safely add\n // them rather than buffer them in the pending event list. The main thing is that this\n // must remain false while the async fetch happens, so we don't try to add events before\n // the pagination has finished. The important thing is that we're not await-ing anything\n // else between setting this and adding events, so no races.\n this.initialEventsFetched = true;\n for (const event of this.replayEvents!) {\n this.addEvent(event, false);\n }\n this.replayEvents = null;\n // just to make sure that, if we've created a timeline window for this thread before the thread itself\n // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);\n } catch (e) {\n logger.error(\"Failed to load start of newly created thread: \", e);\n this.initialEventsFetched = false;\n }\n }\n }\n\n this.emit(ThreadEvent.Update, this);\n }\n\n // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n private async fetchEditsWhereNeeded(...events: MatrixEvent[]): Promise<unknown> {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n if (recursionSupport === ServerSupport.Unsupported) {\n return Promise.all(\n events.filter(isAnEncryptedThreadMessage).map(async (event: MatrixEvent) => {\n try {\n const relations = await this.client.relations(\n this.roomId,\n event.getId()!,\n RelationType.Replace,\n event.getType(),\n {\n limit: 1,\n },\n );\n if (relations.events.length) {\n const editEvent = relations.events[0];\n event.makeReplaced(editEvent);\n this.insertEventIntoTimeline(editEvent);\n }\n } catch (e) {\n logger.error(\"Failed to load edits for encrypted thread event\", e);\n }\n }),\n );\n }\n }\n\n public setEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n EventTimeline.setEventMetadata(event, this.roomState, false);\n event.setThread(this);\n }\n }\n\n public clearEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n event.setThread(undefined);\n delete event.event?.unsigned?.[\"m.relations\"]?.[THREAD_RELATION_TYPE.name];\n }\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.timelineSet.findEventById(eventId);\n }\n\n /**\n * Return last reply to the thread, if known.\n */\n public lastReply(\n matches: (ev: MatrixEvent) => boolean = (ev): boolean => ev.isRelation(THREAD_RELATION_TYPE.name),\n ): MatrixEvent | null {\n for (let i = this.timeline.length - 1; i >= 0; i--) {\n const event = this.timeline[i];\n if (matches(event)) {\n return event;\n }\n }\n return null;\n }\n\n public get roomId(): string {\n return this.room.roomId;\n }\n\n /**\n * The number of messages in the thread\n * Only count rel_type=m.thread as we want to\n * exclude annotations from that number\n */\n public get length(): number {\n return this.replyCount + this.pendingReplyCount;\n }\n\n /**\n * A getter for the last event of the thread.\n * This might be a synthesized event, if so, it will not emit any events to listeners.\n */\n public get replyToEvent(): MatrixEvent | null {\n return this.lastPendingEvent ?? this.lastEvent ?? this.lastReply();\n }\n\n /**\n * The live event timeline for this thread.\n * @deprecated Present for backwards compatibility.\n * Use this.events instead\n * @returns The live event timeline for this thread.\n */\n public get timeline(): MatrixEvent[] {\n return this.events;\n }\n\n public get events(): MatrixEvent[] {\n return this.liveTimeline.getEvents();\n }\n\n public has(eventId: string): boolean {\n return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n }\n\n public get hasCurrentUserParticipated(): boolean {\n return this._currentUserParticipated;\n }\n\n public get liveTimeline(): EventTimeline {\n return this.timelineSet.getLiveTimeline();\n }\n\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSet;\n }\n\n public addReceipt(event: MatrixEvent, synthetic: boolean): void {\n throw new Error(\"Unsupported function on the thread model\");\n }\n\n /**\n * Get the ID of the event that a given user has read up to within this thread,\n * or null if we have received no read receipt (at all) from them.\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 event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized?: boolean): string | null {\n // TODO: we think the implementation here is not right. Here is a sketch\n // of the right answer:\n //\n // for event in timeline.events.reversed():\n // if room.hasUserReadEvent(event):\n // return event\n // return null\n //\n // If this is too slow, we might be able to improve it by trying walking\n // forward from the threaded receipt in this thread. We could alternate\n // between backwards-from-front and forwards-from-threaded-receipt to\n // improve our chances of hitting the right answer sooner.\n //\n // Either way, it's still fundamentally slow because we have to walk\n // events.\n //\n // We also might just want to limit the time we spend on this by giving\n // up after, say, 100 events.\n //\n // --- andyb\n\n const isCurrentUser = userId === this.client.getUserId();\n const lastReply = this.timeline[this.timeline.length - 1];\n if (isCurrentUser && lastReply) {\n // If the last activity in a thread is prior to the first threaded read receipt\n // sent in the room (suggesting that it was sent before the user started\n // using a client that supported threaded read receipts), we want to\n // consider this thread as read.\n const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n const lastReplyId = lastReply.getId();\n // Some unsent events do not have an ID, we do not want to consider them read\n if (beforeFirstThreadedReceipt && lastReplyId) {\n return lastReplyId;\n }\n }\n\n const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n // Check whether the unthreaded read receipt for that user is more recent\n // than the read receipt inside that thread.\n if (lastReply) {\n const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n if (!unthreadedReceipt) {\n return readUpToId;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n // If we encounter the `readUpToId` we do not need to look further\n // there is no \"more recent\" unthreaded read receipt\n if (ev.getId() === readUpToId) return readUpToId;\n\n // Inspecting events from most recent to oldest, we're checking\n // whether an unthreaded read receipt is more recent that the current event.\n // We usually prefer relying on the order of the DAG but in this scenario\n // it is not possible and we have to rely on timestamp\n if (ev.getTs() < unthreadedReceipt.ts) return ev.getId() ?? readUpToId;\n }\n }\n\n return readUpToId;\n }\n\n /**\n * Determine if the given user has read a particular event.\n *\n * It is invalid to call this method with an event that is not part of this thread.\n *\n * This is not a definitive check as it only checks the events that have been\n * loaded client-side 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 hasUserReadEvent(userId: string, eventId: string): boolean {\n if (userId === this.client.getUserId()) {\n // Consider an event read if it's part of a thread that is before the\n // first threaded receipt sent in that room. It is likely that it is\n // part of a thread that was created before MSC3771 was implemented.\n // Or before the last unthreaded receipt for the logged in user\n const beforeFirstThreadedReceipt =\n (this.lastReply()?.getTs() ?? 0) < this.room.getOldestThreadedReceiptTs();\n const unthreadedReceiptTs = this.room.getLastUnthreadedReceiptFor(userId)?.ts ?? 0;\n const beforeLastUnthreadedReceipt = (this?.lastReply()?.getTs() ?? 0) < unthreadedReceiptTs;\n if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n return true;\n }\n }\n\n return this.room.hasUserReadEvent(userId, eventId);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.room.getLastUnthreadedReceiptFor(userId);\n }\n}\n\n/**\n * Decide whether an event deserves to have its potential edits fetched.\n *\n * @returns true if this event is encrypted and is a message that is part of a\n * thread - either inside it, or a root.\n */\nfunction isAnEncryptedThreadMessage(event: MatrixEvent): boolean {\n return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);\n}\n\nexport const FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\n \"related_by_senders\",\n \"io.element.relation_senders\",\n);\nexport const FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\n \"related_by_rel_types\",\n \"io.element.relation_types\",\n);\nexport const THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\n\nexport enum ThreadFilterType {\n \"My\",\n \"All\",\n}\n\nexport function threadFilterTypeToFilter(type: ThreadFilterType | null): \"all\" | \"participated\" {\n switch (type) {\n case Thread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CAAC5H,IAAI,CAAC8M,2BAA2B,CAAClF,MAAM,CAAC;EACxD;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AALAtI,eAAA,CAzzBaR,MAAM,0BACsBP,cAAc,CAACM,IAAI;AAAAS,eAAA,CAD/CR,MAAM,8BAE0BP,cAAc,CAACM,IAAI;AAAAS,eAAA,CAFnDR,MAAM,uCAGmCP,cAAc,CAACM,IAAI;AA4zBzE,SAASmM,0BAA0BA,CAACrL,KAAkB,EAAW;EAC7D,OAAOA,KAAK,CAACmO,WAAW,CAAC,CAAC,KAAKnO,KAAK,CAACE,UAAU,CAACC,oBAAoB,CAACC,IAAI,CAAC,IAAIJ,KAAK,CAACoO,YAAY,CAAC;AACrG;AAEA,OAAO,IAAMxJ,yBAAyB,GAAG,IAAIvG,+BAA+B,CACxE,oBAAoB,EACpB,6BACJ,CAAC;AACD,OAAO,IAAMyG,2BAA2B,GAAG,IAAIzG,+BAA+B,CAC1E,sBAAsB,EACtB,2BACJ,CAAC;AACD,OAAO,IAAM8B,oBAAoB,GAAG,IAAI9B,+BAA+B,CAAC,UAAU,EAAE,mBAAmB,CAAC;AAExG,WAAYgQ,gBAAgB,0BAAhBA,gBAAgB;EAAhBA,gBAAgB,CAAhBA,gBAAgB;EAAhBA,gBAAgB,CAAhBA,gBAAgB;EAAA,OAAhBA,gBAAgB;AAAA;AAK5B,OAAO,SAASC,wBAAwBA,CAACL,IAA6B,EAA0B;EAC5F,QAAQA,IAAI;IACR,KAAKI,gBAAgB,CAACE,EAAE;MACpB,OAAO,cAAc;IACzB;MACI,OAAO,KAAK;EACpB;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"thread.js","names":["PendingEventOrdering","TypedReEmitter","RelationType","MatrixEvent","MatrixEventEvent","Direction","EventTimeline","EventTimelineSet","RoomEvent","ServerControlledNamespacedValue","logger","ReadReceipt","ReceiptType","Feature","ServerSupport","ThreadEvent","FeatureSupport","determineFeatureSupport","stable","unstable","Stable","Experimental","None","Thread","constructor","id","rootEvent","opts","_this","_opts$pendingEventOrd","this","_defineProperty","hasServerSideSupport","_asyncToGenerator","processRootEventPromise","undefined","event","redaction","isRelation","THREAD_RELATION_TYPE","name","room","eventShouldLiveIn","threadId","getId","status","replyCount","updatePendingReplyCount","emit","Update","_ref2","threadRootId","threadEvent","timeline","clearEventMetadata","lastEvent","_currentUserParticipated","Delete","_this$lastEvent","getAssociatedId","updateThreadMetadata","_x","_x2","_x3","apply","arguments","toStartOfTimeline","sender","getSender","shouldSendLocalEchoReceipt","addLocalEchoReceipt","Read","onEcho","_ref3","NewReply","_x4","_x5","setMaxListeners","Error","client","pendingEventOrdering","Chronological","timelineSet","timelineSupport","pendingEvents","reEmitter","reEmit","Timeline","TimelineReset","on","BeforeRedaction","onBeforeRedaction","Redaction","onRedaction","LocalEchoUpdated","onLocalEcho","onTimelineReset","onTimelineEvent","processReceipts","receipts","setEventMetadata","fetchRootEvent","_this2","eventData","fetchRoomEvent","roomId","mapper","getEventMapper","e","error","processEvent","setServerSideSupport","FILTER_RELATED_BY_SENDERS","setPreferUnstable","FILTER_RELATED_BY_REL_TYPES","setServerSideListSupport","hasServerSideListSupport","setServerSideFwdPaginationSupport","hasServerSideFwdPaginationSupport","_this$client$canSuppo","recursionSupport","canSupport","get","RelationsRecursion","Unsupported","_this$getReadReceiptF","oldReceiptEventId","getReadReceiptForUserId","eventId","receiptEvent","findEventById","getTs","roomState","getLiveTimeline","getState","FORWARDS","addEventToTimeline","liveTimeline","fromCache","addToState","insertEventIntoTimeline","addEvents","events","forEach","ev","addEvent","length","lastReply","isNewestReply","localTimestamp","decryptEventIfNeeded","Annotation","Replace","addRelatedThreadEvent","fetchEditsWhereNeeded","initialEventsFetched","_this$replayEvents","replayEvents","push","_this$timelineSet$rel","relations","aggregateChildEvent","_this$client$canSuppo2","_this3","_ref5","receiptType","userId","receipt","synthetic","addReceiptToStructure","getRootEventBundledRelationship","getServerAggregatedRelation","processRootEvent","_this4","bundledRelationship","count","current_user_participated","_objectSpread","latest_event","room_id","unfilteredPendingEvents","Detached","getPendingEvents","filter","_this$lastEvent2","lastPendingEvent","pendingReplyCount","resetLiveTimeline","backPaginationToken","forwardPaginationToken","_this5","oldLive","newLive","newBackward","oldForward","res","createMessagesRequest","Forward","end","Backward","start","getPaginationToken","setPaginationToken","updateThreadFromRootEvent","_this6","_this7","initalEventFetchProm","addEventsToTimeline","paginateEventTimeline","backwards","_arguments","_this8","_this8$client$canSupp","_len","Array","_key","Promise","all","isAnEncryptedThreadMessage","map","_ref6","getType","limit","editEvent","makeReplaced","_x6","setThread","_event$event","unsigned","matches","i","replyToEvent","_ref7","_this$lastPendingEven","getEvents","has","hasCurrentUserParticipated","getUnfilteredTimelineSet","addReceipt","getEventReadUpTo","ignoreSynthesized","isCurrentUser","getUserId","beforeFirstThreadedReceipt","getOldestThreadedReceiptTs","lastReplyId","readUpToId","unthreadedReceipt","getLastUnthreadedReceiptFor","_this$timeline","_ev$getId","ts","hasUserReadEvent","_this$lastReply$getTs","_this$lastReply","_this$room$getLastUnt","_this$room$getLastUnt2","_this$lastReply$getTs2","_this$lastReply2","unthreadedReceiptTs","beforeLastUnthreadedReceipt","setUnread","type","setThreadUnreadNotificationCount","isEncrypted","isThreadRoot","ThreadFilterType","threadFilterTypeToFilter","My"],"sources":["../../src/models/thread.ts"],"sourcesContent":["/*\nCopyright 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 { type MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { RelationType } from \"../@types/event.ts\";\nimport { type IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from \"./event.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { EventTimelineSet, type EventTimelineSetHandlerMap } from \"./event-timeline-set.ts\";\nimport { type NotificationCountType, type Room, RoomEvent } from \"./room.ts\";\nimport { type RoomState } from \"./room-state.ts\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.ts\";\nimport { logger } from \"../logger.ts\";\nimport { ReadReceipt } from \"./read-receipt.ts\";\nimport { type CachedReceiptStructure, type Receipt, ReceiptType } from \"../@types/read_receipts.ts\";\nimport { Feature, ServerSupport } from \"../feature.ts\";\n\nexport enum ThreadEvent {\n New = \"Thread.new\",\n Update = \"Thread.update\",\n NewReply = \"Thread.newReply\",\n ViewThread = \"Thread.viewThread\",\n Delete = \"Thread.delete\",\n}\n\nexport type ThreadEmittedEvents = Exclude<ThreadEvent, ThreadEvent.New> | RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type ThreadEventHandlerMap = {\n [ThreadEvent.Update]: (thread: Thread) => void;\n [ThreadEvent.NewReply]: (thread: Thread, event: MatrixEvent) => void;\n [ThreadEvent.ViewThread]: () => void;\n [ThreadEvent.Delete]: (thread: Thread) => void;\n} & EventTimelineSetHandlerMap;\n\ninterface IThreadOpts {\n room: Room;\n client: MatrixClient;\n pendingEventOrdering?: PendingEventOrdering;\n receipts?: CachedReceiptStructure[];\n}\n\nexport enum FeatureSupport {\n None = 0,\n Experimental = 1,\n Stable = 2,\n}\n\nexport function determineFeatureSupport(stable: boolean, unstable: boolean): FeatureSupport {\n if (stable) {\n return FeatureSupport.Stable;\n } else if (unstable) {\n return FeatureSupport.Experimental;\n } else {\n return FeatureSupport.None;\n }\n}\n\nexport class Thread extends ReadReceipt<ThreadEmittedEvents, ThreadEventHandlerMap> {\n public static hasServerSideSupport = FeatureSupport.None;\n public static hasServerSideListSupport = FeatureSupport.None;\n public static hasServerSideFwdPaginationSupport = FeatureSupport.None;\n\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public readonly timelineSet: EventTimelineSet;\n\n private _currentUserParticipated = false;\n\n private reEmitter: TypedReEmitter<ThreadEmittedEvents, ThreadEventHandlerMap>;\n\n /**\n * The last event in this thread, if we don't yet have this in the timeline.\n *\n * When we run {@link processRootEvent} (which I think happens during the\n * setting-up of the thread), we set this to the event pointed to by the\n * server in `latest_event` [1] that came through with the thread root.\n *\n * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships\n *\n * Later, when we have populated the timeline, this is set to undefined, so\n * that methods like {@link replyToEvent} fall through to use lastReply,\n * which looks in the timeline for the latest event that is a \"thread reply\"\n * i.e. directly refers to the thread root with an m.thread relation.\n *\n * So it looks like this is only really relevant when initialEventsFetched\n * is false, because as soon as the initial events have been fetched, we\n * should have a proper chunk of timeline from the pagination fetch.\n *\n * If all replies in this thread are redacted, this is set to the root\n * event. I'm not clear what the meaning of this is, since usually after the\n * initial events have been fetched, lastEvent should be undefined.\n * In fact, the whole usage inside onRedaction looks suspect - it may be\n * that we were thinking lastEvent always refers to the actual last event,\n * but it only does so before initialEventsFetched becomes true.\n *\n * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd\n * think we probably mean {@link replyToEvent} there - we are trying not to\n * echo a duplicate event, and we probably want that behaviour even after\n * initialEventsFetched has become true.\n *\n * -- andyb\n */\n private lastEvent: MatrixEvent | undefined;\n\n private replyCount = 0;\n private lastPendingEvent: MatrixEvent | undefined;\n private pendingReplyCount = 0;\n\n public readonly room: Room;\n public readonly client: MatrixClient;\n private readonly pendingEventOrdering: PendingEventOrdering;\n private processRootEventPromise?: Promise<void>;\n\n /**\n * Whether or not we need to fetch the initial set of events for the thread. We can\n * only do this if the server has support for it, so if it doesn't we just pretend\n * that we've already fetched them.\n */\n public initialEventsFetched = !Thread.hasServerSideSupport;\n private initalEventFetchProm: Promise<boolean> | undefined;\n\n /**\n * An array of events to add to the timeline once the thread has been initialised\n * with server suppport.\n */\n public replayEvents: MatrixEvent[] | null = [];\n\n public constructor(\n public readonly id: string,\n public rootEvent: MatrixEvent | undefined,\n opts: IThreadOpts,\n ) {\n super();\n\n // each Event in the thread adds a reemitter, so we could hit the listener limit.\n this.setMaxListeners(1000);\n\n if (!opts?.room) {\n // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n // Hope is that we end up with a more obvious stack trace.\n throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n }\n\n this.room = opts.room;\n this.client = opts.client;\n this.pendingEventOrdering = opts.pendingEventOrdering ?? PendingEventOrdering.Chronological;\n this.timelineSet = new EventTimelineSet(\n this.room,\n {\n timelineSupport: true,\n pendingEvents: true,\n },\n this.client,\n this,\n );\n this.reEmitter = new TypedReEmitter(this);\n\n this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n this.room.on(RoomEvent.Redaction, this.onRedaction);\n this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);\n this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n\n this.processReceipts(opts.receipts);\n\n // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n // gappy sync and a thread around this event may already exist.\n this.updateThreadMetadata();\n this.setEventMetadata(this.rootEvent);\n }\n\n private onTimelineReset = async (): Promise<void> => {\n // We hit a gappy sync, ask the server for an update\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n };\n\n private async fetchRootEvent(): Promise<void> {\n // Always fetch the root event, even if we already have it, so we can get the latest\n // state (via unsigned).\n try {\n const eventData = await this.client.fetchRoomEvent(this.roomId, this.id);\n const mapper = this.client.getEventMapper();\n this.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n } catch (e) {\n logger.error(\"Failed to fetch thread root to construct thread with\", e);\n }\n await this.processEvent(this.rootEvent);\n }\n\n public static setServerSideSupport(status: FeatureSupport): void {\n Thread.hasServerSideSupport = status;\n // XXX: This global latching behaviour is really unexpected and means that you can't undo when moving to a server without support\n if (status !== FeatureSupport.Stable) {\n FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n THREAD_RELATION_TYPE.setPreferUnstable(true);\n }\n }\n\n public static setServerSideListSupport(status: FeatureSupport): void {\n Thread.hasServerSideListSupport = status;\n }\n\n public static setServerSideFwdPaginationSupport(status: FeatureSupport): void {\n Thread.hasServerSideFwdPaginationSupport = status;\n }\n\n private onBeforeRedaction = (event: MatrixEvent, redaction: MatrixEvent): void => {\n if (\n event?.isRelation(THREAD_RELATION_TYPE.name) &&\n this.room.eventShouldLiveIn(event).threadId === this.id &&\n event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction\n !redaction.status // only respect it when it succeeds\n ) {\n this.replyCount--;\n this.updatePendingReplyCount();\n this.emit(ThreadEvent.Update, this);\n }\n };\n\n private onRedaction = async (event: MatrixEvent, room: Room, threadRootId?: string): Promise<void> => {\n if (threadRootId !== this.id) return; // ignore redactions for other timelines\n if (this.replyCount <= 0) {\n for (const threadEvent of this.timeline) {\n this.clearEventMetadata(threadEvent);\n }\n this.lastEvent = this.rootEvent;\n this._currentUserParticipated = false;\n this.emit(ThreadEvent.Delete, this);\n } else {\n if (this.lastEvent?.getId() === event.getAssociatedId()) {\n // XXX: If our last event got redacted we query the server for the last event once again\n await this.processRootEventPromise;\n this.processRootEventPromise = undefined;\n }\n await this.updateThreadMetadata();\n }\n };\n\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n ): void => {\n // Add a synthesized receipt when paginating forward in the timeline\n if (!toStartOfTimeline) {\n const sender = event.getSender();\n if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.replyCount++;\n }\n }\n this.onEcho(event, toStartOfTimeline ?? false);\n };\n\n private shouldSendLocalEchoReceipt(sender: string, event: MatrixEvent): boolean {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n // Normally we add a local receipt, but if we don't have\n // recursion support, then events may arrive out of order, so we\n // only create a receipt if it's after our existing receipt.\n const oldReceiptEventId = this.getReadReceiptForUserId(sender)?.eventId;\n if (oldReceiptEventId) {\n const receiptEvent = this.findEventById(oldReceiptEventId);\n if (receiptEvent && receiptEvent.getTs() > event.getTs()) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n private onLocalEcho = (event: MatrixEvent): void => {\n this.onEcho(event, false);\n };\n\n private onEcho = async (event: MatrixEvent, toStartOfTimeline: boolean): Promise<void> => {\n if (event.threadRootId !== this.id) return; // ignore echoes for other timelines\n if (this.lastEvent === event) return; // ignore duplicate events\n await this.updateThreadMetadata();\n if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n // Clear the lastEvent and instead start tracking locally using lastReply\n this.lastEvent = undefined;\n this.emit(ThreadEvent.NewReply, this, event);\n };\n\n public get roomState(): RoomState {\n return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n }\n\n private addEventToTimeline(event: MatrixEvent, toStartOfTimeline: boolean): void {\n if (!this.findEventById(event.getId()!)) {\n this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline,\n fromCache: false,\n roomState: this.roomState,\n addToState: false,\n });\n }\n }\n\n /**\n * TEMPORARY. Only call this when MSC3981 is not available, and we have some\n * late-arriving events to insert, because we recursively found them as part\n * of populating a thread. When we have MSC3981 we won't need it, because\n * they will all be supplied by the homeserver in one request, and they will\n * already be in the right order in that response.\n * This is a copy of addEventToTimeline above, modified to call\n * insertEventIntoTimeline so this event is inserted into our best guess of\n * the right place based on timestamp. (We should be using Sync Order but we\n * don't have it.)\n *\n * @internal\n */\n public insertEventIntoTimeline(event: MatrixEvent): void {\n const eventId = event.getId();\n if (!eventId) {\n return;\n }\n // If the event is already in this thread, bail out\n if (this.findEventById(eventId)) {\n return;\n }\n this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);\n }\n\n public addEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));\n this.updateThreadMetadata();\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event - The event to add\n * @param toStartOfTimeline - whether the event is being added\n * to the start (and not the end) of the timeline.\n * @param emit - whether to emit the Update event if the thread was updated or not.\n */\n public addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): void {\n // Modify this event to point at our room's state, and mark its thread\n // as this.\n this.setEventMetadata(event);\n\n // Decide whether this event is going to be added at the end of the timeline.\n const lastReply = this.lastReply();\n const isNewestReply = !lastReply || event.localTimestamp >= lastReply!.localTimestamp;\n\n if (!Thread.hasServerSideSupport) {\n // When there's no server-side support, just add it to the end of the timeline.\n this.addEventToTimeline(event, toStartOfTimeline);\n this.client.decryptEventIfNeeded(event);\n } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n this.addRelatedThreadEvent(event, toStartOfTimeline);\n return;\n } else if (!toStartOfTimeline && isNewestReply) {\n // When we've asked for the event to be added to the end,\n // and this event belongs at the end, add it.\n this.addEventToTimeline(event, false);\n this.fetchEditsWhereNeeded(event);\n } else {\n // Otherwise, we should add it, but we suspect it is out of order.\n // This may be because we've just created the thread object and are\n // still fetching events, in which case add it where we think is sensible\n // and it will be removed and replaced with the events from the pagination\n // request once that completes.\n if (toStartOfTimeline) {\n // If we're adding at the start of the timeline, it doesn't\n // matter that it's out of order.\n this.addEventToTimeline(event, toStartOfTimeline);\n } else {\n // We think this event might be out of order, because isNewestReply\n // is false (otherwise we would have gone into the earlier if\n // clause), so try to insert it in the right place based on\n // timestamp.\n this.insertEventIntoTimeline(event);\n }\n }\n\n if (\n event.getId() !== this.id &&\n event.isRelation(THREAD_RELATION_TYPE.name) &&\n !toStartOfTimeline &&\n isNewestReply\n ) {\n // Clear the last event as we have the latest end of the timeline\n this.lastEvent = undefined;\n }\n\n if (emit) {\n this.emit(ThreadEvent.NewReply, this, event);\n this.updateThreadMetadata();\n }\n }\n\n private addRelatedThreadEvent(event: MatrixEvent, toStartOfTimeline: boolean): void {\n // If this event is not a direct member of the thread, but is a\n // reference to something that is, then we have two cases:\n\n if (!this.initialEventsFetched) {\n // Case 1: we haven't yet fetched events from the server. In\n // this case, when we do, the events we get back might only be\n // the first-order ones, so this event (which is second-order -\n // a reference to something directly in the thread) needs to be\n // kept so we can replay it when the first-order ones turn up.\n\n /**\n * A thread can be fully discovered via a single sync response\n * And when that's the case we still ask the server to do an initialisation\n * as it's the safest to ensure we have everything.\n * However when we are in that scenario we might loose annotation or edits\n *\n * This fix keeps a reference to those events and replay them once the thread\n * has been initialised properly.\n */\n this.replayEvents?.push(event);\n\n // For annotations (reactions), aggregate immediately (pre-init) to keep\n // reaction counts/summary visible while the thread is still initialising.\n // Only aggregate as child: parent aggregation is unnecessary here.\n if (event.isRelation(RelationType.Annotation)) {\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\n }\n } else {\n // Case 2: this is happening later, and we have a timeline. In\n // this case, these events might be out-of order.\n //\n // Specifically, if the server doesn't support recursion, so we\n // only get these events through sync, they might be coming\n // later than the first-order ones, so we insert them based on\n // timestamp (despite the problems with this documented in\n // #3325).\n //\n // If the server does support recursion, we should have got all\n // the interspersed events from the server when we fetched the\n // initial events, so if they are coming via sync they should be\n // the latest ones, so we can add them as normal.\n //\n // (Note that both insertEventIntoTimeline and addEventToTimeline\n // do nothing if we have seen this event before.)\n\n const recursionSupport =\n this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n\n if (recursionSupport === ServerSupport.Unsupported) {\n this.insertEventIntoTimeline(event);\n } else {\n this.addEventToTimeline(event, toStartOfTimeline);\n }\n // Aggregation is handled by EventTimelineSet when inserting/adding.\n }\n }\n\n public async processEvent(event: MatrixEvent | null | undefined): Promise<void> {\n if (event) {\n this.setEventMetadata(event);\n await this.fetchEditsWhereNeeded(event);\n }\n }\n\n /**\n * Processes the receipts that were caught during initial sync\n * When clients become aware of a thread, they try to retrieve those read receipts\n * and apply them to the current thread\n * @param receipts - A collection of the receipts cached from initial sync\n */\n private processReceipts(receipts: CachedReceiptStructure[] = []): void {\n for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) {\n this.addReceiptToStructure(eventId, receiptType as ReceiptType, userId, receipt, synthetic);\n }\n }\n\n private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {\n return rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>(THREAD_RELATION_TYPE.name);\n }\n\n private async processRootEvent(): Promise<void> {\n const bundledRelationship = this.getRootEventBundledRelationship();\n if (Thread.hasServerSideSupport && bundledRelationship) {\n this.replyCount = bundledRelationship.count;\n this._currentUserParticipated = !!bundledRelationship.current_user_participated;\n\n const mapper = this.client.getEventMapper();\n // re-insert roomId\n this.lastEvent = mapper({\n ...bundledRelationship.latest_event,\n room_id: this.roomId,\n });\n this.updatePendingReplyCount();\n await this.processEvent(this.lastEvent);\n }\n }\n\n private updatePendingReplyCount(): void {\n const unfilteredPendingEvents =\n this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n const pendingEvents = unfilteredPendingEvents.filter(\n (ev) =>\n ev.threadRootId === this.id &&\n ev.isRelation(THREAD_RELATION_TYPE.name) &&\n ev.status !== null &&\n ev.getId() !== this.lastEvent?.getId(),\n );\n this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n this.pendingReplyCount = pendingEvents.length;\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n * set new pagination tokens on the old and the new timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public async resetLiveTimeline(\n backPaginationToken?: string | null,\n forwardPaginationToken?: string | null,\n ): Promise<void> {\n const oldLive = this.liveTimeline;\n this.timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n const newLive = this.liveTimeline;\n\n // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n //\n // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n //\n // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n // /messages does not return new tokens on requests with a limit of 0.\n // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n // anyway.\n\n let newBackward: string | undefined;\n let oldForward: string | undefined;\n if (backPaginationToken) {\n const res = await this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, Direction.Forward);\n newBackward = res.end;\n }\n if (forwardPaginationToken) {\n const res = await this.client.createMessagesRequest(\n this.roomId,\n forwardPaginationToken,\n 1,\n Direction.Backward,\n );\n oldForward = res.start;\n }\n // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n // occur today, but if the above issue is resolved, we'd have to go down this path.\n if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n oldLive.setPaginationToken(oldForward ?? null, Direction.Forward);\n }\n if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n newLive.setPaginationToken(newBackward ?? null, Direction.Backward);\n }\n }\n\n private async updateThreadFromRootEvent(): Promise<void> {\n if (Thread.hasServerSideSupport) {\n // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n // don't want the thread preview to be empty if we can avoid it\n if (!this.initialEventsFetched && !this.lastEvent) {\n await this.processRootEvent();\n }\n await this.fetchRootEvent();\n }\n await this.processRootEvent();\n }\n\n private async updateThreadMetadata(): Promise<void> {\n this.updatePendingReplyCount();\n\n if (!this.processRootEventPromise) {\n // We only want to do this once otherwise we end up rolling back to the last unsigned summary we have for the thread\n this.processRootEventPromise = this.updateThreadFromRootEvent();\n }\n await this.processRootEventPromise;\n\n if (!this.initialEventsFetched) {\n if (this.initalEventFetchProm) {\n await this.initalEventFetchProm;\n } else {\n // fetch initial events to allow proper pagination\n try {\n // clear out any events that were added before the pagination request\n // completed (eg. from sync). They'll be replaced by those from the pagination.\n // Really, we should do this after the pagination request completes, but\n // paginateEventTimeline does the request and adds the events in one go, so\n // this would need a refactor in order to do. It's therefore possible there's\n // a remaining race where an event comes in while the pagination request is\n // happening.\n this.timelineSet.resetLiveTimeline();\n // if the thread has regular events, this will just load the last reply.\n // if the thread is newly created, this will load the root event.\n if (this.replyCount === 0 && this.rootEvent) {\n this.timelineSet.addEventsToTimeline([this.rootEvent], true, false, this.liveTimeline, null);\n this.liveTimeline.setPaginationToken(null, Direction.Backward);\n } else {\n this.initalEventFetchProm = this.client.paginateEventTimeline(this.liveTimeline, {\n backwards: true,\n });\n await this.initalEventFetchProm;\n }\n // We have now fetched the initial events, so set the flag. We need to do this before\n // we actually add the events, so `this.addEvents` knows that it can now safely add\n // them rather than buffer them in the pending event list. The main thing is that this\n // must remain false while the async fetch happens, so we don't try to add events before\n // the pagination has finished. The important thing is that we're not await-ing anything\n // else between setting this and adding events, so no races.\n this.initialEventsFetched = true;\n for (const event of this.replayEvents!) {\n this.addEvent(event, false);\n }\n this.replayEvents = null;\n // just to make sure that, if we've created a timeline window for this thread before the thread itself\n // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);\n } catch (e) {\n logger.error(\"Failed to load start of newly created thread: \", e);\n this.initialEventsFetched = false;\n }\n }\n }\n\n this.emit(ThreadEvent.Update, this);\n }\n\n // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n private async fetchEditsWhereNeeded(...events: MatrixEvent[]): Promise<unknown> {\n const recursionSupport = this.client.canSupport.get(Feature.RelationsRecursion) ?? ServerSupport.Unsupported;\n if (recursionSupport === ServerSupport.Unsupported) {\n return Promise.all(\n events.filter(isAnEncryptedThreadMessage).map(async (event: MatrixEvent) => {\n try {\n const relations = await this.client.relations(\n this.roomId,\n event.getId()!,\n RelationType.Replace,\n event.getType(),\n {\n limit: 1,\n },\n );\n if (relations.events.length) {\n const editEvent = relations.events[0];\n event.makeReplaced(editEvent);\n this.insertEventIntoTimeline(editEvent);\n }\n } catch (e) {\n logger.error(\"Failed to load edits for encrypted thread event\", e);\n }\n }),\n );\n }\n }\n\n public setEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n EventTimeline.setEventMetadata(event, this.roomState, false);\n event.setThread(this);\n }\n }\n\n public clearEventMetadata(event: MatrixEvent | null | undefined): void {\n if (event) {\n event.setThread(undefined);\n delete event.event?.unsigned?.[\"m.relations\"]?.[THREAD_RELATION_TYPE.name];\n }\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.timelineSet.findEventById(eventId);\n }\n\n /**\n * Return last reply to the thread, if known.\n */\n public lastReply(\n matches: (ev: MatrixEvent) => boolean = (ev): boolean => ev.isRelation(THREAD_RELATION_TYPE.name),\n ): MatrixEvent | null {\n for (let i = this.timeline.length - 1; i >= 0; i--) {\n const event = this.timeline[i];\n if (matches(event)) {\n return event;\n }\n }\n return null;\n }\n\n public get roomId(): string {\n return this.room.roomId;\n }\n\n /**\n * The number of messages in the thread\n * Only count rel_type=m.thread as we want to\n * exclude annotations from that number\n */\n public get length(): number {\n return this.replyCount + this.pendingReplyCount;\n }\n\n /**\n * A getter for the last event of the thread.\n * This might be a synthesized event, if so, it will not emit any events to listeners.\n */\n public get replyToEvent(): MatrixEvent | null {\n return this.lastPendingEvent ?? this.lastEvent ?? this.lastReply();\n }\n\n /**\n * The live event timeline for this thread.\n * @deprecated Present for backwards compatibility.\n * Use this.events instead\n * @returns The live event timeline for this thread.\n */\n public get timeline(): MatrixEvent[] {\n return this.events;\n }\n\n public get events(): MatrixEvent[] {\n return this.liveTimeline.getEvents();\n }\n\n public has(eventId: string): boolean {\n return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n }\n\n public get hasCurrentUserParticipated(): boolean {\n return this._currentUserParticipated;\n }\n\n public get liveTimeline(): EventTimeline {\n return this.timelineSet.getLiveTimeline();\n }\n\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSet;\n }\n\n public addReceipt(event: MatrixEvent, synthetic: boolean): void {\n throw new Error(\"Unsupported function on the thread model\");\n }\n\n /**\n * Get the ID of the event that a given user has read up to within this thread,\n * or null if we have received no read receipt (at all) from them.\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 event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized?: boolean): string | null {\n // TODO: we think the implementation here is not right. Here is a sketch\n // of the right answer:\n //\n // for event in timeline.events.reversed():\n // if room.hasUserReadEvent(event):\n // return event\n // return null\n //\n // If this is too slow, we might be able to improve it by trying walking\n // forward from the threaded receipt in this thread. We could alternate\n // between backwards-from-front and forwards-from-threaded-receipt to\n // improve our chances of hitting the right answer sooner.\n //\n // Either way, it's still fundamentally slow because we have to walk\n // events.\n //\n // We also might just want to limit the time we spend on this by giving\n // up after, say, 100 events.\n //\n // --- andyb\n\n const isCurrentUser = userId === this.client.getUserId();\n const lastReply = this.timeline[this.timeline.length - 1];\n if (isCurrentUser && lastReply) {\n // If the last activity in a thread is prior to the first threaded read receipt\n // sent in the room (suggesting that it was sent before the user started\n // using a client that supported threaded read receipts), we want to\n // consider this thread as read.\n const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n const lastReplyId = lastReply.getId();\n // Some unsent events do not have an ID, we do not want to consider them read\n if (beforeFirstThreadedReceipt && lastReplyId) {\n return lastReplyId;\n }\n }\n\n const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n // Check whether the unthreaded read receipt for that user is more recent\n // than the read receipt inside that thread.\n if (lastReply) {\n const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n if (!unthreadedReceipt) {\n return readUpToId;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n // If we encounter the `readUpToId` we do not need to look further\n // there is no \"more recent\" unthreaded read receipt\n if (ev.getId() === readUpToId) return readUpToId;\n\n // Inspecting events from most recent to oldest, we're checking\n // whether an unthreaded read receipt is more recent that the current event.\n // We usually prefer relying on the order of the DAG but in this scenario\n // it is not possible and we have to rely on timestamp\n if (ev.getTs() < unthreadedReceipt.ts) return ev.getId() ?? readUpToId;\n }\n }\n\n return readUpToId;\n }\n\n /**\n * Determine if the given user has read a particular event.\n *\n * It is invalid to call this method with an event that is not part of this thread.\n *\n * This is not a definitive check as it only checks the events that have been\n * loaded client-side 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 hasUserReadEvent(userId: string, eventId: string): boolean {\n if (userId === this.client.getUserId()) {\n // Consider an event read if it's part of a thread that is before the\n // first threaded receipt sent in that room. It is likely that it is\n // part of a thread that was created before MSC3771 was implemented.\n // Or before the last unthreaded receipt for the logged in user\n const beforeFirstThreadedReceipt =\n (this.lastReply()?.getTs() ?? 0) < this.room.getOldestThreadedReceiptTs();\n const unthreadedReceiptTs = this.room.getLastUnthreadedReceiptFor(userId)?.ts ?? 0;\n const beforeLastUnthreadedReceipt = (this?.lastReply()?.getTs() ?? 0) < unthreadedReceiptTs;\n if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n return true;\n }\n }\n\n return this.room.hasUserReadEvent(userId, eventId);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.room.getLastUnthreadedReceiptFor(userId);\n }\n}\n\n/**\n * Decide whether an event deserves to have its potential edits fetched.\n *\n * @returns true if this event is encrypted and is a message that is part of a\n * thread - either inside it, or a root.\n */\nfunction isAnEncryptedThreadMessage(event: MatrixEvent): boolean {\n return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);\n}\n\nexport const FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\n \"related_by_senders\",\n \"io.element.relation_senders\",\n);\nexport const FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\n \"related_by_rel_types\",\n \"io.element.relation_types\",\n);\nexport const THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\n\nexport enum ThreadFilterType {\n \"My\",\n \"All\",\n}\n\nexport function threadFilterTypeToFilter(type: ThreadFilterType | null): \"all\" | \"participated\" {\n switch (type) {\n case ThreadFilterType.My:\n return \"participated\";\n default:\n return \"all\";\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4BA,oBAAoB,QAAQ,cAAc;AACtE,SAAS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A,KAAK,CAACoO,WAAW,CAAC,CAAC,KAAKpO,KAAK,CAACE,UAAU,CAACC,oBAAoB,CAACC,IAAI,CAAC,IAAIJ,KAAK,CAACqO,YAAY,CAAC;AACrG;AAEA,OAAO,IAAMzJ,yBAAyB,GAAG,IAAIvG,+BAA+B,CACxE,oBAAoB,EACpB,6BACJ,CAAC;AACD,OAAO,IAAMyG,2BAA2B,GAAG,IAAIzG,+BAA+B,CAC1E,sBAAsB,EACtB,2BACJ,CAAC;AACD,OAAO,IAAM8B,oBAAoB,GAAG,IAAI9B,+BAA+B,CAAC,UAAU,EAAE,mBAAmB,CAAC;AAExG,WAAYiQ,gBAAgB,0BAAhBA,gBAAgB;EAAhBA,gBAAgB,CAAhBA,gBAAgB;EAAhBA,gBAAgB,CAAhBA,gBAAgB;EAAA,OAAhBA,gBAAgB;AAAA;AAK5B,OAAO,SAASC,wBAAwBA,CAACL,IAA6B,EAA0B;EAC5F,QAAQA,IAAI;IACR,KAAKI,gBAAgB,CAACE,EAAE;MACpB,OAAO,cAAc;IACzB;MACI,OAAO,KAAK;EACpB;AACJ","ignoreList":[]}
@@ -37,27 +37,7 @@ export class User extends TypedEventEmitter {
37
37
  */
38
38
  constructor(userId) {
39
39
  super();
40
- this.userId = userId;
41
40
  _defineProperty(this, "modified", -1);
42
- /**
43
- * The 'displayname' of the user if known.
44
- * @privateRemarks
45
- * Should be read-only
46
- */
47
- _defineProperty(this, "displayName", void 0);
48
- _defineProperty(this, "rawDisplayName", void 0);
49
- /**
50
- * The 'avatar_url' of the user if known.
51
- * @privateRemarks
52
- * Should be read-only
53
- */
54
- _defineProperty(this, "avatarUrl", void 0);
55
- /**
56
- * The presence status message if known.
57
- * @privateRemarks
58
- * Should be read-only
59
- */
60
- _defineProperty(this, "presenceStatusMsg", void 0);
61
41
  /**
62
42
  * The presence enum if known.
63
43
  * @privateRemarks
@@ -91,6 +71,7 @@ export class User extends TypedEventEmitter {
91
71
  * Should be read-only
92
72
  */
93
73
  _defineProperty(this, "events", {});
74
+ this.userId = userId;
94
75
  this.displayName = userId;
95
76
  this.rawDisplayName = userId;
96
77
  this.updateModifiedTime();
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","names":["TypedEventEmitter","UserEvent","User","constructor","userId","_defineProperty","displayName","rawDisplayName","updateModifiedTime","createUser","client","user","reEmitter","reEmit","AvatarUrl","DisplayName","Presence","CurrentlyActive","LastPresenceTs","setPresenceEvent","event","getType","firstFire","events","presence","eventsToFire","getContent","push","avatar_url","avatarUrl","displayname","currently_active","undefined","currentlyActive","status_msg","presenceStatusMsg","lastActiveAgo","last_active_ago","lastPresenceTs","Date","now","eventToFire","emit","setDisplayName","name","oldName","setRawDisplayName","setAvatarUrl","url","oldUrl","modified","getLastModifiedTime","getLastActiveTs"],"sources":["../../src/models/user.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 { type Json, type JsonValue } from \"../@types/json.ts\";\nimport { type MatrixClient } from \"../matrix.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum UserEvent {\n DisplayName = \"User.displayName\",\n AvatarUrl = \"User.avatarUrl\",\n Presence = \"User.presence\",\n CurrentlyActive = \"User.currentlyActive\",\n LastPresenceTs = \"User.lastPresenceTs\",\n}\n\n/**\n * An object of extended profile attributes for a user as it arrives down the sync stream.\n */\nexport type SyncUserProfile = Record<string, Json | JsonValue>;\n\nexport type UserEventHandlerMap = {\n /**\n * Fires whenever any user's display name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.displayName changed.\n * @example\n * ```\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n * ```\n */\n [UserEvent.DisplayName]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's avatar URL changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.avatarUrl changed.\n * @example\n * ```\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n * ```\n */\n [UserEvent.AvatarUrl]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's presence changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.presence changed.\n * @example\n * ```\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n * ```\n */\n [UserEvent.Presence]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's currentlyActive changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.currentlyActive changed.\n * @example\n * ```\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n * ```\n */\n [UserEvent.CurrentlyActive]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.lastPresenceTs changed.\n * @example\n * ```\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n * ```\n */\n [UserEvent.LastPresenceTs]: (event: MatrixEvent | undefined, user: User) => void;\n};\n\nexport class User extends TypedEventEmitter<UserEvent, UserEventHandlerMap> {\n private modified = -1;\n\n /**\n * The 'displayname' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public displayName?: string;\n public rawDisplayName?: string;\n /**\n * The 'avatar_url' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public avatarUrl?: string;\n /**\n * The presence status message if known.\n * @privateRemarks\n * Should be read-only\n */\n public presenceStatusMsg?: string;\n /**\n * The presence enum if known.\n * @privateRemarks\n * Should be read-only\n */\n public presence = \"offline\";\n /**\n * Timestamp (ms since the epoch) for when we last received presence data for this user.\n * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n * @privateRemarks\n * Should be read-only\n */\n public lastActiveAgo = 0;\n /**\n * The time elapsed in ms since the user interacted proactively with the server,\n * or we saw a message from the user\n * @privateRemarks\n * Should be read-only\n */\n public lastPresenceTs = 0;\n /**\n * Whether we should consider lastActiveAgo to be an approximation\n * and that the user should be seen as active 'now'\n * @privateRemarks\n * Should be read-only\n */\n public currentlyActive = false;\n /**\n * The events describing this user.\n * @privateRemarks\n * Should be read-only\n */\n public events: {\n /** The m.presence event for this user. */\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @deprecated use `User.createUser`\n */\n public constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Construct a new User whose events will also emit on MatrixClient.\n * A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @param client - An instance of MatrixClient object\n * @returns User object with reEmitter setup on client\n */\n public static createUser(userId: string, client: MatrixClient): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n UserEvent.AvatarUrl,\n UserEvent.DisplayName,\n UserEvent.Presence,\n UserEvent.CurrentlyActive,\n UserEvent.LastPresenceTs,\n ]);\n return user;\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param event - The `m.presence` event.\n *\n * @remarks\n * Fires {@link UserEvent.Presence}\n * Fires {@link UserEvent.DisplayName}\n * Fires {@link UserEvent.AvatarUrl}\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire: UserEvent[] = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(UserEvent.Presence);\n }\n if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(UserEvent.AvatarUrl);\n }\n if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n eventsToFire.push(UserEvent.DisplayName);\n }\n if (\n event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive\n ) {\n eventsToFire.push(UserEvent.CurrentlyActive);\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(UserEvent.LastPresenceTs);\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (const eventToFire of eventsToFire) {\n this.emit(eventToFire, event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n this.displayName = name;\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setRawDisplayName(name?: string): void {\n this.rawDisplayName = name;\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param url - The new avatar URL.\n */\n public setAvatarUrl(url?: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated <i>before</i> firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @returns The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastPresenceTs - this.lastActiveAgo;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,iBAAiB,QAAQ,0BAA0B;AAE5D,WAAYC,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;;AAQrB;AACA;AACA;;AAmEA,OAAO,MAAMC,IAAI,SAASF,iBAAiB,CAAiC;EA4DxE;AACJ;AACA;AACA;AACA;EACWG,WAAWA,CAAiBC,MAAc,EAAE;IAC/C,KAAK,CAAC,CAAC;IAAC,KADuBA,MAAc,GAAdA,MAAc;IAAAC,eAAA,mBAhE9B,CAAC,CAAC;IAErB;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAAAA,eAAA;IAOA;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAMA;AACJ;AACA;AACA;AACA;IAJIA,eAAA;IAMA;AACJ;AACA;AACA;AACA;IAJIA,eAAA,mBAKkB,SAAS;IAC3B;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,wBAMuB,CAAC;IACxB;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,yBAMwB,CAAC;IACzB;AACJ;AACA;AACA;AACA;AACA;IALIA,eAAA,0BAMyB,KAAK;IAC9B;AACJ;AACA;AACA;AACA;IAJIA,eAAA,iBASI,CAAC,CAAC;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MACpC,IAAI,CAACiB,IAAI,CAACD,WAAW,EAAErB,KAAK,EAAE,IAAI,CAAC;IACvC;EACJ;;EAEA;AACJ;AACA;AACA;AACA;EACWuB,cAAcA,CAACC,IAAY,EAAQ;IACtC,IAAMC,OAAO,GAAG,IAAI,CAACvC,WAAW;IAChC,IAAI,CAACA,WAAW,GAAGsC,IAAI;IACvB,IAAIA,IAAI,KAAKC,OAAO,EAAE;MAClB,IAAI,CAACrC,kBAAkB,CAAC,CAAC;IAC7B;EACJ;;EAEA;AACJ;AACA;AACA;AACA;EACWsC,iBAAiBA,CAACF,IAAa,EAAQ;IAC1C,IAAI,CAACrC,cAAc,GAAGqC,IAAI;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;EACWG,YAAYA,CAACC,GAAY,EAAQ;IACpC,IAAMC,MAAM,GAAG,IAAI,CAACpB,SAAS;IAC7B,IAAI,CAACA,SAAS,GAAGmB,GAAG;IACpB,IAAIA,GAAG,KAAKC,MAAM,EAAE;MAChB,IAAI,CAACzC,kBAAkB,CAAC,CAAC;IAC7B;EACJ;;EAEA;AACJ;AACA;EACYA,kBAAkBA,CAAA,EAAS;IAC/B,IAAI,CAAC0C,QAAQ,GAAGX,IAAI,CAACC,GAAG,CAAC,CAAC;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWW,mBAAmBA,CAAA,EAAW;IACjC,OAAO,IAAI,CAACD,QAAQ;EACxB;;EAEA;AACJ;AACA;AACA;AACA;EACWE,eAAeA,CAAA,EAAW;IAC7B,OAAO,IAAI,CAACd,cAAc,GAAG,IAAI,CAACF,aAAa;EACnD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"user.js","names":["TypedEventEmitter","UserEvent","User","constructor","userId","_defineProperty","displayName","rawDisplayName","updateModifiedTime","createUser","client","user","reEmitter","reEmit","AvatarUrl","DisplayName","Presence","CurrentlyActive","LastPresenceTs","setPresenceEvent","event","getType","firstFire","events","presence","eventsToFire","getContent","push","avatar_url","avatarUrl","displayname","currently_active","undefined","currentlyActive","status_msg","presenceStatusMsg","lastActiveAgo","last_active_ago","lastPresenceTs","Date","now","eventToFire","emit","setDisplayName","name","oldName","setRawDisplayName","setAvatarUrl","url","oldUrl","modified","getLastModifiedTime","getLastActiveTs"],"sources":["../../src/models/user.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 { type Json, type JsonValue } from \"../@types/json.ts\";\nimport { type MatrixClient } from \"../matrix.ts\";\nimport { type MatrixEvent } from \"./event.ts\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.ts\";\n\nexport enum UserEvent {\n DisplayName = \"User.displayName\",\n AvatarUrl = \"User.avatarUrl\",\n Presence = \"User.presence\",\n CurrentlyActive = \"User.currentlyActive\",\n LastPresenceTs = \"User.lastPresenceTs\",\n}\n\n/**\n * An object of extended profile attributes for a user as it arrives down the sync stream.\n */\nexport type SyncUserProfile = Record<string, Json | JsonValue>;\n\nexport type UserEventHandlerMap = {\n /**\n * Fires whenever any user's display name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.displayName changed.\n * @example\n * ```\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n * ```\n */\n [UserEvent.DisplayName]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's avatar URL changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.avatarUrl changed.\n * @example\n * ```\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n * ```\n */\n [UserEvent.AvatarUrl]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's presence changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.presence changed.\n * @example\n * ```\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n * ```\n */\n [UserEvent.Presence]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's currentlyActive changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.currentlyActive changed.\n * @example\n * ```\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n * ```\n */\n [UserEvent.CurrentlyActive]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.lastPresenceTs changed.\n * @example\n * ```\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n * ```\n */\n [UserEvent.LastPresenceTs]: (event: MatrixEvent | undefined, user: User) => void;\n};\n\nexport class User extends TypedEventEmitter<UserEvent, UserEventHandlerMap> {\n private modified = -1;\n\n /**\n * The 'displayname' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public displayName?: string;\n public rawDisplayName?: string;\n /**\n * The 'avatar_url' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public avatarUrl?: string;\n /**\n * The presence status message if known.\n * @privateRemarks\n * Should be read-only\n */\n public presenceStatusMsg?: string;\n /**\n * The presence enum if known.\n * @privateRemarks\n * Should be read-only\n */\n public presence = \"offline\";\n /**\n * Timestamp (ms since the epoch) for when we last received presence data for this user.\n * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n * @privateRemarks\n * Should be read-only\n */\n public lastActiveAgo = 0;\n /**\n * The time elapsed in ms since the user interacted proactively with the server,\n * or we saw a message from the user\n * @privateRemarks\n * Should be read-only\n */\n public lastPresenceTs = 0;\n /**\n * Whether we should consider lastActiveAgo to be an approximation\n * and that the user should be seen as active 'now'\n * @privateRemarks\n * Should be read-only\n */\n public currentlyActive = false;\n /**\n * The events describing this user.\n * @privateRemarks\n * Should be read-only\n */\n public events: {\n /** The m.presence event for this user. */\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @deprecated use `User.createUser`\n */\n public constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Construct a new User whose events will also emit on MatrixClient.\n * A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n * @param client - An instance of MatrixClient object\n * @returns User object with reEmitter setup on client\n */\n public static createUser(userId: string, client: MatrixClient): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n UserEvent.AvatarUrl,\n UserEvent.DisplayName,\n UserEvent.Presence,\n UserEvent.CurrentlyActive,\n UserEvent.LastPresenceTs,\n ]);\n return user;\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param event - The `m.presence` event.\n *\n * @remarks\n * Fires {@link UserEvent.Presence}\n * Fires {@link UserEvent.DisplayName}\n * Fires {@link UserEvent.AvatarUrl}\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire: UserEvent[] = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(UserEvent.Presence);\n }\n if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(UserEvent.AvatarUrl);\n }\n if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n eventsToFire.push(UserEvent.DisplayName);\n }\n if (\n event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive\n ) {\n eventsToFire.push(UserEvent.CurrentlyActive);\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(UserEvent.LastPresenceTs);\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (const eventToFire of eventsToFire) {\n this.emit(eventToFire, event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n this.displayName = name;\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setRawDisplayName(name?: string): void {\n this.rawDisplayName = name;\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param url - The new avatar URL.\n */\n public setAvatarUrl(url?: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated <i>before</i> firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @returns The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastP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