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

Sign up to get free protection for your applications and to get access to all the features.
package/lib/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["SyncApi","SyncState","EventStatus","MatrixEvent","MatrixEventEvent","StubStore","createNewMatrixCall","supportsMatrixCall","Filter","CallEventHandler","GroupCallEventHandler","utils","noUnsafeEventProps","replaceParam","safeSet","sleep","Direction","EventTimeline","PushProcessor","AutoDiscovery","olmlib","decodeBase64","encodeBase64","encodeUnpaddedBase64Url","TypedReEmitter","logger","SERVICE_TYPES","ClientPrefix","IdentityPrefix","MatrixError","MatrixHttpApi","MediaPrefix","Method","retryNetworkOperation","Crypto","CryptoEvent","LegacyCryptoEvent","fixBackupKey","User","UserEvent","getHttpUriForMxc","SearchResult","DEHYDRATION_ALGORITHM","CrossSigningKey","ContentHelpers","NotificationCountType","RoomMemberEvent","EventType","LOCAL_NOTIFICATION_SETTINGS_PREFIX","MSC3912_RELATION_BASED_REDACTIONS_PROP","MsgType","PUSHER_ENABLED","RelationType","RoomCreateTypeField","RoomType","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3088_PURPOSE","UNSTABLE_MSC3089_TREE_SUBTYPE","GuestAccess","HistoryVisibility","Preset","eventMapperFor","randomString","BackupManager","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","MSC3089TreeSpace","SearchOrderBy","PushRuleActionName","PushRuleKind","GroupCall","MediaHandler","TypedEventEmitter","MAIN_ROOM_TIMELINE","ReceiptType","SlidingSyncSdk","determineFeatureSupport","FeatureSupport","Thread","THREAD_RELATION_TYPE","ThreadFilterType","threadFilterTypeToFilter","M_BEACON_INFO","NamespacedValue","UnstableValue","ToDeviceMessageQueue","IgnoredInvites","buildFeatureSupportMap","Feature","ServerSupport","RUST_SDK_STORE_PREFIX","decodeRecoveryKey","ServerSideSecretStorageImpl","MatrixRTCSessionManager","getRelationsThreadFilter","KnownMembership","ServerCapabilities","sha256","keyFromAuthData","SCROLLBACK_DELAY_MS","TURN_CHECK_INTERVAL","UNSTABLE_MSC3852_LAST_SEEN_UA","PendingEventOrdering","GET_LOGIN_TOKEN_CAPABILITY","UNSTABLE_MSC2666_SHARED_ROOMS","UNSTABLE_MSC2666_MUTUAL_ROOMS","UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS","UNSTABLE_MSC4140_DELAYED_EVENTS","UNSTABLE_MSC4133_EXTENDED_PROFILES","CrossSigningKeyType","EVENT_ID_PREFIX","ClientEvent","SSO_ACTION_PARAM","MatrixClient","constructor","opts","_opts$logger","_opts$usingExternalCr","_this","_opts$cryptoCallbacks","this","_defineProperty","Map","Set","isInitialSyncComplete","callEventHandler","start","groupCallEventHandler","off","Sync","startCallEventHandler","matrixRTC","startMatrixRTC","_this$getRooms","unreadRooms","getRooms","filter","room","getUnreadNotificationCount","Total","currentUserId","getSafeUserId","fixupNotifications","fixupRoomNotifications","baseUrl","ensureNoTrailingSlash","idBaseUrl","identityServer","usingExternalCrypto","store","deviceId","sessionId","userId","credentials","http","fetchFn","accessToken","refreshToken","tokenRefreshFunction","prefix","V3","onlyData","extraParams","queryParams","localTimeoutMs","useAuthorizationHeader","deviceToImport","warn","exportedOlmDeviceToImport","olmDevice","pickleKey","useLivekitForGroupCalls","Boolean","scheduler","setProcessFunction","_ref","_asyncToGenerator","eventToSend","getRoom","getRoomId","status","SENDING","updatePendingEventStatus","res","sendEventHttpRequest","updatePendingEvent","SENT","event_id","_x","apply","arguments","canSupportVoip","on","serverCapabilitiesService","timelineSupport","cryptoStore","verificationMethods","cryptoCallbacks","forceTURN","iceCandidatePoolSize","undefined","supportsCallTransfer","fallbackICEServerAllowed","isVoipWithNoMediaAllowed","useE2eForGroupCall","livekitServiceURL","roomNameGenerator","toDeviceMessageQueue","Decrypted","event","fixNotificationCountOnDecryption","ignoredInvites","_secretStorage","setMaxListeners","newStore","_store","setUserCreator","createUser","startClient","_this2","clientRunning","getUserId","storeUser","checkTurnServersIntervalID","setInterval","checkTurnServers","syncApi","error","stop","getVersions","threads","list","fwdPagination","doesServerSupportThread","setServerSideSupport","setServerSideListSupport","setServerSideFwdPaginationSupport","e","clientOpts","slidingSync","buildSyncApiOptions","sync","catch","info","clientWellKnownPollPeriod","clientWellKnownIntervalID","fetchClientWellKnown","crypto","cryptoBackend","canResetEntireTimeline","roomId","canResetTimelineCallback","stopClient","_this$cryptoBackend","_this$syncApi","_this$peekSync","_this$callEventHandle","_this$groupCallEventH","debug","peekSync","stopPeeking","globalThis","clearInterval","rehydrateDevice","_this3","Error","getDehydrationKey","getDeviceResult","getDehydratedDevice","device_data","device_id","account","Olm","Account","deviceData","algorithm","key","k","unpickle","Uint8Array","rehydrateResult","authedRequest","Post","success","pickledAccount","pickle","sessions","free","_this4","Get","setDehydrationKey","keyInfo","deviceDisplayName","_this5","dehydrationManager","setKeyAndQueueDehydration","createDehydratedDevice","_this6","setKey","dehydrateDevice","exportDevice","_this7","export","clearStores","_this8","promises","push","deleteAllData","deleteRustSdkStore","_ref2","indexedDB","_unused","_loop","dbname","prom","Promise","resolve","reject","concat","req","deleteDatabase","onsuccess","_","onerror","onblocked","all","then","getDomain","replace","getUserIdLocalpart","split","substring","getDeviceId","getSessionId","supportsVoip","getMediaHandler","mediaHandler","setForceTURN","force","setSupportsCallTransfer","support","getUseE2eForGroupCall","createCall","createGroupCall","type","isPtt","intent","dataChannelsEnabled","dataChannelOptions","_this9","getGroupCallForRoom","create","getLivekitServiceURL","setLivekitServiceURL","newURL","waitUntilRoomReadyForGroupCalls","groupCalls","get","getSyncState","_this$syncApi$getSync","_this$syncApi2","getSyncStateData","state","Prepared","Syncing","isGuest","isGuestAccount","setGuest","guest","getScheduler","retryImmediately","_this$syncApi$retryIm","_this$syncApi3","sendQueue","getNotifTimelineSet","notifTimelineSet","setNotifTimelineSet","set","getCapabilities","_this10","caps","getCachedCapabilities","fetchCapabilities","initCrypto","_this11","startup","reEmitter","reEmit","KeyBackupFailed","KeyBackupSessionsRemaining","RoomKeyRequest","RoomKeyRequestCancellation","Warning","DevicesUpdated","WillUpdateDevices","DeviceVerificationChanged","UserTrustStatusChanged","KeysChanged","init","exportedOlmDevice","olmVersion","getOlmVersion","registerEventHandlers","uploadDeviceKeys","initRustCrypto","_arguments","_this12","_this12$pickleKey","args","length","RustCrypto","rustCrypto","secretStorage","storePrefix","useIndexedDB","storeKey","storageKey","storePassphrase","storagePassword","legacyCryptoStore","legacyPickleKey","legacyMigrationProgressListener","progress","total","emit","LegacyCryptoStoreMigrationProgress","setSupportedVerificationMethods","Membership","onRoomMembership","bind","Event","onLiveEventFromSync","VerificationRequestReceived","KeyBackupStatus","KeyBackupDecryptionKeyCached","getCrypto","isCryptoEnabled","getDeviceEd25519Key","_this$crypto$getDevic","_this$crypto","getDeviceCurve25519Key","_this$crypto$getDevic2","_this$crypto2","uploadKeys","_this13","downloadKeys","userIds","forceDownload","getStoredDevicesForUser","getStoredDevice","setDeviceVerified","verified","setDeviceVerification","checkKeyBackup","setDeviceBlocked","blocked","setDeviceKnown","known","_this14","requestVerificationDM","findVerificationRequestDMInProgress","getVerificationRequestsToDeviceInProgress","requestVerification","devices","beginKeyVerification","method","checkSecretStorageKey","checkKey","setGlobalBlacklistUnverifiedDevices","value","globalBlacklistUnverifiedDevices","getGlobalBlacklistUnverifiedDevices","setGlobalErrorOnUnknownDevices","globalErrorOnUnknownDevices","getGlobalErrorOnUnknownDevices","getCrossSigningId","Master","getStoredCrossSigningForUser","checkUserTrust","checkDeviceTrust","checkIfOwnDeviceCrossSigned","checkOwnCrossSigningTrust","checkCrossSigningPrivateKey","privateKey","expectedPublicKey","legacyDeviceVerification","prepareToEncrypt","userHasCrossSigningKeys","isCrossSigningReady","bootstrapCrossSigning","getCryptoTrustCrossSignedDevices","getTrustCrossSignedDevices","setCryptoTrustCrossSignedDevices","val","setTrustCrossSignedDevices","countSessionsNeedingBackup","getEventEncryptionInfo","createRecoveryKeyFromPassphrase","password","isSecretStorageReady","bootstrapSecretStorage","addSecretStorageKey","keyName","addKey","hasSecretStorageKey","keyId","hasKey","storeSecret","name","secret","keys","getSecret","isSecretStored","isStored","requestSecret","getDefaultSecretStorageKeyId","getDefaultKeyId","setDefaultSecretStorageKeyId","setDefaultKeyId","checkSecretStoragePrivateKey","getEventSenderDeviceInfo","_this15","isEventSenderVerified","_this16","device","isVerified","getOutgoingRoomKeyRequest","wireContent","getWireContent","requestBody","session_id","sender_key","room_id","cancelAndResendEventRoomKeyRequest","cancelAndResendKeyRequest","setRoomEncryption","config","isRoomEncrypted","_this$crypto$isRoomEn","_this$crypto3","hasEncryptionStateEvent","encryptAndSendToDevices","userDeviceInfoArr","payload","forceDiscardSession","exportRoomKeys","importRoomKeys","backupManager","getKeyBackupVersion","_this17","errcode","checkBackupVersion","isKeyBackupTrusted","getKeyBackupEnabled","enableKeyBackup","disableKeyBackup","prepareKeyBackupVersion","_arguments2","_this18","secureSecretStorage","auth_data","recovery_key","isKeyBackupKeyStored","createKeyBackupVersion","_this19","data","signObject","getCrossSigningKey","crossSigningInfo","getId","deleteKeyBackupVersion","version","_this20","makeKeyBackupPath","path","encodeUri","$roomId","$sessionId","queryData","sendKeyBackup","_this21","Put","scheduleAllGroupSessionsForBackup","_this22","flagAllGroupSessionsForBackup","isValidRecoveryKey","recoveryKey","_unused2","keyBackupKeyFromPassword","backupInfo","keyBackupKeyFromRecoveryKey","restoreKeyBackupWithPassword","targetRoomId","targetSessionId","_this23","privKey","restoreKeyBackup","restoreKeyBackupWithSecretStorage","_this24","storedKey","fixedKey","getKey","restoreKeyBackupWithRecoveryKey","restoreKeyBackupWithCache","_this25","getSessionBackupPrivateKey","_this26","cacheCompleteCallback","progressCallback","backupVersion","totalKeyCount","totalFailures","totalImported","backupDecryptor","getBackupDecryptor","untrusted","sourceTrusted","storeSessionBackupPrivateKey","stage","rooms","getTotalKeyCount","handleDecryptionOfAFullBackup","_ref3","chunk","importBackedUpRoomKeys","successes","failures","_x2","Object","decryptSessions","checkKeyBackupAndEnable","imported","roomData","values","chunkSize","block","groupChunkCount","chunkGroupByRoom","handleChunkCallback","_ref4","roomChunks","currentChunk","decryptedSessions","_x3","entries","session","sessionsForRoom","deleteKeysFromBackup","_this27","Delete","getMediaConfig","getVisibleRooms","msc3946ProcessDynamicPredecessor","allRooms","replacedRooms","r","_r$findPredecessor","predecessor","findPredecessor","add","tombstone","currentState","getStateEvents","RoomTombstone","has","getUser","getUsers","setAccountData","eventType","content","$userId","$type","getAccountData","getAccountDataFromServer","_this28","getContent","_data","deleteAccountData","_this29","msc3391DeleteAccountDataServerSupport","canSupport","AccountDataDeletion","Unsupported","options","Unstable","getIgnoredUsers","setIgnoredUsers","ignored_users","forEach","u","isUserIgnored","includes","joinRoom","roomIdOrAlias","_arguments3","_this30","syncRoom","hasMembershipState","Join","signPromise","inviteSignUrl","url","URL","searchParams","requestOtherUrl","viaServers","server_name","via","signedInviteObj","third_party_signed","$roomid","resolvedRoom","createRoom","knockRoom","Knock","$roomIdOrAlias","body","reason","resendEvent","encryptAndSendEvent","cancelPendingEvent","QUEUED","NOT_SENT","ENCRYPTING","eventsBeingEncrypted","delete","removeEventFromQueue","CANCELLED","setRoomName","sendStateEvent","RoomName","setRoomTopic","topic","htmlTopic","makeTopicContent","RoomTopic","getRoomTags","setRoomTag","tagName","metadata","$tag","deleteRoomTag","setRoomAccountData","setPowerLevel","powerLevel","_this31","_content","_this31$getRoom","RoomPowerLevels","getStateEvent","deepCopy","users","Array","isArray","user","unstable_createLiveBeacon","beaconInfoContent","_this32","unstable_setLiveBeacon","_this33","sendEvent","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","threadId","txnId","startsWith","addThreadRelationIfNeeded","sendCompleteEvent","_content$mRelates_to","rel_type","_content$mRelates_to2","_this$getRoom","isReply","_objectSpread","is_falling_back","thread","getThread","_thread$lastReply$get","_thread$lastReply","lastReply","ev","isRelation","eventObject","delayOptsOrTxnId","delayOpts","makeTxnId","localEvent","assign","user_id","sender","origin_server_ts","Date","getTime","setThread","Replaced","VisibilityChange","BeforeRedaction","targetId","getAssociatedId","target","getPendingEvents","find","once","LocalEventIdReplaced","updateAssociatedId","getType","setTxnId","setStatus","addPendingEvent","_this34","cancelled","encryptEventIfNeeded","promise","queueEvent","getQueueForEvent","err","_this35","shouldEncryptEventForRoom","encryptEvent","_this36","_this36$cryptoBackend","isEncrypted","Reaction","isRedaction","isEncryptionEnabledInRoom","getEncryptedIfNeededEventType","_this$getRoom2","RoomMessageEncrypted","newStatus","getTxnId","pathParams","$eventType","getWireType","$stateKey","getStateKey","$txnId","isState","pathTemplate","redacts","$redactsEventId","getUnstableDelayQueryOpts","redactEvent","eventId","_eventId","_opts","_opts2","with_rel_types","RelationBasedRedactions","withRelTypesPropName","Stable","stable","unstable","RoomRedaction","sendMessage","RoomMessage","sendContent","sendTextMessage","_threadId","makeTextMessage","sendNotice","_threadId2","makeNotice","sendEmoteMessage","_threadId3","makeEmoteMessage","sendImageMessage","_threadId4","text","msgtype","Image","sendStickerMessage","_threadId5","Sticker","sendHtmlMessage","htmlBody","_threadId6","makeHtmlMessage","sendHtmlNotice","_threadId7","makeHtmlNotice","sendHtmlEmote","_threadId8","makeHtmlEmote","_unstable_sendDelayedEvent","_this37","doesServerSupportUnstableFeature","_unstable_sendDelayedStateEvent","_arguments4","_this38","stateKey","_unstable_getDelayedEvents","fromToken","_this39","queryDict","from","_unstable_updateDelayedEvent","delayId","action","_this40","$delayId","sendReceipt","receiptType","_arguments5","_this41","unthreaded","$receiptType","$eventId","shouldAddThreadId","supportsThreads","fullBody","thread_id","threadIdForReceipt","addLocalEchoReceipt","sendReadReceipt","_arguments6","_this42","Read","hasPendingEvent","setRoomReadMarkers","rmEventId","rrEvent","rpEvent","_this43","rrEventId","rpEventId","ReadPrivate","setRoomReadMarkersHttpRequest","getUrlPreview","ts","Math","floor","parsed","hash","toString","urlPreviewCache","resp","priority","sendTyping","isTyping","timeoutMs","typing","timeout","getRoomUpgradeHistory","verifyLinks","currentRoom","before","findPredecessorRooms","after","findSuccessorRooms","_room$findPredecessor","ret","seenRoomIDs","predecessorRoomId","_room$findPredecessor2","predecessorRoom","splice","tombstoneEvent","successorRoom","_successorRoom$findPr","roomIds","map","ref","size","slice","invite","membershipChange","Invite","inviteByEmail","email","inviteByThreePid","medium","address","_this44","_this44$identityServe","identityServerUrl","getIdentityServerUrl","params","id_server","getAccessToken","identityAccessToken","leave","Leave","leaveRoomChain","includeFuture","upgradeHistory","eligibleToLeave","populationResults","doLeave","ban","Ban","forget","_arguments7","_this45","deleteRoom","$room_id","response","removeRoom","DeleteRoom","unban","kick","membership","$membership","getPushActionsForEvent","forceRecalculate","getPushActions","actions","rule","pushProcessor","actionsAndRuleForEvent","setPushDetails","getPushDetailsForEvent","getPushDetails","setProfileInfo","$info","setDisplayName","_this46","displayname","displayName","DisplayName","events","presence","setAvatarUrl","_this47","avatar_url","avatarUrl","AvatarUrl","mxcUrlToHttp","mxcUrl","width","height","resizeMethod","allowDirectLinks","allowRedirects","useAuthentication","setSyncPresence","_this48","_this48$syncApi","setPresence","_this49","validStates","indexOf","getPresence","scrollback","limit","timeToWaitMs","ongoingScrollbacks","errorTs","timeWaitedMs","now","max","oldState","paginationToken","numAdded","createMessagesRequest","Backward","_res$end","_res$end2","matrixEvents","getEventMapper","stateEvents","setUnknownStateEvents","timelineEvents","threadedEvents","unknownRelations","partitionThreadedEvents","processAggregatedTimelineEvents","addEventsToTimeline","getLiveTimeline","processThreadEvents","relations","aggregateChildEvent","end","storeEvents","getEventTimeline","timelineSet","_this50","_this50$clientOpts","_ref5","_timelineSet$getTimel","_timelineSet$room$fin","getTimelineForEvent","getThreadTimeline","lazyLoadMembers","JSON","stringify","LAZY_LOADING_MESSAGES_FILTER","mapper","events_after","reverse","events_before","timeline","getState","BACKWARDS","addTimeline","initialiseState","FORWARDS","findThreadForEvent","liveTimeline","_this51","_this51$clientOpts","canContain","recurse","RelationsRecursion","hasServerSideSupport","hasServerSideFwdPaginationSupport","_resOlder$next_batch","_resNewer$next_batch","_timelineSet$getTimel2","resOlder","fetchRelations","id","dir","resNewer","Forward","_timelineSet$thread","processEvent","next_batch","originalEvent","fetchRoomEvent","setPaginationToken","_resOlder$next_batch2","eventsNewer","nextBatch","_resNewer$next_batch2","_timelineSet$thread2","getLatestTimeline","_this52","threadListType","_res$chunk","createThreadListMessagesRequest","getFilter","_res$chunk2","_this52$clientOpts","_res2$chunk","messagesPath","_this$clientOpts","timelineFilter","_timelineFilter$getRo","getRoomTimelineFilterComponent","toJSON","_this$clientOpts2","All","include","_timelineFilter$getRo2","hasServerSideListSupport","V1","_res$chunk3","prev_batch","paginateEventTimeline","eventTimeline","_this53","isNotifTimeline","getTimelineSet","backwards","token","getPaginationToken","pendingRequest","paginationRequests","_opts$limit","only","_ref6","next_token","notifications","i","notification","_x4","finally","roomState","processThreadRoots","_eventTimeline$getRoo","_eventTimeline$getRoo2","_ref7","getSender","getEventReadUpTo","newToken","_thread$rootEvent","_eventTimeline$getRoo3","rootEvent","_x5","it","getServerAggregatedRelation","atEnd","resetNotifTimelineSet","resetLiveTimeline","peekInRoom","_this$peekSync2","peek","setGuestAccess","writePromise","RoomGuestAccess","guest_access","allowJoin","CanJoin","Forbidden","readPromise","allowRead","RoomHistoryVisibility","history_visibility","WorldReadable","requestRegisterEmailToken","clientSecret","sendAttempt","nextLink","requestTokenFromEndpoint","client_secret","send_attempt","next_link","requestRegisterMsisdnToken","phoneCountry","phoneNumber","country","phone_number","requestAdd3pidEmailToken","requestAdd3pidMsisdnToken","requestPasswordEmailToken","requestPasswordMsisdnToken","endpoint","_this54","postParams","request","getRoomPushRule","scope","pushRules","_this$pushRules$scope","rule_id","setRoomMutePushRule","mute","hasDontNotifyRule","roomPushRule","DontNotify","deletePushRule","RoomSpecific","addPushRule","deferred","defer","getPushRules","result","err2","searchMessageText","roomEvents","search_term","query","search","search_categories","room_events","searchRoomEvents","term","order_by","Recent","event_context","before_limit","after_limit","include_profile","searchResults","_query","results","highlights","processRoomEventsSearch","backPaginateRoomEventsSearch","searchOpts","abortSignal","_roomEvents$results$l","_roomEvents$results","count","hl","resultsLength","sr","fromJson","context","getEvent","getTimeline","getMember","syncLeftRooms","syncedLeftRooms","syncLeftRoomsPromise","createFilter","filter_id","storeFilter","filterId","allowCached","$filterId","getOrCreateFilter","filterName","_this55","getFilterIdByName","existingId","existingFilter","oldDef","getDefinition","newDef","deepCompare","setFilterIdByName","createdFilter","getOpenIdToken","turnServer","getTurnServers","turnServers","getTurnServersExpiry","turnServersExpiry","pollingTurnServers","_this56","credentialsGood","remainingTime","uris","ttl","servers","urls","username","credential","TurnServers","httpStatus","TurnServersError","setFallbackICEServerAllowed","allow","isFallbackICEServerAllowed","isSynapseAdministrator","admin","whoisSynapseUser","deactivateSynapseUser","_this57","_this57$getDomain","clientWellKnownPromise","getRawClientConfig","clientWellKnown","ClientWellKnown","getClientWellKnown","waitForClientWellKnown","storeClientOptions","primTypes","serializableOpts","_ref8","reduce","obj","_ref9","_unstable_getSharedRooms","_this58","sharedRoomsSupport","mutualRoomsSupport","queryMutualRoomsSupport","tokenQuery","joined","next_batch_token","_this59","serverVersionsPromise","serverVersions","isVersionSupported","_this60","versions","feature","_this61","unstableFeatures","doesServerForceEncryptionForPreset","presetName","_this62","versionsPresetName","_this63","threadUnstable","threadStable","listUnstable","listStable","fwdPaginationUnstable","fwdPaginationStable","_unused3","None","hasLazyLoadMembersEnabled","_this$clientOpts3","setCanResetTimelineCallback","cb","getCanResetTimelineCallback","relationType","_arguments8","_this64","_result$next_batch","_result$prev_batch","fetchedEventType","eventResult","allEvents","decryptEventIfNeeded","Replace","prevBatch","getCrossSigningCacheCallbacks","_this$crypto4","getCacheCallbacks","generateClientSecret","shouldAttemptDecryption","attemptDecryption","isBeingDecrypted","getDecryptionPromise","termsUrlForService","serviceType","IS","getUrl","V2","IM","getHomeserverUrl","_this$idBaseUrl","_this$idBaseUrl2","stripProto","setIdentityServerUrl","setIdBaseUrl","getRefreshToken","_this$http$opts$refre","setAccessToken","isLoggedIn","txnCtr","isUsernameAvailable","available","register","auth","bindThreepids","guestAccessToken","inhibitLogin","refresh_token","guest_access_token","inhibit_login","registerRequest","registerGuest","kind","performRefreshRequestWithPrefix","inhibitLogoutEmit","loginFlows","login","loginType","access_token","loginWithPassword","getCasLoginUrl","redirectUrl","getSsoLoginUrl","idpId","href","loginWithToken","logout","_arguments9","_this65","_this65$crypto","backupPendingKeys","abort","deactivateAccount","erase","requestLoginToken","_this66","getFallbackAuthUrl","authSessionId","$loginType","_this67","_this67$identityServe","invitesNeedingToken","invite_3pid","id_access_token","Experimental","queryString","encodeParams","templatedUrl","$relationType","members","includeMembership","excludeMembership","atEventId","not_membership","at","upgradeRoom","newVersion","new_version","roomInitialSync","_limit$toString","_this68","FullyRead","getJoinedRooms","getJoinedRoomMembers","publicRooms","_ref10","server","since","_objectWithoutProperties","_excluded","createAlias","alias","$alias","deleteAlias","getLocalAliases","getRoomIdForAlias","getRoomDirectoryVisibility","setRoomDirectoryVisibility","visibility","searchUserDirectory","_ref11","uploadContent","file","cancelUpload","upload","getCurrentUploads","getProfileInfo","doesServerSupportExtendedProfiles","_this69","getExtendedProfileRequestPrefix","_this70","getExtendedProfile","_this71","getExtendedProfileProperty","_this72","profile","$key","setExtendedProfileProperty","_this73","deleteExtendedProfileProperty","_this74","patchExtendedProfile","_this75","Patch","setExtendedProfile","_this76","getThreePids","addThreePidOnly","_this77","bindThreePid","_this78","unbindThreePid","_this79","deleteThreePid","setPassword","authDict","newPassword","logoutDevices","new_password","logout_devices","getDevices","getDevice","$device_id","setDeviceDetails","deleteDevice","deleteMultipleDevices","getPushers","_this80","pushers","pusher","hasOwnProperty","setPusher","removePusher","pushKey","appId","pushkey","app_id","setLocalNotificationSettings","notificationSettings","rules","setPushRules","rewriteDefaultRules","updateCachedPushRuleKeys","ruleId","$kind","$ruleId","setPushRuleEnabled","enabled","setPushRuleActions","_ref12","uploadKeysRequest","uploadKeySignatures","downloadKeysForUsers","device_keys","claimOneTimeKeys","keyAlgorithm","queries","one_time_keys","getKeyChanges","oldToken","qps","to","uploadDeviceSigningKeys","registerWithIdentityServer","hsOpenIdToken","uri","requestEmailToken","idServerRequest","requestMsisdnToken","submitMsisdnToken","sid","msisdnToken","submitMsisdnTokenOtherUrl","getIdentityHashDetails","identityHashedLookup","addressPairs","_this81","hashes","localMapping","_ref13","p","addr","toLowerCase","med","hashBuffer","hashed","_x6","unhashed","foundAddresses","mxid","plainAddress","lookupThreePid","_this82","mapping","bulkLookupThreePids","_this83","v1results","_loop2","originalQuery","threepids","getIdentityAccount","sendToDevice","contentMap","messages","recursiveMapToObject","targets","deviceMessages","queueToDevice","batch","queueBatch","getThirdpartyProtocols","getThirdpartyLocation","protocol","$protocol","getThirdpartyUser","getTerms","agreeToTerms","termsUrls","headers","Authorization","user_accepts","reportEvent","score","getRoomHierarchy","maxDepth","suggestedOnly","suggested_only","String","max_depth","unstableCreateFileTree","_this84","preset","PrivateChat","power_level_content_override","creation_content","Space","initial_state","state_key","RoomEncryption","MEGOLM_ALGORITHM","unstableGetFileTreeSpace","_purposeEvent$getCont","_createEvent$getConte","getMyMembership","createEvent","RoomCreate","purposeEvent","proxyBaseUrl","pos","clientTimeout","_this$clientOpts4","threadSupport","supportsIntentionalMentions","IntentionalMentions","getRoomSummary","_this85","paramOpts","toStartOfTimeline","processThreadedEvents","processBeaconEvents","processPollEvents","whoami","_this86","timestampToEvent","timestamp","_this87","getAuthIssuer","_this88","fromEntries","_ref14","v","cli","_actions$tweaks","ourUserId","findEventById","isThreadEvent","threadRootId","isThreadRoot","hasReadEvent","hasUserReadEvent","newHighlight","tweaks","highlight","newCount","getUnreadCountForEventContext","Highlight","setThreadUnreadNotificationCount","setUnreadNotificationCount","newNotify","notify","inMainTimelineForReceipt","isRelatedToRoot","relationEventId"],"sources":["../src/client.ts"],"sourcesContent":["/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport type { IDeviceKeys, IMegolmSessionData, IOneTimeKey } from \"./@types/crypto.ts\";\nimport { ISyncStateData, SetPresence, SyncApi, SyncApiOptions, SyncState } from \"./sync.ts\";\nimport {\n EventStatus,\n IContent,\n IDecryptOptions,\n IEvent,\n MatrixEvent,\n MatrixEventEvent,\n MatrixEventHandlerMap,\n PushDetails,\n} from \"./models/event.ts\";\nimport { StubStore } from \"./store/stub.ts\";\nimport { CallEvent, CallEventHandlerMap, createNewMatrixCall, MatrixCall, supportsMatrixCall } from \"./webrtc/call.ts\";\nimport { Filter, IFilterDefinition, IRoomEventFilter } from \"./filter.ts\";\nimport { CallEventHandler, CallEventHandlerEvent, CallEventHandlerEventHandlerMap } from \"./webrtc/callEventHandler.ts\";\nimport {\n GroupCallEventHandler,\n GroupCallEventHandlerEvent,\n GroupCallEventHandlerEventHandlerMap,\n} from \"./webrtc/groupCallEventHandler.ts\";\nimport * as utils from \"./utils.ts\";\nimport { noUnsafeEventProps, QueryDict, replaceParam, safeSet, sleep } from \"./utils.ts\";\nimport { Direction, EventTimeline } from \"./models/event-timeline.ts\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor.ts\";\nimport { AutoDiscovery, AutoDiscoveryAction } from \"./autodiscovery.ts\";\nimport * as olmlib from \"./crypto/olmlib.ts\";\nimport { decodeBase64, encodeBase64, encodeUnpaddedBase64Url } from \"./base64.ts\";\nimport { IExportedDevice as IExportedOlmDevice } from \"./crypto/OlmDevice.ts\";\nimport { IOlmDevice } from \"./crypto/algorithms/megolm.ts\";\nimport { TypedReEmitter } from \"./ReEmitter.ts\";\nimport { IRoomEncryption } from \"./crypto/RoomList.ts\";\nimport { logger, Logger } from \"./logger.ts\";\nimport { SERVICE_TYPES } from \"./service-types.ts\";\nimport {\n Body,\n ClientPrefix,\n FileType,\n HttpApiEvent,\n HttpApiEventHandlerMap,\n HTTPError,\n IdentityPrefix,\n IHttpOpts,\n IRequestOpts,\n MatrixError,\n MatrixHttpApi,\n MediaPrefix,\n Method,\n retryNetworkOperation,\n TokenRefreshFunction,\n Upload,\n UploadOpts,\n UploadResponse,\n} from \"./http-api/index.ts\";\nimport {\n Crypto,\n CryptoEvent as LegacyCryptoEvent,\n CryptoEventHandlerMap as LegacyCryptoEventHandlerMap,\n fixBackupKey,\n ICheckOwnCrossSigningTrustOpts,\n IRoomKeyRequestBody,\n} from \"./crypto/index.ts\";\nimport { DeviceInfo } from \"./crypto/deviceinfo.ts\";\nimport { User, UserEvent, UserEventHandlerMap } from \"./models/user.ts\";\nimport { getHttpUriForMxc } from \"./content-repo.ts\";\nimport { SearchResult } from \"./models/search-result.ts\";\nimport { DEHYDRATION_ALGORITHM, IDehydratedDevice, IDehydratedDeviceKeyInfo } from \"./crypto/dehydration.ts\";\nimport {\n IKeyBackupInfo,\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupRoomSessions,\n IKeyBackupSession,\n} from \"./crypto/keybackup.ts\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./models/beacon.ts\";\nimport { AuthDict } from \"./interactive-auth.ts\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent } from \"./sync-accumulator.ts\";\nimport { CrossSigningKey, ICreateSecretStorageOpts, IEncryptedEventInfo, IRecoveryKey } from \"./crypto/api.ts\";\nimport { EventTimelineSet } from \"./models/event-timeline-set.ts\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest.ts\";\nimport { VerificationBase as Verification } from \"./crypto/verification/Base.ts\";\nimport * as ContentHelpers from \"./content-helpers.ts\";\nimport { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from \"./crypto/CrossSigning.ts\";\nimport { NotificationCountType, Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from \"./models/room.ts\";\nimport { RoomMemberEvent, RoomMemberEventHandlerMap } from \"./models/room-member.ts\";\nimport { IPowerLevelsContent, RoomStateEvent, RoomStateEventHandlerMap } from \"./models/room-state.ts\";\nimport {\n DelayedEventInfo,\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n IContextResponse,\n ICreateRoomOpts,\n IEventSearchOpts,\n IFilterResponse,\n IGuestAccessOpts,\n IJoinRoomOpts,\n INotificationsResponse,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRelationsRequestOpts,\n IRelationsResponse,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IStatusResponse,\n ITagsResponse,\n KnockRoomOpts,\n SendDelayedEventRequestOpts,\n SendDelayedEventResponse,\n UpdateDelayedEventAction,\n} from \"./@types/requests.ts\";\nimport {\n EventType,\n LOCAL_NOTIFICATION_SETTINGS_PREFIX,\n MSC3912_RELATION_BASED_REDACTIONS_PROP,\n MsgType,\n PUSHER_ENABLED,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n StateEvents,\n TimelineEvents,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event.ts\";\nimport {\n GuestAccess,\n HistoryVisibility,\n IdServerUnbindResult,\n JoinRule,\n Preset,\n Visibility,\n} from \"./@types/partials.ts\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper.ts\";\nimport { randomString } from \"./randomstring.ts\";\nimport { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup.ts\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace.ts\";\nimport { ISignatures } from \"./@types/signed.ts\";\nimport { IStore } from \"./store/index.ts\";\nimport { ISecretRequest } from \"./crypto/SecretStorage.ts\";\nimport {\n IEventWithRoomId,\n ISearchRequestBody,\n ISearchResponse,\n ISearchResults,\n IStateEventWithRoomId,\n SearchOrderBy,\n} from \"./@types/search.ts\";\nimport { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from \"./@types/synapse.ts\";\nimport { IHierarchyRoom } from \"./@types/spaces.ts\";\nimport {\n IPusher,\n IPusherRequest,\n IPushRule,\n IPushRules,\n PushRuleAction,\n PushRuleActionName,\n PushRuleKind,\n RuleId,\n} from \"./@types/PushRules.ts\";\nimport { IThreepid } from \"./@types/threepids.ts\";\nimport { CryptoStore, OutgoingRoomKeyRequest } from \"./crypto/store/base.ts\";\nimport { GroupCall, GroupCallIntent, GroupCallType, IGroupCallDataChannelOptions } from \"./webrtc/groupCall.ts\";\nimport { MediaHandler } from \"./webrtc/mediaHandler.ts\";\nimport {\n ILoginFlowsResponse,\n IRefreshTokenResponse,\n LoginRequest,\n LoginResponse,\n LoginTokenPostResponse,\n SSOAction,\n} from \"./@types/auth.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts.ts\";\nimport { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from \"./sliding-sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport {\n determineFeatureSupport,\n FeatureSupport,\n Thread,\n THREAD_RELATION_TYPE,\n ThreadFilterType,\n threadFilterTypeToFilter,\n} from \"./models/thread.ts\";\nimport { M_BEACON_INFO, MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { NamespacedValue, UnstableValue } from \"./NamespacedValue.ts\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue.ts\";\nimport { ToDeviceBatch } from \"./models/ToDeviceMessage.ts\";\nimport { IgnoredInvites } from \"./models/invites-ignorer.ts\";\nimport { UIARequest, UIAResponse } from \"./@types/uia.ts\";\nimport { LocalNotificationSettings } from \"./@types/local_notifications.ts\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature.ts\";\nimport { BackupDecryptor, CryptoBackend } from \"./common-crypto/CryptoBackend.ts\";\nimport { RUST_SDK_STORE_PREFIX } from \"./rust-crypto/constants.ts\";\nimport {\n BootstrapCrossSigningOpts,\n CrossSigningKeyInfo,\n CryptoApi,\n decodeRecoveryKey,\n ImportRoomKeysOpts,\n CryptoEvent,\n CryptoEventHandlerMap,\n CryptoCallbacks,\n} from \"./crypto-api/index.ts\";\nimport { DeviceInfoMap } from \"./crypto/DeviceList.ts\";\nimport {\n AddSecretStorageKeyOpts,\n SecretStorageKeyDescription,\n ServerSideSecretStorage,\n ServerSideSecretStorageImpl,\n} from \"./secret-storage.ts\";\nimport { RegisterRequest, RegisterResponse } from \"./@types/registration.ts\";\nimport { MatrixRTCSessionManager } from \"./matrixrtc/MatrixRTCSessionManager.ts\";\nimport { getRelationsThreadFilter } from \"./thread-utils.ts\";\nimport { KnownMembership, Membership } from \"./@types/membership.ts\";\nimport { RoomMessageEventContent, StickerEventContent } from \"./@types/events.ts\";\nimport { ImageInfo } from \"./@types/media.ts\";\nimport { Capabilities, ServerCapabilities } from \"./serverCapabilities.ts\";\nimport { sha256 } from \"./digest.ts\";\nimport { keyFromAuthData } from \"./common-crypto/key-passphrase.ts\";\n\nexport type Store = IStore;\n\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\nconst TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes\n\nexport const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\n \"last_seen_user_agent\",\n \"org.matrix.msc3852.last_seen_user_agent\",\n);\n\ninterface IExportedDevice {\n olmDevice: IExportedOlmDevice;\n userId: string;\n deviceId: string;\n}\n\nexport interface IKeysUploadResponse {\n one_time_key_counts: {\n // eslint-disable-line camelcase\n [algorithm: string]: number;\n };\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * A store to be used for end-to-end crypto session data.\n * The `createClient` helper will create a default store if needed. Calls the factory supplied to\n * {@link setCryptoStoreFactory} if unspecified; or if no factory has been\n * specified, uses a default implementation (indexeddb in the browser,\n * in-memory otherwise).\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n cryptoStore?: CryptoStore;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP requests.\n * Most supported environments have a global `fetch` registered to which this will fall back.\n */\n fetchFn?: typeof globalThis.fetch;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n refreshToken?: string;\n\n /**\n * Function used to attempt refreshing access and refresh tokens\n * Called by http-api when a possibly expired token is encountered\n * and a refreshToken is found\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to false to send the access token to the server via a query parameter rather\n * than the Authorization HTTP header.\n *\n * Note that as of v1.11 of the Matrix spec, sending the access token via a query\n * is deprecated.\n *\n * Default true.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support, see {@link MatrixClient#getEventTimeline}.\n * It is disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * `?user_id=`.\n */\n queryParams?: Record<string, string>;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}.\n *\n * This must be set to the same value every time the client is initialised for the same device.\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n pickleKey?: string;\n\n /**\n * Verification methods we should offer to the other side when performing an interactive verification.\n * If unset, we will offer all known methods. Currently these are: showing a QR code, scanning a QR code, and SAS\n * (aka \"emojis\").\n *\n * See {@link types.VerificationMethod} for a set of useful constants for this parameter.\n */\n verificationMethods?: Array<string>;\n\n /**\n * Whether relaying calls through a TURN server should be forced. Default false.\n */\n forceTURN?: boolean;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * True to advertise support for call transfers to other parties on Matrix calls. Default false.\n */\n supportsCallTransfer?: boolean;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n /**\n * If true, to-device signalling for group calls will be encrypted\n * with Olm. Default: true.\n */\n useE2eForGroupCall?: boolean;\n\n livekitServiceURL?: string;\n\n /**\n * Crypto callbacks provided by the application\n */\n cryptoCallbacks?: CryptoCallbacks;\n\n /**\n * Method to generate room names for empty rooms and rooms names based on membership.\n * Defaults to a built-in English handler with basic pluralisation.\n */\n roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;\n\n /**\n * If true, participant can join group call without video and audio this has to be allowed. By default, a local\n * media stream is needed to establish a group call.\n * Default: false.\n */\n isVoipWithNoMediaAllowed?: boolean;\n\n /**\n * If true, group calls will not establish media connectivity and only create the signaling events,\n * so that livekit media can be used in the application layert (js-sdk contains no livekit code).\n */\n useLivekitForGroupCalls?: boolean;\n\n /**\n * A logger to associate with this MatrixClient.\n * Defaults to the built-in global logger.\n */\n logger?: Logger;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event `limit=` to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put `archived=true</code> on the <code>/initialSync` request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"<b>chronological</b>\", messages will\n * appear in the timeline when the call to `sendEvent` was made. If \"<b>detached</b>\",\n * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n\n /**\n * Will organises events in threaded conversations when\n * a thread relation is encountered\n */\n threadSupport?: boolean;\n\n /**\n * @experimental\n */\n slidingSync?: SlidingSync;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts {}\n\nexport const GET_LOGIN_TOKEN_CAPABILITY = new NamespacedValue(\n \"m.get_login_token\",\n \"org.matrix.msc3882.get_login_token\",\n);\n\nexport const UNSTABLE_MSC2666_SHARED_ROOMS = \"uk.half-shot.msc2666\";\nexport const UNSTABLE_MSC2666_MUTUAL_ROOMS = \"uk.half-shot.msc2666.mutual_rooms\";\nexport const UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = \"uk.half-shot.msc2666.query_mutual_rooms\";\n\nexport const UNSTABLE_MSC4140_DELAYED_EVENTS = \"org.matrix.msc4140\";\n\nexport const UNSTABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133\";\n\nenum CrossSigningKeyType {\n MasterKey = \"master_key\",\n SelfSigningKey = \"self_signing_key\",\n UserSigningKey = \"user_signing_key\",\n}\n\nexport type CrossSigningKeys = Record<CrossSigningKeyType, CrossSigningKeyInfo>;\n\nexport type SendToDeviceContentMap = Map<string, Map<string, Record<string, any>>>;\n\nexport interface ISignedKey {\n keys: Record<string, string>;\n signatures: ISignatures;\n user_id: string;\n algorithms: string[];\n device_id: string;\n}\n\nexport type KeySignatures = Record<string, Record<string, CrossSigningKeyInfo | ISignedKey>>;\nexport interface IUploadKeySignaturesResponse {\n failures: Record<\n string,\n Record<\n string,\n {\n errcode: string;\n error: string;\n }\n >\n >;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: undefined | string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\nexport interface ITurnServerResponse {\n uris: string[];\n username: string;\n password: string;\n ttl: number;\n}\n\nexport interface ITurnServer {\n urls: string[];\n username: string;\n credential: string;\n}\n\nexport interface IServerVersions {\n versions: string[];\n unstable_features: Record<string, boolean>;\n}\n\nexport interface IClientWellKnown {\n [key: string]: any;\n \"m.homeserver\"?: IWellKnownConfig;\n \"m.identity_server\"?: IWellKnownConfig;\n}\n\nexport interface IWellKnownConfig<T = IClientWellKnown> {\n raw?: T;\n action?: AutoDiscoveryAction;\n reason?: string;\n error?: Error | string;\n // eslint-disable-next-line\n base_url?: string | null;\n // XXX: this is undocumented\n server_name?: string;\n}\n\ninterface IKeyBackupPath {\n path: string;\n queryData?: {\n version: string;\n };\n}\n\ninterface IMediaConfig {\n [key: string]: any; // extensible\n \"m.upload.size\"?: number;\n}\n\ninterface IThirdPartySigned {\n sender: string;\n mxid: string;\n token: string;\n signatures: ISignatures;\n}\n\ninterface IJoinRequestBody {\n third_party_signed?: IThirdPartySigned;\n}\n\ninterface ITagMetadata {\n [key: string]: any;\n order?: number;\n}\n\ninterface IMessagesResponse {\n start?: string;\n end?: string;\n chunk: IRoomEvent[];\n state?: IStateEvent[];\n}\n\ninterface IThreadedMessagesResponse {\n prev_batch: string;\n next_batch: string;\n chunk: IRoomEvent[];\n state: IStateEvent[];\n}\n\nexport interface IRequestTokenResponse {\n sid: string;\n submit_url?: string;\n}\n\nexport interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {\n msisdn: string;\n success: boolean;\n intl_fmt: string;\n}\n\nexport interface IUploadKeysRequest {\n \"device_keys\"?: Required<IDeviceKeys>;\n \"one_time_keys\"?: Record<string, IOneTimeKey>;\n \"org.matrix.msc2732.fallback_keys\"?: Record<string, IOneTimeKey>;\n}\n\nexport interface IQueryKeysRequest {\n device_keys: { [userId: string]: string[] };\n timeout?: number;\n token?: string;\n}\n\nexport interface IClaimKeysRequest {\n one_time_keys: { [userId: string]: { [deviceId: string]: string } };\n timeout?: number;\n}\n\nexport interface IOpenIDToken {\n access_token: string;\n token_type: \"Bearer\" | string;\n matrix_server_name: string;\n expires_in: number;\n}\n\ninterface IRoomInitialSyncResponse {\n room_id: string;\n membership: Membership;\n messages?: {\n start?: string;\n end?: string;\n chunk: IEventWithRoomId[];\n };\n state?: IStateEventWithRoomId[];\n visibility: Visibility;\n account_data?: IMinimalEvent[];\n presence: Partial<IEvent>; // legacy and undocumented, api is deprecated so this won't get attention\n}\n\ninterface IJoinedRoomsResponse {\n joined_rooms: string[];\n}\n\ninterface IJoinedMembersResponse {\n joined: {\n [userId: string]: {\n display_name: string;\n avatar_url: string;\n };\n };\n}\n\n// Re-export for backwards compatibility\nexport type IRegisterRequestParams = RegisterRequest;\n\nexport interface IPublicRoomsChunkRoom {\n room_id: string;\n name?: string;\n avatar_url?: string;\n topic?: string;\n canonical_alias?: string;\n aliases?: string[];\n world_readable: boolean;\n guest_can_join: boolean;\n num_joined_members: number;\n room_type?: RoomType | string; // Added by MSC3827\n join_rule?: JoinRule.Knock | JoinRule.Public; // Added by MSC2403\n}\n\ninterface IPublicRoomsResponse {\n chunk: IPublicRoomsChunkRoom[];\n next_batch?: string;\n prev_batch?: string;\n total_room_count_estimate?: number;\n}\n\ninterface IUserDirectoryResponse {\n results: {\n user_id: string;\n display_name?: string;\n avatar_url?: string;\n }[];\n limited: boolean;\n}\n\nexport interface IMyDevice {\n \"device_id\": string;\n \"display_name\"?: string;\n \"last_seen_ip\"?: string;\n \"last_seen_ts\"?: number;\n // UNSTABLE_MSC3852_LAST_SEEN_UA\n \"last_seen_user_agent\"?: string;\n \"org.matrix.msc3852.last_seen_user_agent\"?: string;\n}\n\nexport interface Keys {\n keys: { [keyId: string]: string };\n usage: string[];\n user_id: string;\n}\n\nexport interface SigningKeys extends Keys {\n signatures: ISignatures;\n}\n\nexport interface DeviceKeys {\n [deviceId: string]: IDeviceKeys & {\n unsigned?: {\n device_display_name: string;\n };\n };\n}\n\nexport interface IDownloadKeyResult {\n failures: { [serverName: string]: object };\n device_keys: { [userId: string]: DeviceKeys };\n // the following three fields were added in 1.1\n master_keys?: { [userId: string]: Keys };\n self_signing_keys?: { [userId: string]: SigningKeys };\n user_signing_keys?: { [userId: string]: SigningKeys };\n}\n\nexport interface IClaimOTKsResult {\n failures: { [serverName: string]: object };\n one_time_keys: {\n [userId: string]: {\n [deviceId: string]: {\n [keyId: string]: {\n key: string;\n signatures: ISignatures;\n };\n };\n };\n };\n}\n\nexport interface IFieldType {\n regexp: string;\n placeholder: string;\n}\n\nexport interface IInstance {\n desc: string;\n icon?: string;\n fields: object;\n network_id: string;\n // XXX: this is undocumented but we rely on it: https://github.com/matrix-org/matrix-doc/issues/3203\n instance_id: string;\n}\n\nexport interface IProtocol {\n user_fields: string[];\n location_fields: string[];\n icon: string;\n field_types: Record<string, IFieldType>;\n instances: IInstance[];\n}\n\ninterface IThirdPartyLocation {\n alias: string;\n protocol: string;\n fields: object;\n}\n\ninterface IThirdPartyUser {\n userid: string;\n protocol: string;\n fields: object;\n}\n\n/**\n * The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n */\nexport interface RoomSummary extends Omit<IPublicRoomsChunkRoom, \"canonical_alias\" | \"aliases\"> {\n /**\n * The current membership of this user in the room.\n * Usually \"leave\" if the room is fetched over federation.\n */\n \"membership\"?: Membership;\n /**\n * Version of the room.\n */\n \"im.nheko.summary.room_version\"?: string;\n /**\n * The encryption algorithm used for this room, if the room is encrypted.\n */\n \"im.nheko.summary.encryption\"?: string;\n}\n\ninterface IRoomKeysResponse {\n sessions: IKeyBackupRoomSessions;\n}\n\ninterface IRoomsKeysResponse {\n rooms: Record<string, IRoomKeysResponse>;\n}\n\ninterface IRoomHierarchy {\n rooms: IHierarchyRoom[];\n next_batch?: string;\n}\n\nexport interface TimestampToEventResponse {\n event_id: string;\n origin_server_ts: number;\n}\n\ninterface IWhoamiResponse {\n user_id: string;\n device_id?: string;\n is_guest?: boolean;\n}\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nconst EVENT_ID_PREFIX = \"$\";\n\nexport enum ClientEvent {\n Sync = \"sync\",\n Event = \"event\",\n ToDeviceEvent = \"toDeviceEvent\",\n AccountData = \"accountData\",\n Room = \"Room\",\n DeleteRoom = \"deleteRoom\",\n SyncUnexpectedError = \"sync.unexpectedError\",\n ClientWellKnown = \"WellKnown.client\",\n ReceivedVoipEvent = \"received_voip_event\",\n UndecryptableToDeviceEvent = \"toDeviceEvent.undecryptable\",\n TurnServers = \"turnServers\",\n TurnServersError = \"turnServers.error\",\n}\n\ntype RoomEvents =\n | RoomEvent.Name\n | RoomEvent.Redaction\n | RoomEvent.RedactionCancelled\n | RoomEvent.Receipt\n | RoomEvent.Tags\n | RoomEvent.LocalEchoUpdated\n | RoomEvent.HistoryImportedWithinTimeline\n | RoomEvent.AccountData\n | RoomEvent.MyMembership\n | RoomEvent.Timeline\n | RoomEvent.TimelineReset;\n\ntype RoomStateEvents =\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker;\n\ntype LegacyCryptoEvents =\n | LegacyCryptoEvent.KeySignatureUploadFailure\n | LegacyCryptoEvent.KeyBackupStatus\n | LegacyCryptoEvent.KeyBackupFailed\n | LegacyCryptoEvent.KeyBackupSessionsRemaining\n | LegacyCryptoEvent.KeyBackupDecryptionKeyCached\n | LegacyCryptoEvent.RoomKeyRequest\n | LegacyCryptoEvent.RoomKeyRequestCancellation\n | LegacyCryptoEvent.VerificationRequest\n | LegacyCryptoEvent.VerificationRequestReceived\n | LegacyCryptoEvent.DeviceVerificationChanged\n | LegacyCryptoEvent.UserTrustStatusChanged\n | LegacyCryptoEvent.KeysChanged\n | LegacyCryptoEvent.Warning\n | LegacyCryptoEvent.DevicesUpdated\n | LegacyCryptoEvent.WillUpdateDevices\n | LegacyCryptoEvent.LegacyCryptoStoreMigrationProgress;\n\ntype CryptoEvents = (typeof CryptoEvent)[keyof typeof CryptoEvent];\n\ntype MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;\n\ntype RoomMemberEvents =\n | RoomMemberEvent.Name\n | RoomMemberEvent.Typing\n | RoomMemberEvent.PowerLevel\n | RoomMemberEvent.Membership;\n\ntype UserEvents =\n | UserEvent.AvatarUrl\n | UserEvent.DisplayName\n | UserEvent.Presence\n | UserEvent.CurrentlyActive\n | UserEvent.LastPresenceTs;\n\nexport type EmittedEvents =\n | ClientEvent\n | RoomEvents\n | RoomStateEvents\n | LegacyCryptoEvents\n | CryptoEvents\n | MatrixEventEvents\n | RoomMemberEvents\n | UserEvents\n | CallEvent // re-emitted by call.ts using Object.values\n | CallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Outgoing\n | GroupCallEventHandlerEvent.Ended\n | GroupCallEventHandlerEvent.Participants\n | HttpApiEvent.SessionLoggedOut\n | HttpApiEvent.NoConsent\n | BeaconEvent;\n\nexport type ClientEventHandlerMap = {\n /**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n * <ul>\n *\n * <li>PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n * previous API.</i></li>\n *\n * <li>CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.</li>\n *\n * <li>SYNCING : The client is currently polling for new events from the server.\n * This will be called <i>after</i> processing latest events from a sync.</li>\n *\n * <li>ERROR : The client has had a problem syncing with the server. If this is\n * called <i>before</i> PREPARED then there was a problem performing the initial\n * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n * API.</i></li>\n *\n * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n * </li>\n *\n * <li>STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n * </li>\n * </ul>\n * State transition diagram:\n * ```\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * ```\n * Transitions:\n * <ul>\n *\n * <li>`null -> PREPARED` : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n * <li>`null -> ERROR` : Occurs when the initial sync failed first time.\n *\n * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds\n * after previously failing.\n *\n * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.\n *\n * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n *\n * <li>`ERROR -> SYNCING` : Occurs when the client has performed a\n * live update after having previously failed.\n *\n * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive\n * for a second time or more.</li>\n *\n * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live\n * update. This is called <i>after</i> processing.</li>\n *\n * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.</li>\n * </ul>\n *\n * @param state - An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param prevState - An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n *\n * @param data - Data about this transition.\n *\n * @example\n * ```\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n * ```\n */\n [ClientEvent.Sync]: (state: SyncState, prevState: SyncState | null, data?: ISyncStateData) => void;\n /**\n * Fires whenever the SDK receives a new event.\n * <p>\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.Event]: (event: MatrixEvent) => void;\n /**\n * Fires whenever the SDK receives a new to-device event.\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires if a to-device event is received that cannot be decrypted.\n * Encrypted to-device events will (generally) use plain Olm encryption,\n * in which case decryption failures are fatal: the event will never be\n * decryptable, unlike Megolm encrypted events where the key may simply\n * arrive later.\n *\n * An undecryptable to-device event is therefore likley to indicate problems.\n *\n * @param event - The undecyptable to-device event\n */\n [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires whenever new user-scoped account_data is added.\n * @param event - The event describing the account_data just added\n * @param event - The previous account data, if known.\n * @example\n * ```\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n * ```\n */\n [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. <strong>This event is experimental and\n * may change.</strong>\n * @param room - The newly created, fully populated room.\n * @example\n * ```\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n * ```\n */\n [ClientEvent.Room]: (room: Room) => void;\n /**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * <strong>This event is experimental and may change.</strong>\n * @param roomId - The deleted room ID.\n * @example\n * ```\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n * ```\n */\n [ClientEvent.DeleteRoom]: (roomId: string) => void;\n [ClientEvent.SyncUnexpectedError]: (error: Error) => void;\n /**\n * Fires when the client .well-known info is fetched.\n *\n * @param data - The JSON object returned by the server\n */\n [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;\n [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;\n [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;\n [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;\n} & RoomEventHandlerMap &\n RoomStateEventHandlerMap &\n LegacyCryptoEventHandlerMap &\n CryptoEventHandlerMap &\n MatrixEventHandlerMap &\n RoomMemberEventHandlerMap &\n UserEventHandlerMap &\n CallEventHandlerEventHandlerMap &\n GroupCallEventHandlerEventHandlerMap &\n CallEventHandlerMap &\n HttpApiEventHandlerMap &\n BeaconEventHandlerMap;\n\nconst SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = \"RESTORE_BACKUP_ERROR_BAD_KEY\";\n\n private readonly logger: Logger;\n\n public reEmitter = new TypedReEmitter<EmittedEvents, ClientEventHandlerMap>(this);\n public olmVersion: [number, number, number] | null = null; // populated after initCrypto\n public usingExternalCrypto = false;\n private _store!: Store;\n public deviceId: string | null;\n public credentials: { userId: string | null };\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.\n *\n * As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.\n *\n * If unset, either a hardcoded key or no encryption at all is used, depending on the Crypto implementation.\n *\n * @deprecated this should be a private property.\n */\n public pickleKey?: string;\n\n public scheduler?: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse> } = {};\n public identityServer?: IIdentityServerProvider;\n public http: MatrixHttpApi<IHttpOpts & { onlyData: true }>; // XXX: Intended private, used in code.\n\n /**\n * The libolm crypto implementation, if it is in use.\n *\n * @deprecated This should not be used. Instead, use the methods exposed directly on this class or\n * (where they are available) via {@link getCrypto}.\n */\n public crypto?: Crypto; // XXX: Intended private, used in code. Being replaced by cryptoBackend\n\n private cryptoBackend?: CryptoBackend; // one of crypto or rustCrypto\n public cryptoCallbacks: CryptoCallbacks; // XXX: Intended private, used in code.\n public callEventHandler?: CallEventHandler; // XXX: Intended private, used in code.\n public groupCallEventHandler?: GroupCallEventHandler;\n public supportsCallTransfer = false; // XXX: Intended private, used in code.\n public forceTURN = false; // XXX: Intended private, used in code.\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl?: string;\n public baseUrl: string;\n public readonly isVoipWithNoMediaAllowed;\n\n public useLivekitForGroupCalls: boolean;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected canSupportVoip = false;\n protected peekSync: SyncApi | null = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number } } = {};\n protected notifTimelineSet: EventTimelineSet | null = null;\n /* @deprecated */\n protected cryptoStore?: CryptoStore;\n protected verificationMethods?: string[];\n protected fallbackICEServerAllowed = false;\n protected syncApi?: SlidingSyncSdk | SyncApi;\n public roomNameGenerator?: ICreateClientOpts[\"roomNameGenerator\"];\n public pushRules?: IPushRules;\n protected syncLeftRoomsPromise?: Promise<Room[]>;\n protected syncedLeftRooms = false;\n protected clientOpts?: IStoredClientOpts;\n protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>;\n protected canResetTimelineCallback?: ResetTimelineCallback;\n\n public canSupport = new Map<Feature, ServerSupport>();\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise?: Promise<IServerVersions>;\n\n protected clientWellKnown?: IClientWellKnown;\n protected clientWellKnownPromise?: Promise<IClientWellKnown>;\n protected turnServers: ITurnServer[] = [];\n protected turnServersExpiry = 0;\n protected checkTurnServersIntervalID?: ReturnType<typeof setInterval>;\n protected exportedOlmDeviceToImport?: IExportedOlmDevice;\n protected txnCtr = 0;\n protected mediaHandler = new MediaHandler(this);\n protected sessionId: string;\n\n /** IDs of events which are currently being encrypted.\n *\n * This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,\n * that tells us that it has been cancelled, and we should not send it.\n */\n private eventsBeingEncrypted = new Set<string>();\n\n private useE2eForGroupCall = true;\n private toDeviceMessageQueue: ToDeviceMessageQueue;\n public livekitServiceURL?: string;\n\n private _secretStorage: ServerSideSecretStorageImpl;\n\n // A manager for determining which invites should be ignored.\n public readonly ignoredInvites: IgnoredInvites;\n\n public readonly matrixRTC: MatrixRTCSessionManager;\n\n private serverCapabilitiesService: ServerCapabilities;\n\n public constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n // If a custom logger is provided, use it. Otherwise, default to the global\n // one in logger.ts.\n this.logger = opts.logger ?? logger;\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n this.identityServer = opts.identityServer;\n\n this.usingExternalCrypto = opts.usingExternalCrypto ?? false;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n this.sessionId = randomString(10);\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this as ConstructorParameters<typeof MatrixHttpApi>[0], {\n fetchFn: opts.fetchFn,\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n refreshToken: opts.refreshToken,\n tokenRefreshFunction: opts.tokenRefreshFunction,\n prefix: ClientPrefix.V3,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n logger: this.logger,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n this.logger.warn(\n \"not importing device because device ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (this.credentials.userId) {\n this.logger.warn(\n \"not importing device because user ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (!opts.deviceToImport.deviceId) {\n this.logger.warn(\"not importing device because no device ID in exported data\");\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n // will be used during async initialization of the crypto\n this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend: MatrixEvent) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n if (supportsMatrixCall()) {\n this.callEventHandler = new CallEventHandler(this);\n this.groupCallEventHandler = new GroupCallEventHandler(this);\n this.canSupportVoip = true;\n // Start listening for calls after the initial sync is done\n // We do not need to backfill the call event buffer\n // with encrypted events that might never get decrypted\n this.on(ClientEvent.Sync, this.startCallEventHandler);\n }\n\n // NB. We initialise MatrixRTC whether we have call support or not: this is just\n // the underlying session management and doesn't use any actual media capabilities\n this.matrixRTC = new MatrixRTCSessionManager(this);\n\n this.serverCapabilitiesService = new ServerCapabilities(this.http);\n\n this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n\n this.cryptoStore = opts.cryptoStore;\n this.verificationMethods = opts.verificationMethods;\n this.cryptoCallbacks = opts.cryptoCallbacks || {};\n\n this.forceTURN = opts.forceTURN || false;\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.supportsCallTransfer = opts.supportsCallTransfer || false;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n\n if (opts.useE2eForGroupCall !== undefined) this.useE2eForGroupCall = opts.useE2eForGroupCall;\n\n this.livekitServiceURL = opts.livekitServiceURL;\n\n this.roomNameGenerator = opts.roomNameGenerator;\n\n this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);\n\n // The SDK doesn't really provide a clean way for events to recalculate the push\n // actions for themselves, so we have to kinda help them out when they are encrypted.\n // We do this so that push rules are correctly executed on events in their decrypted\n // state, such as highlights when the user's name is mentioned.\n this.on(MatrixEventEvent.Decrypted, (event) => {\n fixNotificationCountOnDecryption(this, event);\n });\n\n this.ignoredInvites = new IgnoredInvites(this);\n this._secretStorage = new ServerSideSecretStorageImpl(this, opts.cryptoCallbacks ?? {});\n\n // having lots of event listeners is not unusual. 0 means \"unlimited\".\n this.setMaxListeners(0);\n }\n\n public set store(newStore: Store) {\n this._store = newStore;\n this._store.setUserCreator((userId) => User.createUser(userId, this));\n }\n\n public get store(): Store {\n return this._store;\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link ClientEvent.Event}\n * via {@link MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param opts - Options to apply when syncing.\n */\n public async startClient(opts?: IStartClientOpts): Promise<void> {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n\n this.on(ClientEvent.Sync, this.startMatrixRTC);\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // periodically poll for turn servers if we support voip\n if (this.canSupportVoip) {\n this.checkTurnServersIntervalID = setInterval(() => {\n this.checkTurnServers();\n }, TURN_CHECK_INTERVAL);\n // noinspection ES6MissingAwait\n this.checkTurnServers();\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n this.logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n try {\n await this.getVersions();\n\n // This should be done with `canSupport`\n // TODO: https://github.com/vector-im/element-web/issues/23643\n const { threads, list, fwdPagination } = await this.doesServerSupportThread();\n Thread.setServerSideSupport(threads);\n Thread.setServerSideListSupport(list);\n Thread.setServerSideFwdPaginationSupport(fwdPagination);\n } catch (e) {\n this.logger.error(\n \"Can't fetch server versions, continuing to initialise sync, this will be retried later\",\n e,\n );\n }\n\n this.clientOpts = opts ?? {};\n if (this.clientOpts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(\n this.clientOpts.slidingSync,\n this,\n this.clientOpts,\n this.buildSyncApiOptions(),\n );\n } else {\n this.syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n }\n\n this.syncApi.sync().catch((e) => this.logger.info(\"Sync startup aborted with an error:\", e));\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID = setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod);\n this.fetchClientWellKnown();\n }\n\n this.toDeviceMessageQueue.start();\n this.serverCapabilitiesService.start();\n }\n\n /**\n * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n */\n protected buildSyncApiOptions(): SyncApiOptions {\n return {\n crypto: this.crypto,\n cryptoCallbacks: this.cryptoBackend,\n canResetEntireTimeline: (roomId: string): boolean => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n },\n };\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient(): void {\n this.cryptoBackend?.stop(); // crypto might have been initialised even if the client wasn't fully started\n\n this.off(ClientEvent.Sync, this.startMatrixRTC);\n\n if (!this.clientRunning) return; // already stopped\n\n this.logger.debug(\"stopping MatrixClient\");\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = undefined;\n\n this.peekSync?.stopPeeking();\n\n this.callEventHandler?.stop();\n this.groupCallEventHandler?.stop();\n this.callEventHandler = undefined;\n this.groupCallEventHandler = undefined;\n\n globalThis.clearInterval(this.checkTurnServersIntervalID);\n this.checkTurnServersIntervalID = undefined;\n\n if (this.clientWellKnownIntervalID !== undefined) {\n globalThis.clearInterval(this.clientWellKnownIntervalID);\n }\n\n this.toDeviceMessageQueue.stop();\n\n this.matrixRTC.stop();\n\n this.serverCapabilitiesService.stop();\n }\n\n /**\n * Try to rehydrate a device if available. The client must have been\n * initialized with a `cryptoCallback.getDehydrationKey` option, and this\n * function must be called before initCrypto and startClient are called.\n *\n * @returns Promise which resolves to undefined if a device could not be dehydrated, or\n * to the new device ID if the dehydration was successful.\n * @returns Rejects: with an error response.\n *\n * @deprecated MSC2697 device dehydration is not supported for rust cryptography.\n */\n public async rehydrateDevice(): Promise<string | undefined> {\n if (this.crypto) {\n throw new Error(\"Cannot rehydrate device after crypto is initialized\");\n }\n\n if (!this.cryptoCallbacks.getDehydrationKey) {\n return;\n }\n\n const getDeviceResult = await this.getDehydratedDevice();\n if (!getDeviceResult) {\n return;\n }\n\n if (!getDeviceResult.device_data || !getDeviceResult.device_id) {\n this.logger.info(\"no dehydrated device found\");\n return;\n }\n\n const account = new globalThis.Olm.Account();\n try {\n const deviceData = getDeviceResult.device_data;\n if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {\n this.logger.warn(\"Wrong algorithm for dehydrated device\");\n return;\n }\n this.logger.debug(\"unpickling dehydrated device\");\n const key = await this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => {\n // copy the key so that it doesn't get clobbered\n account.unpickle(new Uint8Array(k), deviceData.account);\n });\n account.unpickle(key, deviceData.account);\n this.logger.debug(\"unpickled device\");\n\n const rehydrateResult = await this.http.authedRequest<{ success: boolean }>(\n Method.Post,\n \"/dehydrated_device/claim\",\n undefined,\n {\n device_id: getDeviceResult.device_id,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n if (rehydrateResult.success) {\n this.deviceId = getDeviceResult.device_id;\n this.logger.info(\"using dehydrated device\");\n const pickleKey = this.pickleKey || \"DEFAULT_KEY\";\n this.exportedOlmDeviceToImport = {\n pickledAccount: account.pickle(pickleKey),\n sessions: [],\n pickleKey: pickleKey,\n };\n account.free();\n return this.deviceId;\n } else {\n account.free();\n this.logger.info(\"not using dehydrated device\");\n return;\n }\n } catch (e) {\n account.free();\n this.logger.warn(\"could not unpickle\", e);\n }\n }\n\n /**\n * Get the current dehydrated device, if any\n * @returns A promise of an object containing the dehydrated device\n *\n * @deprecated MSC2697 device dehydration is not supported for rust cryptography.\n */\n public async getDehydratedDevice(): Promise<IDehydratedDevice | undefined> {\n try {\n return await this.http.authedRequest<IDehydratedDevice>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n } catch (e) {\n this.logger.info(\"could not get dehydrated device\", e);\n return;\n }\n }\n\n /**\n * Set the dehydration key. This will also periodically dehydrate devices to\n * the server.\n *\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns A promise that resolves when the dehydrated device is stored.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public async setDehydrationKey(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<void> {\n if (!this.crypto) {\n this.logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n return this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName);\n }\n\n /**\n * Creates a new MSC2967 dehydrated device (without queuing periodic dehydration)\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns the device id of the newly created dehydrated device\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.startDehydration}.\n */\n public async createDehydratedDevice(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<string | undefined> {\n if (!this.crypto) {\n this.logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n await this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName);\n return this.crypto.dehydrationManager.dehydrateDevice();\n }\n\n /** @deprecated Not supported for Rust Cryptography. */\n public async exportDevice(): Promise<IExportedDevice | undefined> {\n if (!this.crypto) {\n this.logger.warn(\"not exporting device if crypto is not enabled\");\n return;\n }\n return {\n userId: this.credentials.userId!,\n deviceId: this.deviceId!,\n // XXX: Private member access.\n olmDevice: await this.crypto.olmDevice.export(),\n };\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise<void> {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises: Promise<void>[] = [];\n\n promises.push(this.store.deleteAllData());\n if (this.cryptoStore) {\n promises.push(this.cryptoStore.deleteAllData());\n }\n\n // delete the stores used by the rust matrix-sdk-crypto, in case they were used\n const deleteRustSdkStore = async (): Promise<void> => {\n let indexedDB: IDBFactory;\n try {\n indexedDB = globalThis.indexedDB;\n if (!indexedDB) return; // No indexedDB support\n } catch {\n // No indexedDB support\n return;\n }\n for (const dbname of [\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`,\n ]) {\n const prom = new Promise((resolve, reject) => {\n this.logger.info(`Removing IndexedDB instance ${dbname}`);\n const req = indexedDB.deleteDatabase(dbname);\n req.onsuccess = (_): void => {\n this.logger.info(`Removed IndexedDB instance ${dbname}`);\n resolve(0);\n };\n req.onerror = (e): void => {\n // In private browsing, Firefox has a globalThis.indexedDB, but attempts to delete an indexeddb\n // (even a non-existent one) fail with \"DOMException: A mutation operation was attempted on a\n // database that did not allow mutations.\"\n //\n // it seems like the only thing we can really do is ignore the error.\n this.logger.warn(`Failed to remove IndexedDB instance ${dbname}:`, e);\n resolve(0);\n };\n req.onblocked = (e): void => {\n this.logger.info(`cannot yet remove IndexedDB instance ${dbname}`);\n };\n });\n await prom;\n }\n };\n promises.push(deleteRustSdkStore());\n\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user\n * @throws Error if not logged in\n */\n public getSafeUserId(): string {\n const userId = this.getUserId();\n if (!userId) {\n throw new Error(\"Expected logged in user but found none.\");\n }\n return userId;\n }\n\n /**\n * Get the domain for this client's MXID\n * @returns Domain of this MXID\n */\n public getDomain(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, \"\");\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n * @returns The user ID localpart or null.\n */\n public getUserIdLocalpart(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @returns device ID\n */\n public getDeviceId(): string | null {\n return this.deviceId;\n }\n\n /**\n * Get the session ID of this client\n * @returns session ID\n */\n public getSessionId(): string {\n return this.sessionId;\n }\n\n /**\n * Check if the runtime environment supports VoIP calling.\n * @returns True if VoIP is supported.\n */\n public supportsVoip(): boolean {\n return this.canSupportVoip;\n }\n\n /**\n * @returns\n */\n public getMediaHandler(): MediaHandler {\n return this.mediaHandler;\n }\n\n /**\n * Set whether VoIP calls are forced to use only TURN\n * candidates. This is the same as the forceTURN option\n * when creating the client.\n * @param force - True to force use of TURN servers\n */\n public setForceTURN(force: boolean): void {\n this.forceTURN = force;\n }\n\n /**\n * Set whether to advertise transfer support to other parties on Matrix calls.\n * @param support - True to advertise the 'm.call.transferee' capability\n */\n public setSupportsCallTransfer(support: boolean): void {\n this.supportsCallTransfer = support;\n }\n\n /**\n * Returns true if to-device signalling for group calls will be encrypted with Olm.\n * If false, it will be sent unencrypted.\n * @returns boolean Whether group call signalling will be encrypted\n */\n public getUseE2eForGroupCall(): boolean {\n return this.useE2eForGroupCall;\n }\n\n /**\n * Creates a new call.\n * The place*Call methods on the returned call can be used to actually place a call\n *\n * @param roomId - The room the call is to be placed in.\n * @returns the call or null if the browser doesn't support calling.\n */\n public createCall(roomId: string): MatrixCall | null {\n return createNewMatrixCall(this, roomId);\n }\n\n /**\n * Creates a new group call and sends the associated state event\n * to alert other members that the room now has a group call.\n *\n * @param roomId - The room the call is to be placed in.\n */\n public async createGroupCall(\n roomId: string,\n type: GroupCallType,\n isPtt: boolean,\n intent: GroupCallIntent,\n dataChannelsEnabled?: boolean,\n dataChannelOptions?: IGroupCallDataChannelOptions,\n ): Promise<GroupCall> {\n if (this.getGroupCallForRoom(roomId)) {\n throw new Error(`${roomId} already has an existing group call`);\n }\n\n const room = this.getRoom(roomId);\n\n if (!room) {\n throw new Error(`Cannot find room ${roomId}`);\n }\n\n // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n // no media WebRTC connection anyway.\n return new GroupCall(\n this,\n room,\n type,\n isPtt,\n intent,\n undefined,\n dataChannelsEnabled || this.isVoipWithNoMediaAllowed,\n dataChannelOptions,\n this.isVoipWithNoMediaAllowed,\n this.useLivekitForGroupCalls,\n this.livekitServiceURL,\n ).create();\n }\n\n public getLivekitServiceURL(): string | undefined {\n return this.livekitServiceURL;\n }\n\n // This shouldn't need to exist, but the widget API has startup ordering problems that\n // mean it doesn't know the livekit URL fast enough: remove this once this is fixed.\n public setLivekitServiceURL(newURL: string): void {\n this.livekitServiceURL = newURL;\n }\n\n /**\n * Wait until an initial state for the given room has been processed by the\n * client and the client is aware of any ongoing group calls. Awaiting on\n * the promise returned by this method before calling getGroupCallForRoom()\n * avoids races where getGroupCallForRoom is called before the state for that\n * room has been processed. It does not, however, fix other races, eg. two\n * clients both creating a group call at the same time.\n * @param roomId - The room ID to wait for\n * @returns A promise that resolves once existing group calls in the room\n * have been processed.\n */\n public waitUntilRoomReadyForGroupCalls(roomId: string): Promise<void> {\n return this.groupCallEventHandler!.waitUntilRoomReadyForGroupCalls(roomId);\n }\n\n /**\n * Get an existing group call for the provided room.\n * @returns The group call or null if it doesn't already exist.\n */\n public getGroupCallForRoom(roomId: string): GroupCall | null {\n return this.groupCallEventHandler!.groupCalls.get(roomId) || null;\n }\n\n /**\n * Get the current sync state.\n * @returns the sync state, which may be null.\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncApi?.getSyncState() ?? null;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @returns True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @returns True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. <b>This method is experimental\n * and may change without warning.</b>\n * @param guest - True if this is a guest account.\n * @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'\n * access token, which means that the SDK can determine this entirely without\n * the dev manually flipping this flag.\n */\n public setGuest(guest: boolean): void {\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @returns The scheduler or undefined\n */\n public getScheduler(): MatrixScheduler | undefined {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * Will also retry any outbound to-device messages currently in the queue to be sent\n * (retries of regular outgoing events are handled separately, per-event).\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n // don't await for this promise: we just want to kick it off\n this.toDeviceMessageQueue.sendQueue();\n return this.syncApi?.retryImmediately() ?? false;\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @returns the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet | null {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n */\n public setNotifTimelineSet(set: EventTimelineSet): void {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the cached capabilities of the homeserver, returning cached ones if available.\n * If there are no cached capabilities and none can be fetched, throw an exception.\n *\n * @returns Promise resolving with The capabilities of the homeserver\n */\n public async getCapabilities(): Promise<Capabilities> {\n const caps = this.serverCapabilitiesService.getCachedCapabilities();\n if (caps) return caps;\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Gets the cached capabilities of the homeserver. If none have been fetched yet,\n * return undefined.\n *\n * @returns The capabilities of the homeserver\n */\n public getCachedCapabilities(): Capabilities | undefined {\n return this.serverCapabilitiesService.getCachedCapabilities();\n }\n\n /**\n * Fetches the latest capabilities from the homeserver, ignoring any cached\n * versions. The newly returned version is cached.\n *\n * @returns A promise which resolves to the capabilities of the homeserver\n */\n public fetchCapabilities(): Promise<Capabilities> {\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using libolm.\n *\n * You should call this method after creating the matrixclient, but *before*\n * calling `startClient`, if you want to support end-to-end encryption.\n *\n * It will return a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n *\n * @deprecated libolm is deprecated. Prefer {@link initRustCrypto}.\n */\n public async initCrypto(): Promise<void> {\n if (this.cryptoBackend) {\n this.logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n if (!this.cryptoStore) {\n // the cryptostore is provided by sdk.createClient, so this shouldn't happen\n throw new Error(`Cannot enable encryption: no cryptoStore provided`);\n }\n\n this.logger.debug(\"Crypto: Starting up crypto store...\");\n await this.cryptoStore.startup();\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n if (this.deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n const crypto = new Crypto(this, userId, this.deviceId, this.store, this.cryptoStore, this.verificationMethods!);\n\n this.reEmitter.reEmit(crypto, [\n LegacyCryptoEvent.KeyBackupFailed,\n LegacyCryptoEvent.KeyBackupSessionsRemaining,\n LegacyCryptoEvent.RoomKeyRequest,\n LegacyCryptoEvent.RoomKeyRequestCancellation,\n LegacyCryptoEvent.Warning,\n LegacyCryptoEvent.DevicesUpdated,\n LegacyCryptoEvent.WillUpdateDevices,\n LegacyCryptoEvent.DeviceVerificationChanged,\n LegacyCryptoEvent.UserTrustStatusChanged,\n LegacyCryptoEvent.KeysChanged,\n ]);\n\n this.logger.debug(\"Crypto: initialising crypto object...\");\n await crypto.init({\n exportedOlmDevice: this.exportedOlmDeviceToImport,\n pickleKey: this.pickleKey,\n });\n delete this.exportedOlmDeviceToImport;\n\n this.olmVersion = Crypto.getOlmVersion();\n\n // if crypto initialisation was successful, tell it to attach its event handlers.\n crypto.registerEventHandlers(this as Parameters<Crypto[\"registerEventHandlers\"]>[0]);\n this.cryptoBackend = this.crypto = crypto;\n\n // upload our keys in the background\n this.crypto.uploadDeviceKeys().catch((e) => {\n // TODO: throwing away this error is a really bad idea.\n this.logger.error(\"Error uploading device keys\", e);\n });\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.\n *\n * An alternative to {@link initCrypto}.\n *\n * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.\n * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly\n * 32 bytes of data, and must be the same each time the client is initialised for a given device.\n * If both this and `storagePassword` are unspecified, the store will be unencrypted.\n * @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to\n * encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer\n * to pass a `storageKey` directly where possible.\n *\n * @returns a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n */\n public async initRustCrypto(\n args: {\n useIndexedDB?: boolean;\n storageKey?: Uint8Array;\n storagePassword?: string;\n } = {},\n ): Promise<void> {\n if (this.cryptoBackend) {\n this.logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n const deviceId = this.getDeviceId();\n if (deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n // importing rust-crypto will download the webassembly, so we delay it until we know it will be\n // needed.\n this.logger.debug(\"Downloading Rust crypto library\");\n const RustCrypto = await import(\"./rust-crypto/index.ts\");\n\n const rustCrypto = await RustCrypto.initRustCrypto({\n logger: this.logger,\n http: this.http,\n userId: userId,\n deviceId: deviceId,\n secretStorage: this.secretStorage,\n cryptoCallbacks: this.cryptoCallbacks,\n storePrefix: args.useIndexedDB === false ? null : RUST_SDK_STORE_PREFIX,\n storeKey: args.storageKey,\n storePassphrase: args.storagePassword,\n\n legacyCryptoStore: this.cryptoStore,\n legacyPickleKey: this.pickleKey ?? \"DEFAULT_KEY\",\n legacyMigrationProgressListener: (progress: number, total: number): void => {\n this.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total);\n },\n });\n\n rustCrypto.setSupportedVerificationMethods(this.verificationMethods);\n\n this.cryptoBackend = rustCrypto;\n\n // attach the event listeners needed by RustCrypto\n this.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto));\n this.on(ClientEvent.Event, (event) => {\n rustCrypto.onLiveEventFromSync(event);\n });\n\n // re-emit the events emitted by the crypto impl\n this.reEmitter.reEmit(rustCrypto, [\n CryptoEvent.VerificationRequestReceived,\n CryptoEvent.UserTrustStatusChanged,\n CryptoEvent.KeyBackupStatus,\n CryptoEvent.KeyBackupSessionsRemaining,\n CryptoEvent.KeyBackupFailed,\n CryptoEvent.KeyBackupDecryptionKeyCached,\n CryptoEvent.KeysChanged,\n CryptoEvent.DevicesUpdated,\n CryptoEvent.WillUpdateDevices,\n ]);\n }\n\n /**\n * Access the server-side secret storage API for this client.\n */\n public get secretStorage(): ServerSideSecretStorage {\n return this._secretStorage;\n }\n\n /**\n * Access the crypto API for this client.\n *\n * If end-to-end encryption has been enabled for this client (via {@link initCrypto} or {@link initRustCrypto}),\n * returns an object giving access to the crypto API. Otherwise, returns `undefined`.\n */\n public getCrypto(): CryptoApi | undefined {\n return this.cryptoBackend;\n }\n\n /**\n * Is end-to-end crypto enabled for this client.\n * @returns True if end-to-end is enabled.\n * @deprecated prefer {@link getCrypto}\n */\n public isCryptoEnabled(): boolean {\n return !!this.cryptoBackend;\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @returns base64-encoded ed25519 key. Null if crypto is\n * disabled.\n *\n * @deprecated Not supported for Rust Cryptography.Prefer {@link CryptoApi.getOwnDeviceKeys}\n */\n public getDeviceEd25519Key(): string | null {\n return this.crypto?.getDeviceEd25519Key() ?? null;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @returns base64-encoded curve25519 key. Null if crypto is\n * disabled.\n *\n * @deprecated Not supported for Rust Cryptography. Use {@link CryptoApi.getOwnDeviceKeys}\n */\n public getDeviceCurve25519Key(): string | null {\n return this.crypto?.getDeviceCurve25519Key() ?? null;\n }\n\n /**\n * @deprecated Does nothing.\n */\n public async uploadKeys(): Promise<void> {\n this.logger.warn(\"MatrixClient.uploadKeys is deprecated\");\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map userId-\\>deviceId-\\>`DeviceInfo`\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise<DeviceInfoMap> {\n if (!this.crypto) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.crypto.downloadKeys(userIds, forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevicesForUser(userId) || [];\n }\n\n /**\n * Get the stored device key for a user id and device id\n *\n * @param userId - the user to list keys for.\n * @param deviceId - unique identifier for the device\n *\n * @returns device or null\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevice(userId, deviceId) || null;\n }\n\n /**\n * Mark the given device as verified\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param verified - whether to mark the device as verified. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n */\n public setDeviceVerified(userId: string, deviceId: string, verified = true): Promise<void> {\n const prom = this.setDeviceVerification(userId, deviceId, verified, null, null);\n\n // if one of the user's own devices is being marked as verified / unverified,\n // check the key backup status, since whether or not we use this depends on\n // whether it has a signature from a verified device\n if (userId == this.credentials.userId) {\n this.checkKeyBackup();\n }\n return prom;\n }\n\n /**\n * Mark the given device as blocked/unblocked\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param blocked - whether to mark the device as blocked. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link LegacyCryptoEvent.DeviceVerificationChanged}\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public setDeviceBlocked(userId: string, deviceId: string, blocked = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, blocked, null);\n }\n\n /**\n * Mark the given device as known/unknown\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param known - whether to mark the device as known. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public setDeviceKnown(userId: string, deviceId: string, known = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, null, known);\n }\n\n private async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified?: boolean | null,\n blocked?: boolean | null,\n known?: boolean | null,\n ): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n await this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);\n }\n\n /**\n * Request a key verification from another user, using a DM.\n *\n * @param userId - the user to request verification with\n * @param roomId - the room to use for verification\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.requestVerificationDM}.\n */\n public requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerificationDM(userId, roomId);\n }\n\n /**\n * Finds a DM verification request that is already in progress for the given room id\n *\n * @param roomId - the room to use for verification\n *\n * @returns the VerificationRequest that is in progress, if any\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.findVerificationRequestDMInProgress}.\n */\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n } else if (!this.crypto) {\n // Hack for element-R to avoid breaking the cypress tests. We can get rid of this once the react-sdk is\n // updated to use CryptoApi.findVerificationRequestDMInProgress.\n return undefined;\n }\n return this.crypto.findVerificationRequestDMInProgress(roomId);\n }\n\n /**\n * Returns all to-device verification requests that are already in progress for the given user id\n *\n * @param userId - the ID of the user to query\n *\n * @returns the VerificationRequests that are in progress\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getVerificationRequestsToDeviceInProgress}.\n */\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getVerificationRequestsToDeviceInProgress(userId);\n }\n\n /**\n * Request a key verification from another user.\n *\n * @param userId - the user to request verification with\n * @param devices - array of device IDs to send requests to. Defaults to\n * all devices owned by the user\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}.\n */\n public requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerification(userId, devices);\n }\n\n /**\n * Begin a key verification.\n *\n * @param method - the verification method to use\n * @param userId - the user to verify keys with\n * @param deviceId - the device to verify\n *\n * @returns a verification object\n * @deprecated Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}.\n */\n public beginKeyVerification(method: string, userId: string, deviceId: string): Verification<any, any> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.beginKeyVerification(method, userId, deviceId);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#checkKey}.\n */\n public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise<boolean> {\n return this.secretStorage.checkKey(key, info);\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param value - whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * client.getCrypto().globalBlacklistUnverifiedDevices = value;\n * ```\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalBlacklistUnverifiedDevices = value;\n return value;\n }\n\n /**\n * @returns whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * value = client.getCrypto().globalBlacklistUnverifiedDevices;\n * ```\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Set whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send them message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n *\n * It has no effect with the Rust crypto implementation.\n *\n * @param value - whether error on unknown devices\n *\n * ```ts\n * client.getCrypto().globalErrorOnUnknownDevices = value;\n * ```\n */\n public setGlobalErrorOnUnknownDevices(value: boolean): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalErrorOnUnknownDevices = value;\n }\n\n /**\n * @returns whether to error on unknown devices\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n */\n public getGlobalErrorOnUnknownDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalErrorOnUnknownDevices;\n }\n\n /**\n * Get the ID of one of the user's cross-signing keys\n *\n * @param type - The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the key ID\n * @deprecated Not supported for Rust Cryptography. prefer {@link Crypto.CryptoApi#getCrossSigningKeyId}\n */\n public getCrossSigningId(type: CrossSigningKey | string = CrossSigningKey.Master): string | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCrossSigningId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - the user ID to get the cross-signing info for.\n *\n * @returns the cross signing information for the user.\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#userHasCrossSigningKeys}\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user to check.\n *\n * @deprecated Use {@link Crypto.CryptoApi.getUserVerificationStatus | `CryptoApi.getUserVerificationStatus`}\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkUserTrust(userId);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param deviceId - The ID of the device to check\n *\n * @deprecated Use {@link Crypto.CryptoApi.getDeviceVerificationStatus | `CryptoApi.getDeviceVerificationStatus`}\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkDeviceTrust(userId, deviceId);\n }\n\n /**\n * Check whether one of our own devices is cross-signed by our\n * user's stored keys, regardless of whether we trust those keys yet.\n *\n * @param deviceId - The ID of the device to check\n *\n * @returns true if the device is cross-signed\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public checkIfOwnDeviceCrossSigned(deviceId: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkIfOwnDeviceCrossSigned(deviceId);\n }\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n * @param opts - ICheckOwnCrossSigningTrustOpts object\n *\n * @deprecated Unneeded for the new crypto\n */\n public checkOwnCrossSigningTrust(opts?: ICheckOwnCrossSigningTrustOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkOwnCrossSigningTrust(opts);\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestDeviceVerification}.\n */\n public legacyDeviceVerification(userId: string, deviceId: string, method: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.legacyDeviceVerification(userId, deviceId, method);\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n * @param room - the room the event is in\n *\n * @deprecated Prefer {@link CryptoApi.prepareToEncrypt | `CryptoApi.prepareToEncrypt`}:\n *\n * ```javascript\n * client.getCrypto().prepareToEncrypt(room);\n * ```\n */\n public prepareToEncrypt(room: Room): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.prepareToEncrypt(room);\n }\n\n /**\n * Checks if the user has previously published cross-signing keys\n *\n * This means downloading the devicelist for the user and checking if the list includes\n * the cross-signing pseudo-device.\n *\n * @deprecated Prefer {@link CryptoApi.userHasCrossSigningKeys | `CryptoApi.userHasCrossSigningKeys`}:\n *\n * ```javascript\n * result = client.getCrypto().userHasCrossSigningKeys();\n * ```\n */\n public userHasCrossSigningKeys(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.userHasCrossSigningKeys();\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n * @returns True if cross-signing is ready to be used on this device\n * @deprecated Prefer {@link CryptoApi.isCrossSigningReady | `CryptoApi.isCrossSigningReady`}:\n */\n public isCrossSigningReady(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.isCrossSigningReady();\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been set up)\n *\n * @deprecated Prefer {@link CryptoApi.bootstrapCrossSigning | `CryptoApi.bootstrapCrossSigning`}.\n */\n public bootstrapCrossSigning(opts: BootstrapCrossSigningOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.bootstrapCrossSigning(opts);\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @returns True if trusting cross-signed devices\n *\n * @deprecated Prefer {@link CryptoApi.getTrustCrossSignedDevices | `CryptoApi.getTrustCrossSignedDevices`}.\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getTrustCrossSignedDevices();\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n *\n * @param val - True to trust cross-signed devices\n *\n * @deprecated Prefer {@link CryptoApi.setTrustCrossSignedDevices | `CryptoApi.setTrustCrossSignedDevices`}.\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.setTrustCrossSignedDevices(val);\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public countSessionsNeedingBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.countSessionsNeedingBackup();\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param event - event to be checked\n * @returns The event information.\n * @deprecated Prefer {@link Crypto.CryptoApi.getEncryptionInfoForEvent | `CryptoApi.getEncryptionInfoForEvent`}.\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getEventEncryptionInfo(event);\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n *\n * @deprecated Prefer {@link CryptoApi.createRecoveryKeyFromPassphrase | `CryptoApi.createRecoveryKeyFromPassphrase`}.\n */\n public createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.createRecoveryKeyFromPassphrase(password);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * @returns True if secret storage is ready to be used on this device\n * @deprecated Prefer {@link CryptoApi.isSecretStorageReady | `CryptoApi.isSecretStorageReady`}.\n */\n public isSecretStorageReady(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.isSecretStorageReady();\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * @deprecated Use {@link CryptoApi.bootstrapSecretStorage | `CryptoApi.bootstrapSecretStorage`}.\n */\n public bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.bootstrapSecretStorage(opts);\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param algorithm - the algorithm used by the key\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyName - the name of the key. If not given, a random name will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#addKey}.\n */\n public addSecretStorageKey(\n algorithm: string,\n opts: AddSecretStorageKeyOpts,\n keyName?: string,\n ): Promise<{ keyId: string; keyInfo: SecretStorageKeyDescription }> {\n return this.secretStorage.addKey(algorithm, opts, keyName);\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#hasKey}.\n */\n public hasSecretStorageKey(keyId?: string): Promise<boolean> {\n return this.secretStorage.hasKey(keyId);\n }\n\n /**\n * Store an encrypted secret on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - The name of the secret\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret or null/undefined\n * to use the default (will throw if no default key is set).\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#store}.\n */\n public storeSecret(name: string, secret: string, keys?: string[]): Promise<void> {\n return this.secretStorage.store(name, secret, keys);\n }\n\n /**\n * Get a secret from storage.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n *\n * @returns the contents of the secret\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#get}.\n */\n public getSecret(name: string): Promise<string | undefined> {\n return this.secretStorage.get(name);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#isStored}.\n */\n public isSecretStored(name: string): Promise<Record<string, SecretStorageKeyDescription> | null> {\n return this.secretStorage.isStored(name);\n }\n\n /**\n * Request a secret from another device.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret to request\n * @param devices - the devices to request the secret from\n *\n * @returns the secret request object\n * @deprecated Not supported for Rust Cryptography.\n */\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestSecret(name, devices);\n }\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns The default key ID or null if no default key ID is set\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getDefaultKeyId}.\n */\n public getDefaultSecretStorageKeyId(): Promise<string | null> {\n return this.secretStorage.getDefaultKeyId();\n }\n\n /**\n * Set the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The new default key ID\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#setDefaultKeyId}.\n */\n public setDefaultSecretStorageKeyId(keyId: string): Promise<void> {\n return this.secretStorage.setDefaultKeyId(keyId);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n *\n * @deprecated The use of asymmetric keys for SSSS is deprecated.\n * Use {@link SecretStorage.ServerSideSecretStorage#checkKey} for symmetric keys.\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * Get e2e information on the device that sent an event\n *\n * @param event - event to be checked\n * @deprecated Not supported for Rust Cryptography.\n */\n public async getEventSenderDeviceInfo(event: MatrixEvent): Promise<DeviceInfo | null> {\n if (!this.crypto) {\n return null;\n }\n return this.crypto.getEventSenderDeviceInfo(event);\n }\n\n /**\n * Check if the sender of an event is verified\n *\n * @param event - event to be checked\n *\n * @returns true if the sender of this event has been verified using\n * {@link MatrixClient#setDeviceVerified}.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public async isEventSenderVerified(event: MatrixEvent): Promise<boolean> {\n const device = await this.getEventSenderDeviceInfo(event);\n if (!device) {\n return false;\n }\n return device.isVerified();\n }\n\n /**\n * Get outgoing room key request for this event if there is one.\n * @param event - The event to check for\n *\n * @returns A room key request, or null if there is none\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public getOutgoingRoomKeyRequest(event: MatrixEvent): Promise<OutgoingRoomKeyRequest | null> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n const wireContent = event.getWireContent();\n const requestBody: IRoomKeyRequestBody = {\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key,\n algorithm: wireContent.algorithm,\n room_id: event.getRoomId()!,\n };\n if (!requestBody.session_id || !requestBody.sender_key || !requestBody.algorithm || !requestBody.room_id) {\n return Promise.resolve(null);\n }\n return this.crypto.cryptoStore.getOutgoingRoomKeyRequest(requestBody);\n }\n\n /**\n * Cancel a room key request for this event if one is ongoing and resend the\n * request.\n * @param event - event of which to cancel and resend the room\n * key request.\n * @returns A promise that will resolve when the key request is queued\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return event.cancelAndResendKeyRequest(this.crypto, this.getUserId()!);\n }\n\n /**\n * Enable end-to-end encryption for a room. This does not modify room state.\n * Any messages sent before the returned promise resolves will be sent unencrypted.\n * @param roomId - The room ID to enable encryption in.\n * @param config - The encryption config for the room.\n * @returns A promise that will resolve when encryption is set up.\n *\n * @deprecated Not supported for Rust Cryptography. To enable encryption in a room, send an `m.room.encryption`\n * state event.\n */\n public setRoomEncryption(roomId: string, config: IRoomEncryption): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.setRoomEncryption(roomId, config);\n }\n\n /**\n * Whether encryption is enabled for a room.\n * @param roomId - the room id to query.\n * @returns whether encryption is enabled.\n *\n * @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or\n * {@link Room.hasEncryptionStateEvent}.\n */\n public isRoomEncrypted(roomId: string): boolean {\n const room = this.getRoom(roomId);\n if (!room) {\n // we don't know about this room, so can't determine if it should be\n // encrypted. Let's assume not.\n return false;\n }\n\n // if there is an 'm.room.encryption' event in this room, it should be\n // encrypted (independently of whether we actually support encryption)\n if (room.hasEncryptionStateEvent()) {\n return true;\n }\n\n // we don't have an m.room.encrypted event, but that might be because\n // the server is hiding it from us. Check the store to see if it was\n // previously encrypted.\n return this.crypto?.isRoomEncrypted(roomId) ?? false;\n }\n\n /**\n * Encrypts and sends a given object via Olm to-device messages to a given\n * set of devices.\n *\n * @param userDeviceInfoArr - list of deviceInfo objects representing the devices to send to\n *\n * @param payload - fields to include in the encrypted payload\n *\n * @returns Promise which\n * resolves once the message has been encrypted and sent to the given\n * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }`\n * of the successfully sent messages.\n *\n * @deprecated Instead use {@link CryptoApi.encryptToDeviceMessages} followed by {@link queueToDevice}.\n */\n public encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice<DeviceInfo>[], payload: object): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.encryptAndSendToDevices(userDeviceInfoArr, payload);\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param roomId - The ID of the room to discard the session for\n *\n * @deprecated Prefer {@link CryptoApi.forceDiscardSession | `CryptoApi.forceDiscardSession`}:\n */\n public forceDiscardSession(roomId: string): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n this.cryptoBackend.forceDiscardSession(roomId);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * This should be encrypted before returning it to the user.\n *\n * @returns a promise which resolves to a list of session export objects\n *\n * @deprecated Prefer {@link CryptoApi.exportRoomKeys | `CryptoApi.exportRoomKeys`}:\n *\n * ```javascript\n * sessionData = await client.getCrypto().exportRoomKeys();\n * ```\n */\n public exportRoomKeys(): Promise<IMegolmSessionData[]> {\n if (!this.cryptoBackend) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.cryptoBackend.exportRoomKeys();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param keys - a list of session export objects\n * @param opts - options object\n *\n * @returns a promise which resolves when the keys have been imported\n *\n * @deprecated Prefer {@link CryptoApi.importRoomKeys | `CryptoApi.importRoomKeys`}:\n * ```javascript\n * await client.getCrypto()?.importRoomKeys([..]);\n * ```\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts?: ImportRoomKeysOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.importRoomKeys(keys, opts);\n }\n\n /**\n * Force a re-check of the local key backup status against\n * what's on the server.\n *\n * @returns Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n *\n * @deprecated Prefer {@link Crypto.CryptoApi.checkKeyBackupAndEnable}.\n */\n public checkKeyBackup(): Promise<IKeyBackupCheck | null> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.checkKeyBackup();\n }\n\n /**\n * Get information about the current key backup from the server.\n *\n * Performs some basic validity checks on the shape of the result, and raises an error if it is not as expected.\n *\n * **Note**: there is no (supported) way to distinguish between \"failure to talk to the server\" and \"another client\n * uploaded a key backup version using an algorithm I don't understand.\n *\n * @returns Information object from API, or null if no backup is present on the server.\n *\n * @deprecated Prefer {@link CryptoApi.getKeyBackupInfo}.\n */\n public async getKeyBackupVersion(): Promise<IKeyBackupInfo | null> {\n let res: IKeyBackupInfo;\n try {\n res = await this.http.authedRequest<IKeyBackupInfo>(\n Method.Get,\n \"/room_keys/version\",\n undefined,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n } catch (e) {\n if ((<MatrixError>e).errcode === \"M_NOT_FOUND\") {\n return null;\n } else {\n throw e;\n }\n }\n BackupManager.checkBackupVersion(res);\n return res;\n }\n\n /**\n * @param info - key backup info dict from getKeyBackupVersion()\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.isKeyBackupTrusted | `CryptoApi.isKeyBackupTrusted`}.\n */\n public isKeyBackupTrusted(info: IKeyBackupInfo): Promise<TrustInfo> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.isKeyBackupTrusted(info);\n }\n\n /**\n * @returns true if the client is configured to back up keys to\n * the server, otherwise false. If we haven't completed a successful check\n * of key backup status yet, returns null.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer direct access to {@link Crypto.CryptoApi.getActiveSessionBackupVersion}:\n *\n * ```javascript\n * let enabled = (await client.getCrypto().getActiveSessionBackupVersion()) !== null;\n * ```\n */\n public getKeyBackupEnabled(): boolean | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.getKeyBackupEnabled();\n }\n\n /**\n * Enable backing up of keys, using data previously returned from\n * getKeyBackupVersion.\n *\n * @param info - Backup information object as returned by getKeyBackupVersion\n * @returns Promise which resolves when complete.\n *\n * @deprecated Do not call this directly. Instead call {@link Crypto.CryptoApi.checkKeyBackupAndEnable}.\n */\n public enableKeyBackup(info: IKeyBackupInfo): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.enableKeyBackup(info);\n }\n\n /**\n * Disable backing up of keys.\n *\n * @deprecated Not supported for Rust Cryptography. It should be unnecessary to disable key backup.\n */\n public disableKeyBackup(): void {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n this.crypto.backupManager.disableKeyBackup();\n }\n\n /**\n * Set up the data required to create a new backup version. The backup version\n * will not be created and enabled until createKeyBackupVersion is called.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n *\n * @returns Object that can be passed to createKeyBackupVersion and\n * additionally has a 'recovery_key' member with the user-facing recovery key string.\n *\n * @deprecated Not supported for Rust cryptography. Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}.\n */\n public async prepareKeyBackupVersion(\n password?: string | Uint8Array | null,\n opts: IKeyBackupPrepareOpts = { secureSecretStorage: false },\n ): Promise<Pick<IPreparedKeyBackupVersion, \"algorithm\" | \"auth_data\" | \"recovery_key\">> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // eslint-disable-next-line camelcase\n const { algorithm, auth_data, recovery_key, privateKey } =\n await this.crypto.backupManager.prepareKeyBackupVersion(password);\n\n if (opts.secureSecretStorage) {\n await this.secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n this.logger.info(\"Key backup private key stored in secret storage\");\n }\n\n return {\n algorithm,\n /* eslint-disable camelcase */\n auth_data,\n recovery_key,\n /* eslint-enable camelcase */\n };\n }\n\n /**\n * Check whether the key backup private key is stored in secret storage.\n * @returns map of key name to key info the secret is\n * encrypted with, or null if it is not present or not encrypted with a\n * trusted key\n */\n public isKeyBackupKeyStored(): Promise<Record<string, SecretStorageKeyDescription> | null> {\n return Promise.resolve(this.secretStorage.isStored(\"m.megolm_backup.v1\"));\n }\n\n /**\n * Create a new key backup version and enable it, using the information return\n * from prepareKeyBackupVersion.\n *\n * @param info - Info object from prepareKeyBackupVersion\n * @returns Object with 'version' param indicating the version created\n *\n * @deprecated Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}.\n */\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise<IKeyBackupInfo> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.createKeyBackupVersion(info);\n\n const data = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign the backup auth data with the device key for backwards compat with\n // older devices with cross-signing. This can probably go away very soon in\n // favour of just signing with the cross-singing master key.\n // XXX: Private member access\n await this.crypto.signObject(data.auth_data);\n\n if (\n this.cryptoCallbacks.getCrossSigningKey &&\n // XXX: Private member access\n this.crypto.crossSigningInfo.getId()\n ) {\n // now also sign the auth data with the cross-signing master key\n // we check for the callback explicitly here because we still want to be able\n // to create an un-cross-signed key backup if there is a cross-signing key but\n // no callback supplied.\n // XXX: Private member access\n await this.crypto.crossSigningInfo.signObject(data.auth_data, \"master\");\n }\n\n const res = await this.http.authedRequest<IKeyBackupInfo>(Method.Post, \"/room_keys/version\", undefined, data);\n\n // We could assume everything's okay and enable directly, but this ensures\n // we run the same signature verification that will be used for future\n // sessions.\n await this.checkKeyBackup();\n if (!this.getKeyBackupEnabled()) {\n this.logger.error(\"Key backup not usable even though we just created it\");\n }\n\n return res;\n }\n\n /**\n * @deprecated Use {@link Crypto.CryptoApi.deleteKeyBackupVersion | `CryptoApi.deleteKeyBackupVersion`}.\n */\n public async deleteKeyBackupVersion(version: string): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.cryptoBackend.deleteKeyBackupVersion(version);\n }\n\n private makeKeyBackupPath(roomId?: string, sessionId?: string, version?: string): IKeyBackupPath {\n let path: string;\n if (sessionId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId!,\n $sessionId: sessionId,\n });\n } else if (roomId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId\", {\n $roomId: roomId,\n });\n } else {\n path = \"/room_keys/keys\";\n }\n const queryData = version === undefined ? undefined : { version };\n return { path, queryData };\n }\n\n /**\n * Back up session keys to the homeserver.\n * @param roomId - ID of the room that the keys are for Optional.\n * @param sessionId - ID of the session that the keys are for Optional.\n * @param version - backup version Optional.\n * @param data - Object keys to send\n * @returns a promise that will resolve when the keys\n * are uploaded\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public sendKeyBackup(\n roomId: undefined,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public sendKeyBackup(\n roomId: string,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public sendKeyBackup(\n roomId: string,\n sessionId: string,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public async sendKeyBackup(\n roomId: string | undefined,\n sessionId: string | undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Put, path.path, path.queryData, data, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n *\n * @deprecated Not supported for Rust Cryptography. This is done automatically as part of\n * {@link CryptoApi.resetKeyBackup}, so there is probably no need to call this manually.\n */\n public async scheduleAllGroupSessionsForBackup(): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.scheduleAllGroupSessionsForBackup();\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n *\n * (This is done automatically as part of {@link CryptoApi.resetKeyBackup},\n * so there is probably no need to call this manually.)\n *\n * @returns Promise which resolves to the number of sessions requiring a backup.\n * @deprecated Not supported for Rust Cryptography.\n */\n public flagAllGroupSessionsForBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.flagAllGroupSessionsForBackup();\n }\n\n /**\n * Return true if recovery key is valid.\n * Try to decode the recovery key and check if it's successful.\n * @param recoveryKey\n * @deprecated Use {@link decodeRecoveryKey} directly\n */\n public isValidRecoveryKey(recoveryKey: string): boolean {\n try {\n decodeRecoveryKey(recoveryKey);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get the raw key for a key backup from the password\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @returns key backup key\n * @deprecated Deriving a backup key from a passphrase is not part of the matrix spec. Instead, a random key is generated and stored/shared via 4S.\n */\n public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise<Uint8Array> {\n return keyFromAuthData(backupInfo.auth_data, password);\n }\n\n /**\n * Get the raw key for a key backup from the recovery key\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param recoveryKey - The recovery key\n * @returns key backup key\n * @deprecated Use {@link decodeRecoveryKey} directly\n */\n public keyBackupKeyFromRecoveryKey(recoveryKey: string): Uint8Array {\n return decodeRecoveryKey(recoveryKey);\n }\n\n /**\n * Restore from an existing key backup via a passphrase.\n *\n * @param password - Passphrase\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `getKeyBackupVersion` or `checkKeyBackup`.`backupInfo`\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = await keyFromAuthData(backupInfo.auth_data, password);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via a private key stored in secret\n * storage.\n *\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithSecretStorage(\n backupInfo: IKeyBackupInfo,\n targetRoomId?: string,\n targetSessionId?: string,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const storedKey = await this.secretStorage.get(\"m.megolm_backup.v1\");\n\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const keys = await this.secretStorage.getKey();\n await this.secretStorage.store(\"m.megolm_backup.v1\", fixedKey, [keys![0]]);\n }\n\n const privKey = decodeBase64(fixedKey || storedKey!);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via an encoded recovery key.\n *\n * @param recoveryKey - Encoded recovery key\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param opts - Optional params such as callbacks\n\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = decodeRecoveryKey(recoveryKey);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via a private key stored locally\n * @param targetRoomId\n * @param targetSessionId\n * @param backupInfo\n * @param opts\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const privKey = await this.cryptoBackend.getSessionBackupPrivateKey();\n if (!privKey) {\n throw new Error(\"Couldn't get key\");\n }\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const cacheCompleteCallback = opts?.cacheCompleteCallback;\n const progressCallback = opts?.progressCallback;\n\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n if (!backupInfo.version) {\n throw new Error(\"Backup version must be defined\");\n }\n const backupVersion = backupInfo.version!;\n\n let totalKeyCount = 0;\n let totalFailures = 0;\n let totalImported = 0;\n\n const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupVersion);\n\n const backupDecryptor = await this.cryptoBackend.getBackupDecryptor(backupInfo, privKey);\n\n const untrusted = !backupDecryptor.sourceTrusted;\n\n try {\n if (!(privKey instanceof Uint8Array)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n throw new Error(`restoreKeyBackup expects Uint8Array, got ${privKey}`);\n }\n // Cache the key, if possible.\n // This is async.\n this.cryptoBackend\n .storeSessionBackupPrivateKey(privKey, backupVersion)\n .catch((e) => {\n this.logger.warn(\"Error caching session backup key:\", e);\n })\n .then(cacheCompleteCallback);\n\n if (progressCallback) {\n progressCallback({\n stage: \"fetch\",\n });\n }\n\n const res = await this.http.authedRequest<IRoomsKeysResponse | IRoomKeysResponse | IKeyBackupSession>(\n Method.Get,\n path.path,\n path.queryData,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n\n // We have finished fetching the backup, go to next step\n if (progressCallback) {\n progressCallback({\n stage: \"load_keys\",\n });\n }\n\n if ((res as IRoomsKeysResponse).rooms) {\n // We have a full backup here, it can get quite big, so we need to decrypt and import it in chunks.\n\n // Get the total count as a first pass\n totalKeyCount = this.getTotalKeyCount(res as IRoomsKeysResponse);\n // Now decrypt and import the keys in chunks\n await this.handleDecryptionOfAFullBackup(\n res as IRoomsKeysResponse,\n backupDecryptor,\n 200,\n async (chunk) => {\n // We have a chunk of decrypted keys: import them\n try {\n const backupVersion = backupInfo.version!;\n await this.cryptoBackend!.importBackedUpRoomKeys(chunk, backupVersion, {\n untrusted,\n });\n totalImported += chunk.length;\n } catch (e) {\n totalFailures += chunk.length;\n // We failed to import some keys, but we should still try to import the rest?\n // Log the error and continue\n logger.error(\"Error importing keys from backup\", e);\n }\n\n if (progressCallback) {\n progressCallback({\n total: totalKeyCount,\n successes: totalImported,\n stage: \"load_keys\",\n failures: totalFailures,\n });\n }\n },\n );\n } else if ((res as IRoomKeysResponse).sessions) {\n // For now we don't chunk for a single room backup, but we could in the future.\n // Currently it is not used by the application.\n const sessions = (res as IRoomKeysResponse).sessions;\n totalKeyCount = Object.keys(sessions).length;\n const keys = await backupDecryptor.decryptSessions(sessions);\n for (const k of keys) {\n k.room_id = targetRoomId!;\n }\n await this.cryptoBackend.importBackedUpRoomKeys(keys, backupVersion, {\n progressCallback,\n untrusted,\n });\n totalImported = keys.length;\n } else {\n totalKeyCount = 1;\n try {\n const [key] = await backupDecryptor.decryptSessions({\n [targetSessionId!]: res as IKeyBackupSession,\n });\n key.room_id = targetRoomId!;\n key.session_id = targetSessionId!;\n\n await this.cryptoBackend.importBackedUpRoomKeys([key], backupVersion, {\n progressCallback,\n untrusted,\n });\n totalImported = 1;\n } catch (e) {\n this.logger.debug(\"Failed to decrypt megolm session from backup\", e);\n }\n }\n } finally {\n backupDecryptor.free();\n }\n\n /// in case entering the passphrase would add a new signature?\n await this.cryptoBackend.checkKeyBackupAndEnable();\n\n return { total: totalKeyCount, imported: totalImported };\n }\n\n /**\n * This method calculates the total number of keys present in the response of a `/room_keys/keys` call.\n *\n * @param res - The response from the server containing the keys to be counted.\n *\n * @returns The total number of keys in the backup.\n */\n private getTotalKeyCount(res: IRoomsKeysResponse): number {\n const rooms = res.rooms;\n let totalKeyCount = 0;\n for (const roomData of Object.values(rooms)) {\n if (!roomData.sessions) continue;\n totalKeyCount += Object.keys(roomData.sessions).length;\n }\n return totalKeyCount;\n }\n\n /**\n * This method handles the decryption of a full backup, i.e a call to `/room_keys/keys`.\n * It will decrypt the keys in chunks and call the `block` callback for each chunk.\n *\n * @param res - The response from the server containing the keys to be decrypted.\n * @param backupDecryptor - An instance of the BackupDecryptor class used to decrypt the keys.\n * @param chunkSize - The size of the chunks to be processed at a time.\n * @param block - A callback function that is called for each chunk of keys.\n *\n * @returns A promise that resolves when the decryption is complete.\n */\n private async handleDecryptionOfAFullBackup(\n res: IRoomsKeysResponse,\n backupDecryptor: BackupDecryptor,\n chunkSize: number,\n block: (chunk: IMegolmSessionData[]) => Promise<void>,\n ): Promise<void> {\n const rooms = (res as IRoomsKeysResponse).rooms;\n\n let groupChunkCount = 0;\n let chunkGroupByRoom: Map<string, IKeyBackupRoomSessions> = new Map();\n\n const handleChunkCallback = async (roomChunks: Map<string, IKeyBackupRoomSessions>): Promise<void> => {\n const currentChunk: IMegolmSessionData[] = [];\n for (const roomId of roomChunks.keys()) {\n const decryptedSessions = await backupDecryptor.decryptSessions(roomChunks.get(roomId)!);\n for (const sessionId in decryptedSessions) {\n const k = decryptedSessions[sessionId];\n k.room_id = roomId;\n currentChunk.push(k);\n }\n }\n await block(currentChunk);\n };\n\n for (const [roomId, roomData] of Object.entries(rooms)) {\n if (!roomData.sessions) continue;\n\n chunkGroupByRoom.set(roomId, {});\n\n for (const [sessionId, session] of Object.entries(roomData.sessions)) {\n const sessionsForRoom = chunkGroupByRoom.get(roomId)!;\n sessionsForRoom[sessionId] = session;\n groupChunkCount += 1;\n if (groupChunkCount >= chunkSize) {\n // We have enough chunks to decrypt\n await handleChunkCallback(chunkGroupByRoom);\n chunkGroupByRoom = new Map();\n // There might be remaining keys for that room, so add back an entry for the current room.\n chunkGroupByRoom.set(roomId, {});\n groupChunkCount = 0;\n }\n }\n }\n\n // Handle remaining chunk if needed\n if (groupChunkCount > 0) {\n await handleChunkCallback(chunkGroupByRoom);\n }\n }\n\n public deleteKeysFromBackup(roomId: undefined, sessionId: undefined, version?: string): Promise<void>;\n public deleteKeysFromBackup(roomId: string, sessionId: undefined, version?: string): Promise<void>;\n public deleteKeysFromBackup(roomId: string, sessionId: string, version?: string): Promise<void>;\n public async deleteKeysFromBackup(roomId?: string, sessionId?: string, version?: string): Promise<void> {\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Delete, path.path, path.queryData, undefined, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Get the config for the media repository.\n * @returns Promise which resolves with an object containing the config.\n */\n public getMediaConfig(): Promise<IMediaConfig> {\n return this.http.authedRequest(Method.Get, \"/config\", undefined, undefined, {\n prefix: MediaPrefix.V3,\n });\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param roomId - The room ID\n * @returns The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string | undefined): Room | null {\n if (!roomId) {\n return null;\n }\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and\n * use it if found (MSC3946).\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(msc3946ProcessDynamicPredecessor = false): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const predecessor = r.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (predecessor) {\n replacedRooms.add(predecessor);\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param userId - The user ID to retrieve.\n * @returns A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User | null {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param eventType - The event type\n * @param content - the contents object for the event\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: IContent): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n return retryNetworkOperation(5, () => {\n return this.http.authedRequest(Method.Put, path, undefined, content);\n });\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param eventType - The event type\n * @returns The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent | undefined {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param eventType - The event type\n * @returns Promise which resolves: The contents of the given account data event.\n * @returns Rejects: with an error response.\n */\n public async getAccountDataFromServer<T extends { [k: string]: any }>(eventType: string): Promise<T | null> {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent<T>();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(Method.Get, path);\n } catch (e) {\n if ((<MatrixError>e).data?.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw e;\n }\n }\n\n public async deleteAccountData(eventType: string): Promise<void> {\n const msc3391DeleteAccountDataServerSupport = this.canSupport.get(Feature.AccountDataDeletion);\n // if deletion is not supported overwrite with empty content\n if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n await this.setAccountData(eventType, {});\n return;\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.getSafeUserId(),\n $type: eventType,\n });\n const options =\n msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable\n ? { prefix: \"/_matrix/client/unstable/org.matrix.msc3391\" }\n : undefined;\n return await this.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param userIds - the user IDs to ignore\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[]): Promise<{}> {\n const content = { ignored_users: {} as Record<string, object> };\n userIds.forEach((u) => {\n content.ignored_users[u] = {};\n });\n return this.setAccountData(\"m.ignored_user_list\", content);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param userId - the user ID to check\n * @returns true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to join.\n * @param opts - Options when joining the room.\n * @returns Promise which resolves: Room object.\n * @returns Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts: IJoinRoomOpts = {}): Promise<Room> {\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return room;\n\n let signPromise: Promise<IThirdPartySigned | void> = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n const url = new URL(opts.inviteSignUrl);\n url.searchParams.set(\"mxid\", this.credentials.userId!);\n signPromise = this.http.requestOtherUrl<IThirdPartySigned>(Method.Post, url);\n }\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const data: IJoinRequestBody = {};\n const signedInviteObj = await signPromise;\n if (signedInviteObj) {\n data.third_party_signed = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryParams, data);\n\n const roomId = res.room_id;\n // In case we were originally given an alias, check the room cache again\n // with the resolved ID - this method is supposed to no-op if we already\n // were in the room, after all.\n const resolvedRoom = this.getRoom(roomId);\n if (resolvedRoom?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return resolvedRoom;\n\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n const syncRoom = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n return syncRoom;\n }\n\n /**\n * Knock a room. If you have already knocked the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to knock.\n * @param opts - Options when knocking the room.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public knockRoom(roomIdOrAlias: string, opts: KnockRoomOpts = {}): Promise<{ room_id: string }> {\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Knock)) {\n return Promise.resolve({ room_id: room.roomId });\n }\n\n const path = utils.encodeUri(\"/knock/$roomIdOrAlias\", { $roomIdOrAlias: roomIdOrAlias });\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const body: Record<string, string> = {};\n if (opts.reason) {\n body.reason = opts.reason;\n }\n\n return this.http.authedRequest(Method.Post, path, queryParams, body);\n }\n\n /**\n * Resend an event. Will also retry any to-device messages waiting to be sent.\n * @param event - The event to resend.\n * @param room - Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise<ISendEventResponse> {\n // also kick the to-device queue to retry\n this.toDeviceMessageQueue.sendQueue();\n\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param event - Event to cancel\n * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n */\n public cancelPendingEvent(event: MatrixEvent): void {\n if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status!)) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // If the event is currently being encrypted then remove it from the pending list, to indicate that it should\n // not be sent.\n if (event.status === EventStatus.ENCRYPTING) {\n this.eventsBeingEncrypted.delete(event.getId()!);\n } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n // tell the scheduler to forget about it, if it's queued\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, EventType.RoomName, { name: name });\n }\n\n /**\n * @param htmlTopic - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, htmlTopic?: string): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n }\n\n /**\n * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n * @returns Rejects: with an error response.\n */\n public getRoomTags(roomId: string): Promise<ITagsResponse> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param tagName - name of room tag to be set\n * @param metadata - associated with that tag to be stored\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: ITagMetadata = {}): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Put, path, undefined, metadata);\n }\n\n /**\n * @param tagName - name of room tag to be removed\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * @param eventType - event type to be set\n * @param content - event content\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: Record<string, any>): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Set a power level to one or multiple users.\n * Will apply changes atop of current power level event from local state if running & synced, falling back\n * to fetching latest from the `/state/` API.\n * @param roomId - the room to update power levels in\n * @param userId - the ID of the user or users to update power levels of\n * @param powerLevel - the numeric power level to update given users to\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public async setPowerLevel(\n roomId: string,\n userId: string | string[],\n powerLevel: number | undefined,\n ): Promise<ISendEventResponse> {\n let content: IPowerLevelsContent | undefined;\n if (this.clientRunning && this.isInitialSyncComplete()) {\n content = this.getRoom(roomId)?.currentState?.getStateEvents(EventType.RoomPowerLevels, \"\")?.getContent();\n }\n if (!content) {\n try {\n content = await this.getStateEvent(roomId, EventType.RoomPowerLevels, \"\");\n } catch (e) {\n // It is possible for a Matrix room to not have a power levels event\n if (e instanceof MatrixError && e.errcode === \"M_NOT_FOUND\") {\n content = {};\n } else {\n throw e;\n }\n }\n }\n\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(content);\n\n if (!content?.users) {\n content.users = {};\n }\n const users = Array.isArray(userId) ? userId : [userId];\n for (const user of users) {\n if (powerLevel == null) {\n delete content.users[user];\n } else {\n content.users[user] = powerLevel;\n }\n }\n\n return this.sendStateEvent(roomId, EventType.RoomPowerLevels, content, \"\");\n }\n\n /**\n * Create an m.beacon_info event\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_createLiveBeacon(\n roomId: Room[\"roomId\"],\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.unstable_setLiveBeacon(roomId, beaconInfoContent);\n }\n\n /**\n * Upsert a live beacon event\n * using a specific m.beacon_info.* event variable type\n * @param roomId - string\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_setLiveBeacon(\n roomId: string,\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, this.getUserId()!);\n }\n\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent(\n roomId: string,\n threadIdOrEventType: string | null,\n eventTypeOrContent: string | IContent,\n contentOrTxnId?: IContent | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse> {\n let threadId: string | null;\n let eventType: string;\n let content: IContent;\n let txnId: string | undefined;\n if (!threadIdOrEventType?.startsWith(EVENT_ID_PREFIX) && threadIdOrEventType !== null) {\n txnId = contentOrTxnId as string;\n content = eventTypeOrContent as IContent;\n eventType = threadIdOrEventType;\n threadId = null;\n } else {\n txnId = txnIdOrVoid;\n content = contentOrTxnId as IContent;\n eventType = eventTypeOrContent as string;\n threadId = threadIdOrEventType;\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId);\n }\n\n /**\n * If we expect that an event is part of a thread but is missing the relation\n * we need to add it manually, as well as the reply fallback\n */\n private addThreadRelationIfNeeded(content: IContent, threadId: string | null, roomId: string): void {\n if (threadId && !content[\"m.relates_to\"]?.rel_type) {\n const isReply = !!content[\"m.relates_to\"]?.[\"m.in_reply_to\"];\n content[\"m.relates_to\"] = {\n ...content[\"m.relates_to\"],\n rel_type: THREAD_RELATION_TYPE.name,\n event_id: threadId,\n // Set is_falling_back to true unless this is actually intended to be a reply\n is_falling_back: !isReply,\n };\n const thread = this.getRoom(roomId)?.getThread(threadId);\n if (thread && !isReply) {\n content[\"m.relates_to\"][\"m.in_reply_to\"] = {\n event_id:\n thread\n .lastReply((ev: MatrixEvent) => {\n return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n })\n ?.getId() ?? threadId,\n };\n }\n }\n }\n\n /**\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n /**\n * Sends a delayed event (MSC4140).\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param delayOpts - Properties of the delay for this event.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOpts: SendDelayedEventRequestOpts,\n txnId?: string,\n ): Promise<SendDelayedEventResponse>;\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOptsOrTxnId?: SendDelayedEventRequestOpts | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n let txnId: string | undefined;\n if (typeof delayOptsOrTxnId === \"string\") {\n txnId = delayOptsOrTxnId;\n } else {\n delayOpts = delayOptsOrTxnId;\n txnId = txnIdOrVoid;\n }\n\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // We always construct a MatrixEvent when sending because the store and scheduler use them.\n // We'll extract the params back out if it turns out the client has no scheduler or store.\n const localEvent = new MatrixEvent(\n Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }),\n );\n\n const room = this.getRoom(roomId);\n const thread = threadId ? room?.getThread(threadId) : undefined;\n if (thread) {\n localEvent.setThread(thread);\n }\n\n if (!delayOpts) {\n // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n }\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId?.startsWith(\"~\")) {\n const target = room?.getPendingEvents().find((e) => e.getId() === targetId);\n target?.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n localEvent.updateAssociatedId(target.getId()!);\n });\n }\n\n const type = localEvent.getType();\n this.logger.debug(\n `sendEvent of type ${type} in ${roomId} with txnId ${txnId}${delayOpts ? \" (delayed event)\" : \"\"}`,\n );\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // TODO: separate store for delayed events?\n if (!delayOpts) {\n // add this event immediately to the local store as 'sending'.\n room?.addPendingEvent(localEvent, txnId);\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent);\n } else {\n return this.encryptAndSendEvent(room, localEvent, delayOpts);\n }\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @returns returns a promise which resolves with the result of the send request\n */\n protected async encryptAndSendEvent(room: Room | null, event: MatrixEvent): Promise<ISendEventResponse>;\n /**\n * Simply sends a delayed event without encrypting it.\n * TODO: Allow encrypted delayed events, and encrypt them properly\n * @param delayOpts - Properties of the delay for this event.\n * @returns returns a promise which resolves with the result of the delayed send request\n */\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n if (delayOpts) {\n return this.sendEventHttpRequest(event, delayOpts);\n }\n\n try {\n let cancelled: boolean;\n this.eventsBeingEncrypted.add(event.getId()!);\n try {\n await this.encryptEventIfNeeded(event, room ?? undefined);\n } finally {\n cancelled = !this.eventsBeingEncrypted.delete(event.getId()!);\n }\n\n if (cancelled) {\n // cancelled via MatrixClient::cancelPendingEvent\n return {} as ISendEventResponse;\n }\n\n // encryptEventIfNeeded may have updated the status from SENDING to ENCRYPTING. If so, we need\n // to put it back.\n if (event.status === EventStatus.ENCRYPTING) {\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n }\n\n let promise: Promise<ISendEventResponse> | null = null;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event)!.length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then((res) => {\n room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n return res;\n });\n }\n }\n\n return await promise;\n } catch (err) {\n this.logger.error(\"Error sending event\", err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = <MatrixError>err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n } catch (e) {\n this.logger.error(\"Exception in error handler!\", e);\n }\n if (err instanceof MatrixError) {\n err.event = event;\n }\n throw err;\n }\n }\n\n private async encryptEventIfNeeded(event: MatrixEvent, room?: Room): Promise<void> {\n // If the room is unknown, we cannot encrypt for it\n if (!room) return;\n\n if (!(await this.shouldEncryptEventForRoom(event, room))) return;\n\n if (!this.cryptoBackend && this.usingExternalCrypto) {\n // The client has opted to allow sending messages to encrypted\n // rooms even if the room is encrypted, and we haven't set up\n // crypto. This is useful for users of matrix-org/pantalaimon\n return;\n }\n\n if (!this.cryptoBackend) {\n throw new Error(\"This room is configured to use encryption, but your client does not support encryption.\");\n }\n\n this.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);\n await this.cryptoBackend.encryptEvent(event, room);\n }\n\n /**\n * Determine whether a given event should be encrypted when we send it to the given room.\n *\n * This takes into account event type and room configuration.\n */\n private async shouldEncryptEventForRoom(event: MatrixEvent, room: Room): Promise<boolean> {\n if (event.isEncrypted()) {\n // this event has already been encrypted; this happens if the\n // encryption step succeeded, but the send step failed on the first\n // attempt.\n return false;\n }\n\n if (event.getType() === EventType.Reaction) {\n // For reactions, there is a very little gained by encrypting the entire\n // event, as relation data is already kept in the clear. Event\n // encryption for a reaction effectively only obscures the event type,\n // but the purpose is still obvious from the relation data, so nothing\n // is really gained. It also causes quite a few problems, such as:\n // * triggers notifications via default push rules\n // * prevents server-side bundling for reactions\n // The reaction key / content / emoji value does warrant encrypting, but\n // this will be handled separately by encrypting just this value.\n // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642\n return false;\n }\n\n if (event.isRedaction()) {\n // Redactions do not support encryption in the spec at this time.\n // Whilst it mostly worked in some clients, it wasn't compliant.\n return false;\n }\n\n // If the room has an m.room.encryption event, we should encrypt.\n if (room.hasEncryptionStateEvent()) return true;\n\n // If we have a crypto impl, and *it* thinks we should encrypt, then we should.\n if (await this.cryptoBackend?.isEncryptionEnabledInRoom(room.roomId)) return true;\n\n // Otherwise, no need to encrypt.\n return false;\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param roomId - the room for the events `eventType` relates to\n * @param eventType - the event type\n * @returns the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(\n roomId: string,\n eventType?: EventType | string | null,\n ): EventType | string | null | undefined {\n if (eventType === EventType.Reaction) return eventType;\n return this.getRoom(roomId)?.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;\n }\n\n protected updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus): void {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise<ISendEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId()!,\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey()!,\n $txnId: txnId,\n };\n\n let path: string;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey()!.length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction() && event.event.redacts) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, {\n $redactsEventId: event.event.redacts,\n ...pathParams,\n });\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n const content = event.getWireContent();\n if (!delayOpts) {\n return this.http.authedRequest<ISendEventResponse>(Method.Put, path, undefined, content).then((res) => {\n this.logger.debug(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n } else {\n return this.http.authedRequest<SendDelayedEventResponse>(\n Method.Put,\n path,\n getUnstableDelayQueryOpts(delayOpts),\n content,\n );\n }\n }\n\n /**\n * @param txnId - transaction id. One will be made up if not supplied.\n * @param opts - Redact options\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.\n * Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId?: string,\n txnId?: string | IRedactOpts,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse> {\n if (!eventId?.startsWith(EVENT_ID_PREFIX)) {\n opts = txnId as IRedactOpts;\n txnId = eventId;\n eventId = threadId!;\n threadId = null;\n }\n const reason = opts?.reason;\n const content: IContent = { reason };\n\n if (opts?.with_rel_types !== undefined) {\n if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) {\n throw new Error(\n \"Server does not support relation based redactions \" +\n `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`,\n );\n }\n\n const withRelTypesPropName =\n this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable\n ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable!\n : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable!;\n\n content[withRelTypesPropName] = opts.with_rel_types;\n }\n\n return this.sendCompleteEvent(\n roomId,\n threadId,\n {\n type: EventType.RoomRedaction,\n content,\n redacts: eventId,\n },\n txnId as string,\n );\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: RoomMessageEventContent, txnId?: string): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null,\n content: RoomMessageEventContent,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null | RoomMessageEventContent,\n content?: RoomMessageEventContent | string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (typeof threadId !== \"string\" && threadId !== null) {\n txnId = content as string;\n content = threadId as RoomMessageEventContent;\n threadId = null;\n }\n\n const eventType = EventType.RoomMessage;\n const sendContent = content as RoomMessageEventContent;\n\n return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns\n * @returns Rejects: with an error response.\n */\n public sendTextMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendEmoteMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendImageMessage(roomId: string, url: string, info?: ImageInfo, text?: string): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Image\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Image\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n msgtype: MsgType.Image,\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies RoomMessageEventContent;\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Sticker\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Sticker\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies StickerEventContent;\n\n return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlMessage(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlNotice(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlEmote(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * Send a delayed timeline event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedEvent<K extends keyof TimelineEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, delayOpts, txnId);\n }\n\n /**\n * Send a delayed state event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content as Body, opts);\n }\n\n /**\n * Get all pending delayed events for the calling user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_getDelayedEvents(fromToken?: string): Promise<DelayedEventInfo> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const queryDict = fromToken ? { from: fromToken } : undefined;\n return await this.http.authedRequest(Method.Get, \"/delayed_events\", queryDict, undefined, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Manage a delayed event associated with the given delay_id.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<{}> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const path = utils.encodeUri(\"/delayed_events/$delayId\", {\n $delayId: delayId,\n });\n const data = {\n action,\n };\n return await this.http.authedRequest(Method.Post, path, undefined, data, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Send a receipt.\n * @param event - The event being acknowledged\n * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n * ReceiptType.Read are experimental!\n * @param body - Additional content to send alongside the receipt.\n * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReceipt(\n event: MatrixEvent,\n receiptType: ReceiptType,\n body?: Record<string, any>,\n unthreaded = false,\n ): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId()!,\n $receiptType: receiptType,\n $eventId: event.getId()!,\n });\n\n // Unless we're explicitly making an unthreaded receipt or we don't\n // support threads, include the `thread_id` property in the body.\n const shouldAddThreadId = !unthreaded && this.supportsThreads();\n const fullBody = shouldAddThreadId ? { ...body, thread_id: threadIdForReceipt(event) } : body;\n\n const promise = this.http.authedRequest<{}>(Method.Post, path, undefined, fullBody || {});\n\n const room = this.getRoom(event.getRoomId());\n if (room && this.credentials.userId) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType, unthreaded);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param event - The event that has been read.\n * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReadReceipt(\n event: MatrixEvent | null,\n receiptType = ReceiptType.Read,\n unthreaded = false,\n ): Promise<{} | undefined> {\n if (!event) return;\n const eventId = event.getId()!;\n const room = this.getRoom(event.getRoomId());\n if (room?.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n return this.sendReceipt(event, receiptType, {}, unthreaded);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEvent - the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param rpEvent - the m.read.private read receipt event for when we don't\n * want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent?: MatrixEvent,\n rpEvent?: MatrixEvent,\n ): Promise<{}> {\n const room = this.getRoom(roomId);\n if (room?.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId: string | undefined;\n if (rrEvent) {\n rrEventId = rrEvent.getId()!;\n if (room?.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rrEvent, ReceiptType.Read);\n }\n\n // Add the optional private RR update, do local echo like `sendReceipt`\n let rpEventId: string | undefined;\n if (rpEvent) {\n rpEventId = rpEvent.getId()!;\n if (room?.hasPendingEvent(rpEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rpEvent, ReceiptType.ReadPrivate);\n }\n\n return await this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param url - The URL to get preview data for\n * @param ts - The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @returns Promise which resolves: Object of OG metadata.\n * @returns Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number): Promise<IPreviewUrlResponse> {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n if (key in this.urlPreviewCache) {\n return this.urlPreviewCache[key];\n }\n\n const resp = this.http.authedRequest<IPreviewUrlResponse>(\n Method.Get,\n \"/preview_url\",\n {\n url,\n ts: ts.toString(),\n },\n undefined,\n {\n prefix: MediaPrefix.V3,\n priority: \"low\",\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.getUserId()!,\n });\n const data: QueryDict = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param roomId - The room ID to search from\n * @param verifyLinks - If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @param msc3946ProcessDynamicPredecessor - if true, look for\n * m.room.predecessor state events as well as create events, and prefer\n * predecessor events where they exist (MSC3946).\n * @returns An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(\n roomId: string,\n verifyLinks = false,\n msc3946ProcessDynamicPredecessor = false,\n ): Room[] {\n const currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n\n return [...before, currentRoom, ...after];\n }\n\n private findPredecessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n const seenRoomIDs = new Set<string>([room.roomId]);\n\n // Work backwards from newer to older rooms\n let predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n while (predecessorRoomId !== null) {\n if (predecessorRoomId) {\n if (seenRoomIDs.has(predecessorRoomId)) break;\n seenRoomIDs.add(predecessorRoomId);\n }\n const predecessorRoom = this.getRoom(predecessorRoomId);\n if (predecessorRoom === null) {\n break;\n }\n if (verifyLinks) {\n const tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n ret.splice(0, 0, predecessorRoom);\n\n room = predecessorRoom;\n predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n }\n return ret;\n }\n\n private findSuccessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work forwards, looking at tombstone events\n let tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n while (tombstoneEvent) {\n const successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n if (!successorRoom) break; // end of the chain\n if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n if (verifyLinks) {\n const predecessorRoomId = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n break;\n }\n }\n\n // Push to the end because we're looking forwards\n ret.push(successorRoom);\n const roomIds = new Set(ret.map((ref) => ref.roomId));\n if (roomIds.size < ret.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return ret.slice(0, ret.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n room = successorRoom;\n tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n }\n return ret;\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Invite, reason);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param roomId - The room to invite the user to.\n * @param email - The email address to invite.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param roomId - The room to invite the user to.\n * @param medium - The medium to invite the user e.g. \"email\".\n * @param address - The address for the specified medium.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/invite\", { $roomId: roomId });\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(\n new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }),\n );\n }\n const params: Record<string, string> = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params[\"id_access_token\"] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, params);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public leave(roomId: string): Promise<{}> {\n return this.membershipChange(roomId, undefined, KnownMembership.Leave);\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param roomId - The room ID to start leaving at\n * @param includeFuture - If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @returns Promise which resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults: { [roomId: string]: Error } = {};\n const promises: Promise<unknown>[] = [];\n\n const doLeave = (roomId: string): Promise<void> => {\n return this.leave(roomId)\n .then(() => {\n delete populationResults[roomId];\n })\n .catch((err) => {\n // suppress error\n populationResults[roomId] = err;\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);\n }\n\n /**\n * @param deleteRoom - True to delete the room from the store on success.\n * Default: true.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async forget(roomId: string, deleteRoom = true): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/forget\", {\n $room_id: roomId,\n });\n const response = await this.http.authedRequest<{}>(Method.Post, path);\n if (deleteRoom) {\n this.store.removeRoom(roomId);\n this.emit(ClientEvent.DeleteRoom, roomId);\n }\n return response;\n }\n\n /**\n * @returns Promise which resolves: Object (currently empty)\n * @returns Rejects: with an error response.\n */\n public unban(roomId: string, userId: string): Promise<{}> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n reason: reason,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n private membershipChange(\n roomId: string,\n userId: string | undefined,\n membership: Membership,\n reason?: string,\n ): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(Method.Post, path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n });\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent, forceRecalculate = false): IActionsObject | null {\n if (!event.getPushActions() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushActions();\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushDetailsForEvent(event: MatrixEvent, forceRecalculate = false): PushDetails | null {\n if (!event.getPushDetails() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushDetails();\n }\n\n /**\n * @param info - The kind of info to set (e.g. 'avatar_url')\n * @param data - The JSON object to set.\n * @returns\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setProfileInfo(info: \"avatar_url\", data: { avatar_url: string }): Promise<{}>;\n public setProfileInfo(info: \"displayname\", data: { displayname: string }): Promise<{}>;\n public setProfileInfo(info: \"avatar_url\" | \"displayname\", data: object): Promise<{}> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId!,\n $info: info,\n });\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setDisplayName(name: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"displayname\", { displayname: name });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.displayName = name;\n user.emit(UserEvent.DisplayName, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setAvatarUrl(url: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"avatar_url\", { avatar_url: url });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.avatarUrl = url;\n user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n * may change.</strong>\n * @param mxcUrl - The MXC URL\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @returns the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n ): string | null {\n return getHttpUriForMxc(\n this.baseUrl,\n mxcUrl,\n width,\n height,\n resizeMethod,\n allowDirectLinks,\n allowRedirects,\n useAuthentication,\n );\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * This has an advantage over calls to the PUT /presence API in that it\n * doesn't clobber status_msg set by other devices.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public async setSyncPresence(presence?: SetPresence): Promise<void> {\n this.syncApi?.setPresence(presence);\n }\n\n /**\n * @param opts - Options to apply\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public async setPresence(opts: IPresenceOpts): Promise<void> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId!,\n });\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n await this.http.authedRequest(Method.Put, path, undefined, opts);\n }\n\n /**\n * @param userId - The user to get presence for\n * @returns Promise which resolves: The presence state for this user.\n * @returns Rejects: with an error response.\n */\n public getPresence(userId: string): Promise<IStatusResponse> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param room - The room to get older messages in.\n * @param limit - Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @returns Promise which resolves: Room. If you are at the beginning\n * of the timeline, `Room.oldState.paginationToken` will be\n * `null`.\n * @returns Rejects: with an error response.\n */\n public scrollback(room: Room, limit = 30): Promise<Room> {\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const promise = new Promise<Room>((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs)\n .then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n Direction.Backward,\n );\n })\n .then((res: IMessagesResponse) => {\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] =\n room.partitionThreadedEvents(matrixEvents);\n\n this.processAggregatedTimelineEvents(room, timelineEvents);\n room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline());\n this.processThreadEvents(room, threadedEvents, true);\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n room.oldState.paginationToken = res.end ?? null;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end ?? null, true);\n delete this.ongoingScrollbacks[room.roomId];\n resolve(room);\n })\n .catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n reject(err);\n });\n });\n\n info = { promise };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return promise;\n }\n\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n * <p>If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n * If the event does not belong to this EventTimelineSet then undefined will be returned.\n *\n * @param timelineSet - The timelineSet to look for the event in, must be bound to a room\n * @param eventId - The ID of the event to look for\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} including the given event\n */\n public async getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet?.room) {\n throw new Error(\"getEventTimeline only supports room timelines\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n if (timelineSet.thread && this.supportsThreads()) {\n return this.getThreadTimeline(timelineSet, eventId);\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n let params: Record<string, string | string[]> | undefined = undefined;\n if (this.clientOpts?.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n return undefined;\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...res.events_after.reverse().map(mapper),\n event,\n ...res.events_before.map(mapper),\n ];\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(events[0].getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n timeline.getState(EventTimeline.FORWARDS)!.paginationToken = res.end;\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);\n timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start);\n // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n this.processThreadEvents(timelineSet.room, threadedEvents, true);\n this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n unknownRelations.forEach((event) => timelineSet.relations.aggregateChildEvent(event));\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return (\n timelineSet.getTimelineForEvent(eventId) ??\n timelineSet.room.findThreadForEvent(event)?.liveTimeline ?? // for Threads degraded support\n timeline\n );\n }\n\n public async getThreadTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<EventTimeline | undefined> {\n if (!this.supportsThreads()) {\n throw new Error(\"could not get thread timeline: no client support\");\n }\n\n if (!timelineSet.room) {\n throw new Error(\"could not get thread timeline: not a room timeline\");\n }\n\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n const params: Record<string, string | string[]> = {\n limit: \"0\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n\n if (!timelineSet.canContain(event)) {\n return undefined;\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n if (Thread.hasServerSideSupport) {\n if (Thread.hasServerSideFwdPaginationSupport) {\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const thread = timelineSet.thread;\n const resOlder: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Forward, from: res.end, recurse: recurse || undefined },\n );\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper),\n event,\n ...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper),\n ];\n\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(event.getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n }\n\n timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(resNewer.next_batch ?? null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) ?? timeline;\n } else {\n // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n // functions contiguously, so we have to jump through some hoops to get our target event in it.\n // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n const thread = timelineSet.thread;\n\n const resOlder = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const eventsNewer: IEvent[] = [];\n let nextBatch: Optional<string> = res.end;\n while (nextBatch) {\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: nextBatch, recurse: recurse || undefined },\n );\n nextBatch = resNewer.next_batch ?? null;\n eventsNewer.push(...resNewer.chunk);\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...eventsNewer.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread\n // summaries.\n const timeline = timelineSet.getLiveTimeline();\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n\n timelineSet.addEventsToTimeline(events, true, timeline, null);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n return timeline;\n }\n }\n }\n\n /**\n * Get an EventTimeline for the latest events in the room. This will just\n * call `/messages` to get the latest message in the room, then use\n * `client.getEventTimeline(...)` to construct a new timeline from it.\n *\n * @param timelineSet - The timelineSet to find or add the timeline to\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} timeline with the latest events in the room\n */\n public async getLatestTimeline(timelineSet: EventTimelineSet): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet.room) {\n throw new Error(\"getLatestTimeline only supports room timelines\");\n }\n\n let event: IRoomEvent | undefined;\n if (timelineSet.threadListType !== null) {\n const res = await this.createThreadListMessagesRequest(\n timelineSet.room.roomId,\n null,\n 1,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n event = res.chunk?.[0];\n } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n const res = await this.fetchRelations(\n timelineSet.room.roomId,\n timelineSet.thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, limit: 1, recurse: recurse || undefined },\n );\n event = res.chunk?.[0];\n } else {\n const messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n $roomId: timelineSet.room.roomId,\n });\n\n const params: Record<string, string | string[]> = {\n dir: \"b\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n const res = await this.http.authedRequest<IMessagesResponse>(Method.Get, messagesPath, params);\n event = res.chunk?.[0];\n }\n if (!event) {\n throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n }\n\n return this.getEventTimeline(timelineSet, event.event_id);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir: Direction,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/messages\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter | null = null;\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used by room.fetchRoomThreads\n public createThreadListMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir = Direction.Backward,\n threadListType: ThreadFilterType | null = ThreadFilterType.All,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/threads\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n include: threadFilterTypeToFilter(threadListType),\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter = {};\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = {\n ...Filter.LAZY_LOADING_MESSAGES_FILTER,\n };\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = {\n ...filter,\n ...timelineFilter.getRoomTimelineFilterComponent()?.toJSON(),\n };\n }\n if (Object.keys(filter).length) {\n params.filter = JSON.stringify(filter);\n }\n\n const opts = {\n prefix:\n Thread.hasServerSideListSupport === FeatureSupport.Stable\n ? ClientPrefix.V1\n : \"/_matrix/client/unstable/org.matrix.msc3856\",\n };\n\n return this.http\n .authedRequest<IThreadedMessagesResponse>(Method.Get, path, params, undefined, opts)\n .then((res) => ({\n ...res,\n chunk: res.chunk?.reverse(),\n start: res.prev_batch,\n end: res.next_batch,\n }));\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param eventTimeline - timeline object to be updated\n *\n * @returns Promise which resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise<boolean> {\n const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n const room = this.getRoom(eventTimeline.getRoomId()!);\n const threadListType = eventTimeline.getTimelineSet().threadListType;\n const thread = eventTimeline.getTimelineSet().thread;\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path: string;\n let params: Record<string, string>;\n let promise: Promise<boolean>;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: (opts.limit ?? 30).toString(),\n only: \"highlight\",\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http\n .authedRequest<INotificationsResponse>(Method.Get, path, params)\n .then(async (res) => {\n const token = res.next_token;\n const matrixEvents: MatrixEvent[] = [];\n\n res.notifications = res.notifications.filter(noUnsafeEventProps);\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n\n // @TODO(kerrya) reprocessing every notification is ugly\n // remove if we get server MSC3994 support\n this.getPushDetailsForEvent(event, true);\n\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n // No need to partition events for threads here, everything lives\n // in the notification timeline set\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(res.next_token);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (threadListType !== null) {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n }\n\n promise = this.createThreadListMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n threadListType,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, matrixEvents);\n this.processThreadRoots(room, matrixEvents, backwards);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end !== res.start;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (thread) {\n const room = this.getRoom(eventTimeline.getRoomId() ?? undefined);\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n promise = this.fetchRelations(eventTimeline.getRoomId() ?? \"\", thread.id, null, null, {\n dir,\n limit: opts.limit,\n from: token ?? undefined,\n recurse: recurse || undefined,\n })\n .then(async (res) => {\n const mapper = this.getEventMapper();\n const matrixEvents = res.chunk\n .filter(noUnsafeEventProps)\n .filter(getRelationsThreadFilter(thread.id))\n .map(mapper);\n\n // Process latest events first\n for (const event of matrixEvents.slice().reverse()) {\n await thread?.processEvent(event);\n const sender = event.getSender()!;\n if (!backwards || thread?.getEventReadUpTo(sender) === null) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n }\n\n const newToken = res.next_batch;\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken ?? null);\n if (!newToken && backwards) {\n const originalEvent =\n thread.rootEvent ??\n mapper(await this.fetchRoomEvent(eventTimeline.getRoomId() ?? \"\", thread.id));\n timelineSet.addEventsToTimeline([originalEvent], true, eventTimeline, null);\n }\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !newToken) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(newToken);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n const [timelineEvents, , unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, timelineEvents);\n this.processThreadRoots(\n room,\n timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)),\n false,\n );\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n const atEnd = res.end === undefined || res.end === res.start;\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && atEnd) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return !atEnd;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet(): void {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param roomId - The room to attempt to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns Promise which resolves: Room object\n * @returns Rejects: with an error response.\n */\n public peekInRoom(roomId: string, limit: number = 20): Promise<Room> {\n this.peekSync?.stopPeeking();\n this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n return this.peekSync.peek(roomId, limit);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking(): void {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param roomId - The room to configure guest access in.\n * @param opts - Options\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise<void> {\n const writePromise = this.sendStateEvent(\n roomId,\n EventType.RoomGuestAccess,\n {\n guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden,\n },\n \"\",\n );\n\n let readPromise: Promise<unknown> = Promise.resolve();\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(\n roomId,\n EventType.RoomHistoryVisibility,\n {\n history_visibility: HistoryVisibility.WorldReadable,\n },\n \"\",\n );\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international format\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the homeserver).\n *\n * requestEmailToken calls the equivalent API directly on the identity server,\n * therefore bypassing the password reset specific logic.\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param endpoint - The endpoint to send the request to\n * @param params - Parameters for the POST request\n * @returns Promise which resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint<T extends IRequestTokenResponse>(\n endpoint: string,\n params: QueryDict,\n ): Promise<T> {\n const postParams = Object.assign({}, params);\n\n return this.http.request(Method.Post, endpoint, undefined, postParams);\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @returns the rule or undefined.\n */\n public getRoomPushRule(scope: \"global\" | \"device\", roomId: string): IPushRule | undefined {\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n return this.pushRules[scope]?.room?.find((rule) => rule.rule_id === roomId);\n } else {\n throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @param mute - the mute state.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: \"global\" | \"device\", roomId: string, mute: boolean): Promise<void> | undefined {\n let promise: Promise<unknown> | undefined;\n let hasDontNotifyRule = false;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule?.actions.includes(PushRuleActionName.DontNotify)) {\n hasDontNotifyRule = true;\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule!.rule_id);\n }\n } else {\n if (!roomPushRule) {\n promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n const deferred = utils.defer();\n this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n })\n .then(() => {\n deferred.resolve();\n })\n .catch((err) => {\n deferred.reject(err);\n });\n })\n .catch((err) => {\n deferred.reject(err);\n });\n\n promise = deferred.promise;\n }\n }\n\n if (promise) {\n return new Promise<void>((resolve, reject) => {\n // Update this.pushRules when the operation completes\n promise!\n .then(() => {\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n resolve();\n })\n .catch((err) => {\n reject(err);\n });\n })\n .catch((err: Error) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modified from another client\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n reject(err);\n })\n .catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts): Promise<ISearchResponse> {\n const roomEvents: ISearchRequestBody[\"search_categories\"][\"room_events\"] = {\n search_term: opts.query,\n };\n\n if (\"keys\" in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n });\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * count: estimate of the number of results\n * * next_batch: token for back-pagination; if undefined, there are no more results\n * * highlights: a list of words to highlight from the stemming algorithm\n * * results: a list of results\n *\n * Each entry in the results list is a SearchResult.\n *\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise<ISearchResults> {\n // TODO: support search groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: SearchOrderBy.Recent,\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults: ISearchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then((res) => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param searchResults - the results object to be updated\n * @returns Promise which resolves: updated result object\n * @returns Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch<T extends ISearchResults>(searchResults: T): Promise<T> {\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest as Promise<T>;\n }\n\n const searchOpts = {\n body: searchResults._query!,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts, searchResults.abortSignal)\n .then((res) => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = undefined;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @returns searchResults\n * @internal\n */\n // XXX: Intended private, used in code\n public processRoomEventsSearch<T extends ISearchResults>(searchResults: T, response: ISearchResponse): T {\n const roomEvents = response.search_categories.room_events;\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list;\n const highlights = new Set<string>(roomEvents.highlights);\n searchResults.highlights.forEach((hl) => {\n highlights.add(hl);\n });\n\n // turn it back into a list.\n searchResults.highlights = Array.from(highlights);\n\n const mapper = this.getEventMapper();\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results?.length ?? 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results![i], mapper);\n const room = this.getRoom(sr.context.getEvent().getRoomId());\n if (room) {\n // Copy over a known event sender if we can\n for (const ev of sr.context.getTimeline()) {\n const sender = room.getMember(ev.getSender()!);\n if (!ev.sender && sender) ev.sender = sender;\n }\n }\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @returns Promise which resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @returns Rejects: with an error response.\n */\n public syncLeftRooms(): Promise<Room[]> {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise\n .then(() => {\n this.logger.debug(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n })\n .finally(() => {\n this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param content - The HTTP body for the request\n * @returns Promise which resolves to a Filter object.\n * @returns Rejects: with an error response.\n */\n public createFilter(content: IFilterDefinition): Promise<Filter> {\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId!,\n });\n return this.http.authedRequest<IFilterResponse>(Method.Post, path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param userId - The user ID of the filter owner\n * @param filterId - The filter ID to retrieve\n * @param allowCached - True to allow cached filters to be returned.\n * Default: True.\n * @returns Promise which resolves: a Filter object\n * @returns Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise<Filter> {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest<IFilterDefinition>(Method.Get, path).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(userId, filterId, response);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @returns Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise<string> {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId: string | undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter = await this.getFilter(this.credentials.userId!, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if ((<MatrixError>error).errcode !== \"M_UNKNOWN\" && (<MatrixError>error).errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId!;\n }\n\n /**\n * Gets a bearer token from the homeserver that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @returns Promise which resolves: Token object\n * @returns Rejects: with an error response.\n */\n public getOpenIdToken(): Promise<IOpenIDToken> {\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId!,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, {});\n }\n\n private startCallEventHandler = (): void => {\n if (this.isInitialSyncComplete()) {\n if (supportsMatrixCall()) {\n this.callEventHandler!.start();\n this.groupCallEventHandler!.start();\n }\n\n this.off(ClientEvent.Sync, this.startCallEventHandler);\n }\n };\n\n private startMatrixRTC = (): void => {\n if (this.isInitialSyncComplete()) {\n this.matrixRTC.start();\n\n this.off(ClientEvent.Sync, this.startMatrixRTC);\n }\n };\n\n /**\n * Once the client has been initialised, we want to clear notifications we\n * know for a fact should be here.\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * We consider a room or a thread as fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n */\n private fixupRoomNotifications = (): void => {\n if (this.isInitialSyncComplete()) {\n const unreadRooms = (this.getRooms() ?? []).filter((room) => {\n return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n });\n\n for (const room of unreadRooms) {\n const currentUserId = this.getSafeUserId();\n room.fixupNotifications(currentUserId);\n }\n\n this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n }\n };\n\n /**\n * @returns Promise which resolves: ITurnServerResponse object\n * @returns Rejects: with an error response.\n */\n public turnServer(): Promise<ITurnServerResponse> {\n return this.http.authedRequest(Method.Get, \"/voip/turnServer\");\n }\n\n /**\n * Get the TURN servers for this homeserver.\n * @returns The servers or an empty list.\n */\n public getTurnServers(): ITurnServer[] {\n return this.turnServers || [];\n }\n\n /**\n * Get the unix timestamp (in milliseconds) at which the current\n * TURN credentials (from getTurnServers) expire\n * @returns The expiry timestamp in milliseconds\n */\n public getTurnServersExpiry(): number {\n return this.turnServersExpiry;\n }\n\n public get pollingTurnServers(): boolean {\n return this.checkTurnServersIntervalID !== undefined;\n }\n\n // XXX: Intended private, used in code.\n public async checkTurnServers(): Promise<boolean | undefined> {\n if (!this.canSupportVoip) {\n return;\n }\n\n let credentialsGood = false;\n const remainingTime = this.turnServersExpiry - Date.now();\n if (remainingTime > TURN_CHECK_INTERVAL) {\n this.logger.debug(\"TURN creds are valid for another \" + remainingTime + \" ms: not fetching new ones.\");\n credentialsGood = true;\n } else {\n this.logger.debug(\"Fetching new TURN credentials\");\n try {\n const res = await this.turnServer();\n if (res.uris) {\n this.logger.debug(\"Got TURN URIs: \" + res.uris + \" refresh in \" + res.ttl + \" secs\");\n // map the response to a format that can be fed to RTCPeerConnection\n const servers: ITurnServer = {\n urls: res.uris,\n username: res.username,\n credential: res.password,\n };\n this.turnServers = [servers];\n // The TTL is in seconds but we work in ms\n this.turnServersExpiry = Date.now() + res.ttl * 1000;\n credentialsGood = true;\n this.emit(ClientEvent.TurnServers, this.turnServers);\n }\n } catch (err) {\n this.logger.error(\"Failed to get TURN URIs\", err);\n if ((<HTTPError>err).httpStatus === 403) {\n // We got a 403, so there's no point in looping forever.\n this.logger.info(\"TURN access unavailable for this account: stopping credentials checks\");\n if (this.checkTurnServersIntervalID !== null) {\n globalThis.clearInterval(this.checkTurnServersIntervalID);\n }\n this.checkTurnServersIntervalID = undefined;\n this.emit(ClientEvent.TurnServersError, <HTTPError>err, true); // fatal\n } else {\n // otherwise, if we failed for whatever reason, try again the next time we're called.\n this.emit(ClientEvent.TurnServersError, <Error>err, false); // non-fatal\n }\n }\n }\n\n return credentialsGood;\n }\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n */\n public setFallbackICEServerAllowed(allow: boolean): void {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. <strong>This function is implementation specific and may change\n * as a result.</strong>\n * @returns true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise<boolean> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", { $userId: this.getUserId()! });\n return this.http\n .authedRequest<{ admin: boolean }>(Method.Get, path, undefined, undefined, { prefix: \"\" })\n .then((r) => r.admin); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * <strong>This function is implementation specific and may change as a\n * result.</strong>\n * @param userId - the User ID to look up.\n * @returns the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise<ISynapseAdminWhoisResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix: \"\" });\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. <strong>This\n * function is implementation specific and may change as a result.</strong>\n * @param userId - the User ID to deactivate.\n * @returns the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise<ISynapseAdminDeactivateResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Post, path, undefined, undefined, { prefix: \"\" });\n }\n\n protected async fetchClientWellKnown(): Promise<void> {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(this.getDomain() ?? undefined);\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(ClientEvent.ClientWellKnown, this.clientWellKnown);\n }\n\n public getClientWellKnown(): IClientWellKnown | undefined {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise<IClientWellKnown> {\n if (!this.clientRunning) {\n throw new Error(\"Client is not running\");\n }\n return this.clientWellKnownPromise!;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @returns for store operation\n */\n public storeClientOptions(): Promise<void> {\n // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts!)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce<Record<string, any>>((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.\n *\n * @param userId - The userId to check.\n * @returns Promise which resolves to an array of rooms\n * @returns Rejects: with an error response.\n */\n // TODO: on spec release, rename this to getMutualRooms\n // eslint-disable-next-line\n public async _unstable_getSharedRooms(userId: string): Promise<string[]> {\n // Initial variant of the MSC\n const sharedRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);\n\n // Newer variant that renamed shared rooms to mutual rooms\n const mutualRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);\n\n // Latest variant that changed from path elements to query elements\n const queryMutualRoomsSupport = await this.doesServerSupportUnstableFeature(\n UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS,\n );\n\n if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) {\n throw Error(\"Server does not support the Mutual Rooms API\");\n }\n\n let path;\n let query;\n\n // Cascading unstable support switching.\n if (queryMutualRoomsSupport) {\n path = \"/uk.half-shot.msc2666/user/mutual_rooms\";\n query = { user_id: userId };\n } else {\n path = utils.encodeUri(\n `/uk.half-shot.msc2666/user/${mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\"}/$userId`,\n { $userId: userId },\n );\n query = {};\n }\n\n // Accumulated rooms\n const rooms: string[] = [];\n let token = null;\n\n do {\n const tokenQuery: Record<string, string> = {};\n if (token != null && queryMutualRoomsSupport) {\n tokenQuery[\"batch_token\"] = token;\n }\n\n const res = await this.http.authedRequest<{\n joined: string[];\n next_batch_token?: string;\n }>(Method.Get, path, { ...query, ...tokenQuery }, undefined, {\n prefix: ClientPrefix.Unstable,\n });\n\n rooms.push(...res.joined);\n\n if (res.next_batch_token !== undefined) {\n token = res.next_batch_token;\n } else {\n token = null;\n }\n } while (token != null);\n\n return rooms;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @returns The server /versions response\n */\n public async getVersions(): Promise<IServerVersions> {\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n // We send an authenticated request as of MSC4026\n this.serverVersionsPromise = this.http\n .authedRequest<IServerVersions>(Method.Get, \"/_matrix/client/versions\", undefined, undefined, {\n prefix: \"\",\n })\n .catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = undefined;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n const serverVersions = await this.serverVersionsPromise;\n this.canSupport = await buildFeatureSupportMap(serverVersions);\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param version - The spec version (such as \"r0.5.0\") to check for.\n * @returns Whether it is supported\n */\n public async isVersionSupported(version: string): Promise<boolean> {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param feature - the feature name\n * @returns true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param presetName - The name of the preset to check.\n * @returns true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n public async doesServerSupportThread(): Promise<{\n threads: FeatureSupport;\n list: FeatureSupport;\n fwdPagination: FeatureSupport;\n }> {\n if (await this.isVersionSupported(\"v1.4\")) {\n return {\n threads: FeatureSupport.Stable,\n list: FeatureSupport.Stable,\n fwdPagination: FeatureSupport.Stable,\n };\n }\n\n try {\n const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] =\n await Promise.all([\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\"),\n ]);\n\n return {\n threads: determineFeatureSupport(threadStable, threadUnstable),\n list: determineFeatureSupport(listStable, listUnstable),\n fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable),\n };\n } catch {\n return {\n threads: FeatureSupport.None,\n list: FeatureSupport.None,\n fwdPagination: FeatureSupport.None,\n };\n }\n }\n\n /**\n * Get if lazy loading members is being used.\n * @returns Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts?.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param cb - The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback): void {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @returns The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback | undefined {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<{\n originalEvent?: MatrixEvent | null;\n events: MatrixEvent[];\n nextBatch?: string | null;\n prevBatch?: string | null;\n }> {\n const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;\n const [eventResult, result] = await Promise.all([\n this.fetchRoomEvent(roomId, eventId),\n this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts),\n ]);\n const mapper = this.getEventMapper();\n\n const originalEvent = eventResult ? mapper(eventResult) : undefined;\n let events = result.chunk.map(mapper);\n\n if (fetchedEventType === EventType.RoomMessageEncrypted) {\n const allEvents = originalEvent ? events.concat(originalEvent) : events;\n await Promise.all(allEvents.map((e) => this.decryptEventIfNeeded(e)));\n if (eventType !== null) {\n events = events.filter((e) => e.getType() === eventType);\n }\n }\n\n if (originalEvent && relationType === RelationType.Replace) {\n events = events.filter((e) => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent: originalEvent ?? null,\n events,\n nextBatch: result.next_batch ?? null,\n prevBatch: result.prev_batch ?? null,\n };\n }\n\n /**\n * The app may wish to see if we have a key cached without\n * triggering a user interaction.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public getCrossSigningCacheCallbacks(): ICacheCallbacks | undefined {\n // XXX: Private member access\n return this.crypto?.crossSigningInfo.getCacheCallbacks();\n }\n\n /**\n * Generates a random string suitable for use as a client secret. <strong>This\n * method is experimental and may change.</strong>\n * @returns A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param event - The event to decrypt\n * @returns A decryption promise\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise<void> {\n if (event.shouldAttemptDecryption() && this.isCryptoEnabled()) {\n event.attemptDecryption(this.cryptoBackend!, options);\n }\n\n if (event.isBeingDecrypted()) {\n return event.getDecryptionPromise()!;\n } else {\n return Promise.resolve();\n }\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string): URL {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n case SERVICE_TYPES.IM:\n return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n default:\n throw new Error(\"Unsupported service type\");\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @returns Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the identity server URL of this client\n * @param stripProto - whether or not to strip the protocol from the URL\n * @returns Identity server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string | undefined {\n if (stripProto && (this.idBaseUrl?.startsWith(\"http://\") || this.idBaseUrl?.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the identity server URL of this client\n * @param url - New identity server URL\n */\n public setIdentityServerUrl(url?: string): void {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @returns The access_token or null\n */\n public getAccessToken(): string | null {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * Get the refresh token associated with this account.\n * @returns The refresh_token or null\n */\n public getRefreshToken(): string | null {\n return this.http.opts.refreshToken ?? null;\n }\n\n /**\n * Set the access token associated with this account.\n * @param token - The new access token.\n */\n public setAccessToken(token: string): void {\n this.http.opts.accessToken = token;\n // The /versions response can vary for different users so clear the cache\n this.serverVersionsPromise = undefined;\n }\n\n /**\n * @returns true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @returns a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param username - The username to check the availability of.\n * @returns Promise which resolves: to boolean of whether the username is available.\n */\n public isUsernameAvailable(username: string): Promise<boolean> {\n return this.http\n .authedRequest<{ available: true }>(Method.Get, \"/register/available\", { username })\n .then((response) => {\n return response.available;\n })\n .catch((response) => {\n if (response.errcode === \"M_USER_IN_USE\") {\n return false;\n }\n return Promise.reject(response);\n });\n }\n\n /**\n * @param bindThreepids - Set key 'email' to true to bind any email\n * threepid uses during registration in the identity server. Set 'msisdn' to\n * true to bind msisdn.\n * @returns Promise which resolves to a RegisterResponse object\n * @returns Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string | null,\n auth: { session?: string; type: string },\n bindThreepids?: { email?: boolean; msisdn?: boolean },\n guestAccessToken?: string,\n inhibitLogin?: boolean,\n ): Promise<RegisterResponse> {\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: RegisterRequest = {\n auth: auth,\n refresh_token: true, // always ask for a refresh token - does nothing if unsupported\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n\n return this.registerRequest(params);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param body - JSON HTTP body to provide.\n * @returns Promise which resolves: JSON object that contains:\n * `{ user_id, device_id, access_token, home_server }`\n * @returns Rejects: with an error response.\n */\n public registerGuest({ body }: { body?: RegisterRequest } = {}): Promise<RegisterResponse> {\n return this.registerRequest(body || {}, \"guest\");\n }\n\n /**\n * @param data - parameters for registration request\n * @param kind - type of user to register. may be \"guest\"\n * @returns Promise which resolves: to the /register response\n * @returns Rejects: with an error response.\n */\n public registerRequest(data: RegisterRequest, kind?: string): Promise<RegisterResponse> {\n const params: { kind?: string } = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(Method.Post, \"/register\", params, data);\n }\n\n /**\n * Refreshes an access token using a provided refresh token. The refresh token\n * must be valid for the current access token known to the client instance.\n *\n * Note that this function will not cause a logout if the token is deemed\n * unknown by the server - the caller is responsible for managing logout\n * actions on error.\n * @param refreshToken - The refresh token.\n * @returns Promise which resolves to the new token.\n * @returns Rejects with an error response.\n */\n public refreshToken(refreshToken: string): Promise<IRefreshTokenResponse> {\n const performRefreshRequestWithPrefix = (prefix: ClientPrefix): Promise<IRefreshTokenResponse> =>\n this.http.authedRequest(\n Method.Post,\n \"/refresh\",\n undefined,\n { refresh_token: refreshToken },\n {\n prefix,\n inhibitLogoutEmit: true, // we don't want to cause logout loops\n },\n );\n\n // First try with the (specced) /v3/ prefix.\n // However, before Synapse 1.72.0, Synapse incorrectly required a /v1/ prefix, so we fall\n // back to that if the request fails, for backwards compatibility.\n return performRefreshRequestWithPrefix(ClientPrefix.V3).catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n return performRefreshRequestWithPrefix(ClientPrefix.V1);\n }\n throw e;\n });\n }\n\n /**\n * @returns Promise which resolves to the available login flows\n * @returns Rejects: with an error response.\n */\n public loginFlows(): Promise<ILoginFlowsResponse> {\n return this.http.request(Method.Get, \"/login\");\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public login(loginType: LoginRequest[\"type\"], data: Omit<LoginRequest, \"type\">): Promise<LoginResponse> {\n return this.http\n .authedRequest<LoginResponse>(Method.Post, \"/login\", undefined, {\n ...data,\n type: loginType,\n })\n .then((response) => {\n if (response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string): Promise<LoginResponse> {\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n });\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with CAS.\n * @returns The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param loginType - The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param idpId - The ID of the Identity Provider being targeted, optional.\n * @param action - the SSO flow to indicate to the IdP, optional.\n * @returns The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string, action?: SSOAction): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n const params = {\n redirectUrl,\n [SSO_ACTION_PARAM.unstable!]: action,\n };\n\n return this.http.getUrl(url, params).href;\n }\n\n /**\n * @param token - Login token previously received from homeserver\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithToken(token: string): Promise<LoginResponse> {\n return this.login(\"m.login.token\", {\n token: token,\n });\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n * @returns Promise which resolves: On success, the empty object `{}`\n */\n public async logout(stopClient = false): Promise<{}> {\n if (this.crypto?.backupManager?.getKeyBackupEnabled()) {\n try {\n while ((await this.crypto.backupManager.backupPendingKeys(200)) > 0);\n } catch (err) {\n this.logger.error(\n \"Key backup request failed when logging out. Some keys may be missing from backup\",\n err,\n );\n }\n }\n\n if (stopClient) {\n this.stopClient();\n this.http.abort();\n }\n\n return this.http.authedRequest(Method.Post, \"/logout\");\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @param erase - Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @returns Promise which resolves: On success, the empty object\n */\n public deactivateAccount(\n auth?: AuthDict,\n erase?: boolean,\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const body: Body = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n }\n\n /**\n * Make a request for an `m.login.token` to be issued as per\n * https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token\n *\n * The server may require User-Interactive auth.\n *\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: On success, the token response\n * or UIA auth data.\n */\n public async requestLoginToken(auth?: AuthDict): Promise<UIAResponse<LoginTokenPostResponse>> {\n const body: UIARequest<{}> = { auth };\n return this.http.authedRequest<UIAResponse<LoginTokenPostResponse>>(\n Method.Post,\n \"/login/get_token\",\n undefined, // no query params\n body,\n { prefix: ClientPrefix.V1 },\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param loginType - the type of stage being attempted\n * @param authSessionId - the auth session ID provided by the homeserver\n *\n * @returns HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(path, {\n session: authSessionId,\n }).href;\n }\n\n /**\n * Create a new room.\n * @param options - a list of options to pass to the /createRoom API.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }> {\n // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);\n if (invitesNeedingToken.length > 0 && this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n }\n\n /**\n * Fetches relations for a given event\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns the response, with chunk, prev_batch and, next_batch.\n */\n public fetchRelations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<IRelationsResponse> {\n let params = opts as QueryDict;\n if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n }\n if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) {\n params = replaceParam(\"recurse\", \"org.matrix.msc3981.recurse\", params);\n }\n const queryString = utils.encodeParams(params);\n\n let templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n if (relationType !== null) {\n templatedUrl += \"/$relationType\";\n if (eventType !== null) {\n templatedUrl += \"/$eventType\";\n }\n } else if (eventType !== null) {\n this.logger.warn(`eventType: ${eventType} ignored when fetching\n relations as relationType is null`);\n eventType = null;\n }\n\n const path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType!,\n $eventType: eventType!,\n });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V1,\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomState(roomId: string): Promise<IStateEventWithRoomId[]> {\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get an event in a room by its event id.\n *\n * @returns Promise which resolves to an object containing the event.\n * @returns Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string): Promise<Partial<IEvent>> {\n const path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param includeMembership - the membership type to include in the response\n * @param excludeMembership - the membership type to exclude from the response\n * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n * @returns Promise which resolves: dictionary of userid to profile information\n * @returns Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string,\n excludeMembership?: string,\n atEventId?: string,\n ): Promise<{ [userId: string]: IStateEventWithRoomId[] }> {\n const queryParams: Record<string, string> = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param newVersion - The target version to upgrade to\n * @returns Promise which resolves: Object with key 'replacement_room'\n * @returns Rejects: with an error response.\n */\n public upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: string }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(Method.Post, path, undefined, { new_version: newVersion });\n }\n\n /**\n * Retrieve a state event.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string): Promise<Record<string, any>> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Send a state event into a room\n * @param roomId - ID of the room to send the event into\n * @param eventType - type of the state event to send\n * @param content - content of the event to send\n * @param stateKey - the stateKey to send into the room\n * @param opts - Options for the request function.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public sendStateEvent<K extends keyof StateEvents>(\n roomId: string,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<ISendEventResponse> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, undefined, content as Body, opts);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number): Promise<IRoomInitialSyncResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\", { $roomId: roomId });\n\n return this.http.authedRequest(Method.Get, path, { limit: limit?.toString() ?? \"30\" });\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEventId - ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n * don't want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId?: string,\n rpEventId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content: IContent = {\n [ReceiptType.FullyRead]: rmEventId,\n [ReceiptType.Read]: rrEventId,\n };\n\n if (\n (await this.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) ||\n (await this.isVersionSupported(\"v1.4\"))\n ) {\n content[ReceiptType.ReadPrivate] = rpEventId;\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * @returns Promise which resolves: A list of the user's current rooms\n * @returns Rejects: with an error response.\n */\n public getJoinedRooms(): Promise<IJoinedRoomsResponse> {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param roomId - ID of the room to get membership for\n * @returns Promise which resolves: A list of currently joined users\n * and their profile data.\n * @returns Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise<IJoinedMembersResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param params - Options for this request\n * @returns Promise which resolves: IPublicRoomsResponse\n * @returns Rejects: with an error response.\n */\n public publicRooms({\n server,\n limit,\n since,\n ...options\n }: IRoomDirectoryOptions = {}): Promise<IPublicRoomsResponse> {\n if (Object.keys(options).length === 0) {\n const queryParams: QueryDict = { server, limit, since };\n return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n } else {\n const queryParams: QueryDict = { server };\n const body = {\n limit,\n since,\n ...options,\n };\n return this.http.authedRequest(Method.Post, \"/publicRooms\", queryParams, body);\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param alias - The room alias to create.\n * @param roomId - The room ID to link the alias to.\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server,\n * and you must have sufficient access to do this operation.\n * @param alias - The room alias to delete.\n * @returns Promise which resolves: an empty object `{}`.\n * @returns Rejects: with an error response.\n */\n public deleteAlias(alias: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n * curated list from the m.room.canonical_alias state event.\n * @param roomId - The room ID to get local aliases for.\n * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n * @returns Rejects: with an error response.\n */\n public getLocalAliases(roomId: string): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\", { $roomId: roomId });\n const prefix = ClientPrefix.V3;\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param alias - The room alias to resolve.\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n public getRoomIdForAlias(alias: string): Promise<{ room_id: string; servers: string[] }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string): Promise<{ visibility: Visibility }> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Set the visibility of a room in the current HS's room directory\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(roomId: string, visibility: Visibility): Promise<{}> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility });\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param options\n * @param options.term - the term with which to search.\n * @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.\n * @returns Promise which resolves: an array of results.\n */\n public searchUserDirectory({ term, limit }: { term: string; limit?: number }): Promise<IUserDirectoryResponse> {\n const body: Body = {\n search_term: term,\n };\n\n if (limit !== undefined) {\n body.limit = limit;\n }\n\n return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n }\n\n /**\n * Upload a file to the media repository on the homeserver.\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts?: UploadOpts): Promise<UploadResponse> {\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param upload - The object returned from uploadContent\n * @returns true if canceled, otherwise false\n */\n public cancelUpload(upload: Promise<UploadResponse>): boolean {\n return this.http.cancelUpload(upload);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @returns Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): Upload[] {\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param info - The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getProfileInfo(\n userId: string,\n info?: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ avatar_url?: string; displayname?: string }> {\n const path = info\n ? utils.encodeUri(\"/profile/$userId/$info\", { $userId: userId, $info: info })\n : utils.encodeUri(\"/profile/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Determine if the server supports extended profiles, as described by MSC4133.\n *\n * @returns `true` if supported, otherwise `false`\n */\n public async doesServerSupportExtendedProfiles(): Promise<boolean> {\n return this.doesServerSupportUnstableFeature(UNSTABLE_MSC4133_EXTENDED_PROFILES);\n }\n\n /**\n * Get the prefix used for extended profile requests.\n *\n * @returns The prefix for use with `authedRequest`\n */\n private async getExtendedProfileRequestPrefix(): Promise<string> {\n if (await this.doesServerSupportUnstableFeature(\"uk.tcpip.msc4133.stable\")) {\n return ClientPrefix.V3;\n }\n return \"/_matrix/client/unstable/uk.tcpip.msc4133\";\n }\n\n /**\n * Fetch a user's *extended* profile, which may include additonal keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @returns A set of keys to property values.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the profile could not be found.\n */\n public async getExtendedProfile(userId: string): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n return this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Fetch a specific key from the user's *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @param key The key of the property to fetch.\n * @returns The property value.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.\n */\n public async getExtendedProfileProperty(userId: string, key: string): Promise<unknown> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const profile = (await this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n )) as Record<string, unknown>;\n return profile[key];\n }\n\n /**\n * Set a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to set.\n * @param value The value to set on the propety.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfileProperty(key: string, value: unknown): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n { [key]: value },\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Delete a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to delete.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async deleteExtendedProfileProperty(key: string): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Delete,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Update multiple properties on your *extended* profile. This will\n * merge with any existing keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to merge with the existing profile.\n * @returns The newly merged profile.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async patchExtendedProfile(profile: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n return this.http.authedRequest(\n Method.Patch,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Set multiple properties on your *extended* profile. This will completely\n * replace the existing profile, removing any unspecified keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to set.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfile(profile: Record<string, unknown>): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * @returns Promise which resolves to a list of the user's threepids.\n * @returns Rejects: with an error response.\n */\n public getThreePids(): Promise<{ threepids: IThreepid[] }> {\n return this.http.authedRequest(Method.Get, \"/account/3pid\");\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * @param data - A object with 3PID validation data from having called\n * `account/3pid/<medium>/requestToken` on the homeserver.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async addThreePidOnly(data: IAddThreePidOnlyBody): Promise<{}> {\n const path = \"/account/3pid/add\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * @param data - A object with 3PID validation data from having called\n * `validate/<medium>/requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async bindThreePid(data: IBindThreePidBody): Promise<{}> {\n const path = \"/account/3pid/bind\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public async unbindThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: The server response on success\n * (generally the empty JSON object)\n * @returns Rejects: with an error response.\n */\n public deleteThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/delete\";\n return this.http.authedRequest(Method.Post, path, undefined, { medium, address });\n }\n\n /**\n * Make a request to change your password.\n * @param newPassword - The new desired password.\n * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPassword(authDict: AuthDict, newPassword: string, logoutDevices?: boolean): Promise<{}> {\n const path = \"/account/password\";\n const data = {\n auth: authDict,\n new_password: newPassword,\n logout_devices: logoutDevices,\n };\n\n return this.http.authedRequest<{}>(Method.Post, path, undefined, data);\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevices(): Promise<{ devices: IMyDevice[] }> {\n return this.http.authedRequest(Method.Get, \"/devices\");\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param deviceId - device to query\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise<IMyDevice> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Update the given device\n *\n * @param deviceId - device to update\n * @param body - body of request\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setDeviceDetails(deviceId: string, body: { display_name: string }): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param deviceId - device to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: AuthDict): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: Body = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(Method.Delete, path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param devices - IDs of the devices to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: AuthDict): Promise<{}> {\n const body: Body = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @returns Promise which resolves: Array of objects representing pushers\n * @returns Rejects: with an error response.\n */\n public async getPushers(): Promise<{ pushers: IPusher[] }> {\n const response = await this.http.authedRequest<{ pushers: IPusher[] }>(Method.Get, \"/pushers\");\n\n // Migration path for clients that connect to a homeserver that does not support\n // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n if (!(await this.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n response.pushers = response.pushers.map((pusher) => {\n if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n pusher[PUSHER_ENABLED.name] = true;\n }\n return pusher;\n });\n }\n\n return response;\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param pusher - Object representing a pusher\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public setPusher(pusher: IPusherRequest): Promise<{}> {\n const path = \"/pushers/set\";\n return this.http.authedRequest(Method.Post, path, undefined, pusher);\n }\n\n /**\n * Removes an existing pusher\n * @param pushKey - pushkey of pusher to remove\n * @param appId - app_id of pusher to remove\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public removePusher(pushKey: string, appId: string): Promise<{}> {\n const path = \"/pushers/set\";\n const body = {\n pushkey: pushKey,\n app_id: appId,\n kind: null, // marks pusher for removal\n };\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Persists local notification settings\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setLocalNotificationSettings(\n deviceId: string,\n notificationSettings: LocalNotificationSettings,\n ): Promise<{}> {\n const key = `${LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${deviceId}`;\n return this.setAccountData(key, notificationSettings);\n }\n\n /**\n * Get the push rules for the account from the server.\n * @returns Promise which resolves to the push rules.\n * @returns Rejects: with an error response.\n */\n public getPushRules(): Promise<IPushRules> {\n return this.http.authedRequest<IPushRules>(Method.Get, \"/pushrules/\").then((rules: IPushRules) => {\n this.setPushRules(rules);\n return this.pushRules!;\n });\n }\n\n /**\n * Update the push rules for the account. This should be called whenever\n * updated push rules are available.\n */\n public setPushRules(rules: IPushRules): void {\n // Fix-up defaults, if applicable.\n this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);\n // Pre-calculate any necessary caches.\n this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public addPushRule(\n scope: string,\n kind: PushRuleKind,\n ruleId: Exclude<string, RuleId>,\n body: Pick<IPushRule, \"actions\" | \"conditions\" | \"pattern\">,\n ): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: PushRuleKind, ruleId: Exclude<string, RuleId>): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n enabled: boolean,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { enabled: enabled });\n }\n\n /**\n * Set the actions for a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n actions: PushRuleAction[],\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { actions: actions });\n }\n\n /**\n * Perform a server-side search.\n * @param params\n * @param params.next_batch - the batch token to pass in the query string\n * @param params.body - the JSON object to pass to the request body.\n * @param abortSignal - optional signal used to cancel the http request.\n * @returns Promise which resolves to the search response object.\n * @returns Rejects: with an error response.\n */\n public search(\n { body, next_batch: nextBatch }: { body: ISearchRequestBody; next_batch?: string },\n abortSignal?: AbortSignal,\n ): Promise<ISearchResponse> {\n const queryParams: QueryDict = {};\n if (nextBatch) {\n queryParams.next_batch = nextBatch;\n }\n return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, { abortSignal });\n }\n\n /**\n * Upload keys\n *\n * @param content - body of upload request\n *\n * @param opts - this method no longer takes any opts,\n * used to take opts.device_id but this was not removed from the spec as a redundant parameter\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public uploadKeysRequest(content: IUploadKeysRequest, opts?: void): Promise<IKeysUploadResponse> {\n return this.http.authedRequest(Method.Post, \"/keys/upload\", undefined, content);\n }\n\n public uploadKeySignatures(content: KeySignatures): Promise<IUploadKeySignaturesResponse> {\n return this.http.authedRequest(Method.Post, \"/keys/signatures/upload\", undefined, content);\n }\n\n /**\n * Download device keys\n *\n * @param userIds - list of users to get keys for\n *\n * @param token - sync token to pass in the query request, to help\n * the HS give the most recent results\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public downloadKeysForUsers(userIds: string[], { token }: { token?: string } = {}): Promise<IDownloadKeyResult> {\n const content: IQueryKeysRequest = {\n device_keys: {},\n };\n if (token !== undefined) {\n content.token = token;\n }\n userIds.forEach((u) => {\n content.device_keys[u] = [];\n });\n\n return this.http.authedRequest(Method.Post, \"/keys/query\", undefined, content);\n }\n\n /**\n * Claim one-time keys\n *\n * @param devices - a list of [userId, deviceId] pairs\n *\n * @param keyAlgorithm - desired key type\n *\n * @param timeout - the time (in milliseconds) to wait for keys from remote\n * servers\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public claimOneTimeKeys(\n devices: [string, string][],\n keyAlgorithm = \"signed_curve25519\",\n timeout?: number,\n ): Promise<IClaimOTKsResult> {\n const queries: Record<string, Record<string, string>> = {};\n\n if (keyAlgorithm === undefined) {\n keyAlgorithm = \"signed_curve25519\";\n }\n\n for (const [userId, deviceId] of devices) {\n const query = queries[userId] || {};\n safeSet(queries, userId, query);\n safeSet(query, deviceId, keyAlgorithm);\n }\n const content: IClaimKeysRequest = { one_time_keys: queries };\n if (timeout) {\n content.timeout = timeout;\n }\n const path = \"/keys/claim\";\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<{ changed: string[]; left: string[] }> {\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n }\n\n public uploadDeviceSigningKeys(auth?: AuthDict, keys?: CrossSigningKeys): Promise<{}> {\n // API returns empty object\n const data = Object.assign({}, keys);\n if (auth) Object.assign(data, { auth });\n return this.http.authedRequest(Method.Post, \"/keys/device_signing/upload\", undefined, data, {\n prefix: ClientPrefix.Unstable,\n });\n }\n\n /**\n * Register with an identity server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @returns Promise which resolves: with object containing an Identity\n * Server access token.\n * @returns Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: IOpenIDToken): Promise<{\n access_token: string;\n token: string;\n }> {\n if (!this.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n const uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param email - The email address to request a token for\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestTokenResponse>(\n Method.Post,\n \"/validate/email/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international\n * format\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves to an object with a sid string\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestMsisdnTokenResponse>(\n Method.Post,\n \"/validate/msisdn/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The identity server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n * Some legacy identity servers had no authentication here.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n * @throws Error if No identity server is set\n */\n public submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string | null,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/submitToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken ?? undefined,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param url - The URL to submit the token to\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n return this.http.requestOtherUrl(Method.Post, url, params);\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param identityAccessToken - The access token for the identity server.\n * @returns The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise<{\n /**\n * The algorithms the server supports. Must contain at least sha256.\n */\n algorithms: string[];\n /**\n * The pepper the client MUST use in hashing identifiers,\n * and MUST supply to the /lookup endpoint when performing lookups.\n */\n lookup_pepper: string;\n }> {\n return this.http.idServerRequest(\n Method.Get,\n \"/hash_details\",\n undefined,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param addressPairs - An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: `[\"email@example.org\", \"email\"]`\n * @param identityAccessToken - The access token for the identity server.\n * @returns A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string; mxid: string }[]> {\n const params: Record<string, string | string[]> = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params[\"pepper\"] = hashes[\"lookup_pepper\"];\n\n const localMapping: Record<string, string> = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes[\"algorithms\"].includes(\"sha256\")) {\n params[\"addresses\"] = await Promise.all(\n addressPairs.map(async (p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashBuffer = await sha256(`${addr} ${med} ${params[\"pepper\"]}`);\n const hashed = encodeUnpaddedBase64Url(hashBuffer);\n\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n }),\n );\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes[\"algorithms\"].includes(\"none\")) {\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case-sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest<{\n mappings: { [address: string]: string };\n }>(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n\n if (!response?.[\"mappings\"]) return []; // no results\n\n const foundAddresses: { address: string; mxid: string }[] = [];\n for (const hashed of Object.keys(response[\"mappings\"])) {\n const mxid = response[\"mappings\"][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the identity server\n *\n * @param medium - The medium of the threepid, eg. 'email'\n * @param address - The textual address of the threepid\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @returns Rejects: with an error response.\n */\n public async lookupThreePid(\n medium: string,\n address: string,\n identityAccessToken: string,\n ): Promise<\n | {\n address: string;\n medium: string;\n mxid: string;\n }\n | {}\n > {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup([[address, medium]], identityAccessToken);\n const result = response.find((p) => p.address === address);\n if (!result) {\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param query - Array of arrays containing\n * [medium, address]\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Lookup results from IS.\n * @returns Rejects: with an error response.\n */\n public async bulkLookupThreePids(\n query: [string, string][],\n identityAccessToken: string,\n ): Promise<{\n threepids: [medium: string, address: string, mxid: string][];\n }> {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map((p) => [p[1], p[0]]),\n identityAccessToken,\n );\n\n const v1results: [medium: string, address: string, mxid: string][] = [];\n for (const mapping of response) {\n const originalQuery = query.find((p) => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the identity server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: an object with account info.\n * @returns Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise<{ user_id: string }> {\n return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n }\n\n /**\n * Send an event to a specific list of devices.\n * This is a low-level API that simply wraps the HTTP API\n * call to send to-device messages. We recommend using\n * queueToDevice() which is a higher level API.\n *\n * @param eventType - type of event to send\n * content to send. Map from user_id to device_id to content object.\n * @param txnId - transaction id. One will be made up if not\n * supplied.\n * @returns Promise which resolves: to an empty object `{}`\n */\n public sendToDevice(eventType: string, contentMap: SendToDeviceContentMap, txnId?: string): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: utils.recursiveMapToObject(contentMap),\n };\n\n const targets = new Map<string, string[]>();\n\n for (const [userId, deviceMessages] of contentMap) {\n targets.set(userId, Array.from(deviceMessages.keys()));\n }\n\n this.logger.debug(`PUT ${path}`, targets);\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Sends events directly to specific devices using Matrix's to-device\n * messaging system. The batch will be split up into appropriately sized\n * batches for sending and stored in the store so they can be retried\n * later if they fail to send. Retries will happen automatically.\n * @param batch - The to-device messages to send\n */\n public queueToDevice(batch: ToDeviceBatch): Promise<void> {\n return this.toDeviceMessageQueue.queueBatch(batch);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<{ [protocol: string]: IProtocol }> {\n return this.http\n .authedRequest<Record<string, IProtocol>>(Method.Get, \"/thirdparty/protocols\")\n .then((response) => {\n // sanity check\n if (!response || typeof response !== \"object\") {\n throw new Error(`/thirdparty/protocols did not return an object: ${response}`);\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyLocation(\n protocol: string,\n params: { searchFields?: string[] },\n ): Promise<IThirdPartyLocation[]> {\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params?: QueryDict): Promise<IThirdPartyUser[]> {\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise<any> {\n // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(Method.Get, url);\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<{}> {\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n Method.Post,\n url,\n {\n user_accepts: termsUrls,\n },\n { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param roomId - The room in which the event being reported is located.\n * @param eventId - The event to report.\n * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param reason - The reason the content is being reported. May be blank.\n * @returns Promise which resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, { score, reason });\n }\n\n /**\n * Fetches or paginates a room hierarchy as defined by MSC2946.\n * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n * @param roomId - The ID of the space-room to use as the root of the summary.\n * @param limit - The maximum number of rooms to return per page.\n * @param maxDepth - The maximum depth in the tree from the root room to return.\n * @param suggestedOnly - Whether to only return rooms with suggested=true.\n * @param fromToken - The opaque token to paginate a previous request.\n * @returns the response, with next_batch & rooms fields.\n */\n public getRoomHierarchy(\n roomId: string,\n limit?: number,\n maxDepth?: number,\n suggestedOnly = false,\n fromToken?: string,\n ): Promise<IRoomHierarchy> {\n const path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n $roomId: roomId,\n });\n\n const queryParams: QueryDict = {\n suggested_only: String(suggestedOnly),\n max_depth: maxDepth?.toString(),\n from: fromToken,\n limit: limit?.toString(),\n };\n\n return this.http\n .authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n })\n .catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n // fall back to the prefixed hierarchy API.\n return this.http.authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n throw e;\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param name - The name of the tree space.\n * @returns Promise which resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise<MSC3089TreeSpace> {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()!]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n {\n type: EventType.RoomEncryption,\n state_key: \"\",\n content: {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param roomId - The room ID to get a tree space reference for.\n * @returns The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace | null {\n const room = this.getRoom(roomId);\n if (room?.getMyMembership() !== KnownMembership.Join) return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n );\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Perform a single MSC3575 sliding sync request.\n * @param req - The request to make.\n * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n * @param abortSignal - Optional signal to abort request mid-flight.\n * @returns The sliding sync response, or a standard error.\n * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n */\n public slidingSync(\n req: MSC3575SlidingSyncRequest,\n proxyBaseUrl?: string,\n abortSignal?: AbortSignal,\n ): Promise<MSC3575SlidingSyncResponse> {\n const qps: QueryDict = {};\n if (req.pos) {\n qps.pos = req.pos;\n delete req.pos;\n }\n if (req.timeout) {\n qps.timeout = req.timeout;\n delete req.timeout;\n }\n const clientTimeout = req.clientTimeout;\n delete req.clientTimeout;\n return this.http.authedRequest<MSC3575SlidingSyncResponse>(Method.Post, \"/sync\", qps, req, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3575\",\n baseUrl: proxyBaseUrl,\n localTimeoutMs: clientTimeout,\n abortSignal,\n });\n }\n\n /**\n * A helper to determine thread support\n * @returns a boolean to determine if threads are enabled\n */\n public supportsThreads(): boolean {\n return this.clientOpts?.threadSupport || false;\n }\n\n /**\n * A helper to determine intentional mentions support\n * @returns a boolean to determine if intentional mentions are enabled on the server\n * @experimental\n */\n public supportsIntentionalMentions(): boolean {\n return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;\n }\n\n /**\n * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n * @param via - The list of servers which know about the room if only an ID was provided.\n */\n public async getRoomSummary(roomIdOrAlias: string, via?: string[]): Promise<RoomSummary> {\n const paramOpts = {\n prefix: \"/_matrix/client/unstable/im.nheko.summary\",\n };\n try {\n const path = utils.encodeUri(\"/summary/$roomid\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } catch (e) {\n if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n const path = utils.encodeUri(\"/rooms/$roomid/summary\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * Processes a list of threaded events and adds them to their respective timelines\n * @param room - the room the adds the threaded events\n * @param threadedEvents - an array of the threaded events\n * @param toStartOfTimeline - the direction in which we want to add the events\n */\n public processThreadEvents(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n }\n\n /**\n * Processes a list of thread roots and creates a thread model\n * @param room - the room to create the threads in\n * @param threadedEvents - an array of thread roots\n * @param toStartOfTimeline - the direction\n */\n public processThreadRoots(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.supportsThreads()) return;\n room.processThreadRoots(threadedEvents, toStartOfTimeline);\n }\n\n public processBeaconEvents(room?: Room, events?: MatrixEvent[]): void {\n this.processAggregatedTimelineEvents(room, events);\n }\n\n /**\n * Calls aggregation functions for event types that are aggregated\n * Polls and location beacons\n * @param room - room the events belong to\n * @param events - timeline events to be processed\n * @returns\n */\n public processAggregatedTimelineEvents(room?: Room, events?: MatrixEvent[]): void {\n if (!events?.length) return;\n if (!room) return;\n\n room.currentState.processBeaconEvents(events, this);\n room.processPollEvents(events);\n }\n\n /**\n * Fetches information about the user for the configured access token.\n */\n public async whoami(): Promise<IWhoamiResponse> {\n return this.http.authedRequest(Method.Get, \"/account/whoami\");\n }\n\n /**\n * Find the event_id closest to the given timestamp in the given direction.\n * @returns Resolves: A promise of an object containing the event_id and\n * origin_server_ts of the closest event to the timestamp in the given direction\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n */\n public async timestampToEvent(\n roomId: string,\n timestamp: number,\n dir: Direction,\n ): Promise<TimestampToEventResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n $roomId: roomId,\n });\n const queryParams = {\n ts: timestamp.toString(),\n dir: dir,\n };\n\n try {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n });\n } catch (err) {\n // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n // new, we should also try the unstable endpoint before giving up. We can\n // remove this fallback request in a year (remove after 2023-11-28).\n if (\n (<MatrixError>err).errcode === \"M_UNRECOGNIZED\" &&\n // XXX: The 400 status code check should be removed in the future\n // when Synapse is compliant with MSC3743.\n ((<MatrixError>err).httpStatus === 400 ||\n // This the correct standard status code for an unsupported\n // endpoint according to MSC3743. Not Found and Method Not Allowed\n // both indicate that this endpoint+verb combination is\n // not supported.\n (<MatrixError>err).httpStatus === 404 ||\n (<MatrixError>err).httpStatus === 405)\n ) {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3030\",\n });\n }\n\n throw err;\n }\n }\n\n /**\n * Get the OIDC issuer responsible for authentication on this server, if any\n * @returns Resolves: A promise of an object containing the OIDC issuer if configured\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n * @experimental - part of MSC2965\n */\n public async getAuthIssuer(): Promise<{\n issuer: string;\n }> {\n return this.http.request(Method.Get, \"/auth_issuer\", undefined, undefined, {\n prefix: ClientPrefix.Unstable + \"/org.matrix.msc2965\",\n });\n }\n}\n\nfunction getUnstableDelayQueryOpts(delayOpts: SendDelayedEventRequestOpts): QueryDict {\n return Object.fromEntries(\n Object.entries(delayOpts).map(([k, v]) => [`${UNSTABLE_MSC4140_DELAYED_EVENTS}.${k}`, v]),\n );\n}\n\n/**\n * recalculates an accurate notifications count on event decryption.\n * Servers do not have enough knowledge about encrypted events to calculate an\n * accurate notification_count\n */\nexport function fixNotificationCountOnDecryption(cli: MatrixClient, event: MatrixEvent): void {\n const ourUserId = cli.getUserId();\n const eventId = event.getId();\n\n const room = cli.getRoom(event.getRoomId());\n if (!room || !ourUserId || !eventId) return;\n\n // Due to threads, we can get relation events (eg. edits & reactions) that never get\n // added to a timeline and so cannot be found in their own room (their edit / reaction\n // still applies to the event it needs to, so it doesn't matter too much). However, if\n // we try to process notification about this event, we'll get very confused because we\n // won't be able to find the event in the room, so will assume it must be unread, even\n // if it's actually read. We therefore skip anything that isn't in the room. This isn't\n // *great*, so if we can fix the homeless events (eg. with MSC4023) then we should probably\n // remove this workaround.\n if (!room.findEventById(eventId)) {\n logger.info(`Decrypted event ${event.getId()} is not in room ${room.roomId}: ignoring`);\n return;\n }\n\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n let hasReadEvent;\n if (isThreadEvent) {\n const thread = room.getThread(event.threadRootId);\n hasReadEvent = thread\n ? thread.hasUserReadEvent(ourUserId, eventId)\n : // If the thread object does not exist in the room yet, we don't\n // want to calculate notification for this event yet. We have not\n // restored the read receipts yet and can't accurately calculate\n // notifications at this stage.\n //\n // This issue can likely go away when MSC3874 is implemented\n true;\n } else {\n hasReadEvent = room.hasUserReadEvent(ourUserId, eventId);\n }\n\n if (hasReadEvent) {\n // If the event has been read, ignore it.\n return;\n }\n\n const actions = cli.getPushActionsForEvent(event, true);\n\n // Ensure the unread counts are kept up to date if the event is encrypted\n // We also want to make sure that the notification count goes up if we already\n // have encrypted events to avoid other code from resetting 'highlight' to zero.\n const newHighlight = !!actions?.tweaks?.highlight;\n\n if (newHighlight) {\n // TODO: Handle mentions received while the client is offline\n // See also https://github.com/vector-im/element-web/issues/9069\n const newCount = room.getUnreadCountForEventContext(NotificationCountType.Highlight, event) + 1;\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Highlight, newCount);\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);\n }\n }\n\n // `notify` is used in practice for incrementing the total count\n const newNotify = !!actions?.notify;\n\n // The room total count is NEVER incremented by the server for encrypted rooms. We basically ignore\n // the server here as it's always going to tell us to increment for encrypted events.\n if (newNotify) {\n // Total count is used to typically increment a room notification counter, but not loudly highlight it.\n const newCount = room.getUnreadCountForEventContext(NotificationCountType.Total, event) + 1;\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Total, newCount);\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Total, newCount);\n }\n }\n}\n\n/**\n * Given an event, figure out the thread ID we should use for it in a receipt.\n *\n * This will either be \"main\", or event.threadRootId. For the thread root, or\n * e.g. reactions to the thread root, this will be main. For events inside the\n * thread, or e.g. reactions to them, this will be event.threadRootId.\n *\n * (Exported for test.)\n */\nexport function threadIdForReceipt(event: MatrixEvent): string {\n return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId!;\n}\n\n/**\n * a) True for non-threaded messages, thread roots and non-thread relations to thread roots.\n * b) False for messages with thread relations to the thread root.\n * c) False for messages with any kind of relation to a message from case b.\n *\n * Note: true for redactions of messages that are in threads. Redacted messages\n * are not really in threads (because their relations are gone), so if they look\n * like they are in threads, that is a sign of a bug elsewhere. (At time of\n * writing, this bug definitely exists - messages are not moved to another\n * thread when they are redacted.)\n *\n * @returns true if this event is considered to be in the main timeline as far\n * as receipts are concerned.\n */\nexport function inMainTimelineForReceipt(event: MatrixEvent): boolean {\n if (!event.threadRootId) {\n // Not in a thread: then it is in the main timeline\n return true;\n }\n\n if (event.isThreadRoot) {\n // Thread roots are in the main timeline. Note: the spec is ambiguous (or\n // wrong) on this - see\n // https://github.com/matrix-org/matrix-spec-proposals/pull/4037\n return true;\n }\n\n if (!event.isRelation()) {\n // If it's not related to anything, it can't be related via a chain of\n // relations to a thread root.\n //\n // Note: this is a bug, because how does it have a threadRootId if it is\n // neither a thread root, nor related to one?\n logger.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${event.getId()}`);\n return true;\n }\n\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n // It's a message in a thread - definitely not in the main timeline.\n return false;\n }\n\n const isRelatedToRoot = event.relationEventId === event.threadRootId;\n\n // If it's related to the thread root (and we already know it's not a thread\n // relation) then it's in the main timeline. If it's related to something\n // else, then it's in the thread (because it has a thread ID).\n return isRelatedToRoot;\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAKA,SAAsCA,OAAO,EAAkBC,SAAS,QAAQ,WAAW;AAC3F,SACIC,WAAW,EAIXC,WAAW,EACXC,gBAAgB,QAGb,mBAAmB;AAC1B,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAAyCC,mBAAmB,EAAcC,kBAAkB,QAAQ,kBAAkB;AACtH,SAASC,MAAM,QAA6C,aAAa;AACzE,SAASC,gBAAgB,QAAgE,8BAA8B;AACvH,SACIC,qBAAqB,QAGlB,mCAAmC;AAC1C,OAAO,KAAKC,KAAK,MAAM,YAAY;AACnC,SAASC,kBAAkB,EAAaC,YAAY,EAAEC,OAAO,EAAEC,KAAK,QAAQ,YAAY;AACxF,SAASC,SAAS,EAAEC,aAAa,QAAQ,4BAA4B;AACrE,SAAyBC,aAAa,QAAQ,oBAAoB;AAClE,SAASC,aAAa,QAA6B,oBAAoB;AACvE,OAAO,KAAKC,MAAM,MAAM,oBAAoB;AAC5C,SAASC,YAAY,EAAEC,YAAY,EAAEC,uBAAuB,QAAQ,aAAa;AAGjF,SAASC,cAAc,QAAQ,gBAAgB;AAE/C,SAASC,MAAM,QAAgB,aAAa;AAC5C,SAASC,aAAa,QAAQ,oBAAoB;AAClD,SAEIC,YAAY,EAKZC,cAAc,EAGdC,WAAW,EACXC,aAAa,EACbC,WAAW,EACXC,MAAM,EACNC,qBAAqB,QAKlB,qBAAqB;AAC5B,SACIC,MAAM,EACNC,WAA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+E7G,KAAK,CAACwW,KAAK,CAAC,CAAC,CAAE,CAAC;IAC1G,OAAO,IAAI;EACf;EAEA,IAAIxW,KAAK,CAAC8jB,UAAU,CAAChsB,oBAAoB,CAAC6a,IAAI,CAAC,EAAE;IAC7C;IACA,OAAO,KAAK;EAChB;EAEA,IAAMsqC,eAAe,GAAGj9C,KAAK,CAACk9C,eAAe,KAAKl9C,KAAK,CAACk8C,YAAY;;EAEpE;EACA;EACA;EACA,OAAOe,eAAe;AAC1B","ignoreList":[]}
1
+ {"version":3,"file":"client.js","names":["SyncApi","SyncState","EventStatus","MatrixEvent","MatrixEventEvent","StubStore","createNewMatrixCall","supportsMatrixCall","Filter","CallEventHandler","GroupCallEventHandler","utils","noUnsafeEventProps","replaceParam","safeSet","sleep","Direction","EventTimeline","PushProcessor","AutoDiscovery","olmlib","decodeBase64","encodeBase64","encodeUnpaddedBase64Url","TypedReEmitter","logger","SERVICE_TYPES","ClientPrefix","IdentityPrefix","MatrixError","MatrixHttpApi","MediaPrefix","Method","retryNetworkOperation","Crypto","CryptoEvent","LegacyCryptoEvent","fixBackupKey","isCryptoAvailable","User","UserEvent","getHttpUriForMxc","SearchResult","DEHYDRATION_ALGORITHM","CrossSigningKey","ContentHelpers","NotificationCountType","RoomMemberEvent","EventType","LOCAL_NOTIFICATION_SETTINGS_PREFIX","MSC3912_RELATION_BASED_REDACTIONS_PROP","MsgType","PUSHER_ENABLED","RelationType","RoomCreateTypeField","RoomType","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3088_PURPOSE","UNSTABLE_MSC3089_TREE_SUBTYPE","GuestAccess","HistoryVisibility","Preset","eventMapperFor","randomString","BackupManager","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","MSC3089TreeSpace","SearchOrderBy","PushRuleActionName","PushRuleKind","GroupCall","MediaHandler","TypedEventEmitter","MAIN_ROOM_TIMELINE","ReceiptType","SlidingSyncSdk","determineFeatureSupport","FeatureSupport","Thread","THREAD_RELATION_TYPE","ThreadFilterType","threadFilterTypeToFilter","M_BEACON_INFO","NamespacedValue","UnstableValue","ToDeviceMessageQueue","IgnoredInvites","buildFeatureSupportMap","Feature","ServerSupport","RUST_SDK_STORE_PREFIX","decodeRecoveryKey","ServerSideSecretStorageImpl","MatrixRTCSessionManager","getRelationsThreadFilter","KnownMembership","ServerCapabilities","sha256","keyFromAuthData","SCROLLBACK_DELAY_MS","CRYPTO_ENABLED","TURN_CHECK_INTERVAL","UNSTABLE_MSC3852_LAST_SEEN_UA","PendingEventOrdering","GET_LOGIN_TOKEN_CAPABILITY","UNSTABLE_MSC2666_SHARED_ROOMS","UNSTABLE_MSC2666_MUTUAL_ROOMS","UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS","UNSTABLE_MSC4140_DELAYED_EVENTS","UNSTABLE_MSC4133_EXTENDED_PROFILES","CrossSigningKeyType","EVENT_ID_PREFIX","ClientEvent","SSO_ACTION_PARAM","MatrixClient","constructor","opts","_opts$logger","_opts$usingExternalCr","_this","_opts$cryptoCallbacks","this","_defineProperty","Map","Set","isInitialSyncComplete","callEventHandler","start","groupCallEventHandler","off","Sync","startCallEventHandler","matrixRTC","startMatrixRTC","_this$getRooms","unreadRooms","getRooms","filter","room","getUnreadNotificationCount","Total","currentUserId","getSafeUserId","fixupNotifications","fixupRoomNotifications","baseUrl","ensureNoTrailingSlash","idBaseUrl","identityServer","usingExternalCrypto","store","deviceId","sessionId","userId","credentials","http","fetchFn","accessToken","refreshToken","tokenRefreshFunction","prefix","V3","onlyData","extraParams","queryParams","localTimeoutMs","useAuthorizationHeader","deviceToImport","warn","exportedOlmDeviceToImport","olmDevice","pickleKey","useLivekitForGroupCalls","Boolean","scheduler","setProcessFunction","_ref","_asyncToGenerator","eventToSend","getRoom","getRoomId","status","SENDING","updatePendingEventStatus","res","sendEventHttpRequest","updatePendingEvent","SENT","event_id","_x","apply","arguments","canSupportVoip","on","serverCapabilitiesService","timelineSupport","cryptoStore","verificationMethods","cryptoCallbacks","forceTURN","iceCandidatePoolSize","undefined","supportsCallTransfer","fallbackICEServerAllowed","isVoipWithNoMediaAllowed","useE2eForGroupCall","livekitServiceURL","roomNameGenerator","toDeviceMessageQueue","Decrypted","event","fixNotificationCountOnDecryption","ignoredInvites","_secretStorage","setMaxListeners","newStore","_store","setUserCreator","createUser","startClient","_this2","clientRunning","getUserId","storeUser","checkTurnServersIntervalID","setInterval","checkTurnServers","syncApi","error","stop","getVersions","threads","list","fwdPagination","doesServerSupportThread","setServerSideSupport","setServerSideListSupport","setServerSideFwdPaginationSupport","e","clientOpts","slidingSync","buildSyncApiOptions","sync","catch","info","clientWellKnownPollPeriod","clientWellKnownIntervalID","fetchClientWellKnown","crypto","cryptoBackend","canResetEntireTimeline","roomId","canResetTimelineCallback","stopClient","_this$cryptoBackend","_this$syncApi","_this$peekSync","_this$callEventHandle","_this$groupCallEventH","debug","peekSync","stopPeeking","globalThis","clearInterval","rehydrateDevice","_this3","Error","getDehydrationKey","getDeviceResult","getDehydratedDevice","device_data","device_id","account","Olm","Account","deviceData","algorithm","key","k","unpickle","Uint8Array","rehydrateResult","authedRequest","Post","success","pickledAccount","pickle","sessions","free","_this4","Get","setDehydrationKey","keyInfo","deviceDisplayName","_this5","dehydrationManager","setKeyAndQueueDehydration","createDehydratedDevice","_this6","setKey","dehydrateDevice","exportDevice","_this7","export","clearStores","_this8","promises","push","deleteAllData","deleteRustSdkStore","_ref2","indexedDB","_unused","_loop","dbname","prom","Promise","resolve","reject","concat","req","deleteDatabase","onsuccess","_","onerror","onblocked","all","then","getDomain","replace","getUserIdLocalpart","split","substring","getDeviceId","getSessionId","supportsVoip","getMediaHandler","mediaHandler","setForceTURN","force","setSupportsCallTransfer","support","getUseE2eForGroupCall","createCall","createGroupCall","type","isPtt","intent","dataChannelsEnabled","dataChannelOptions","_this9","getGroupCallForRoom","create","getLivekitServiceURL","setLivekitServiceURL","newURL","waitUntilRoomReadyForGroupCalls","groupCalls","get","getSyncState","_this$syncApi$getSync","_this$syncApi2","getSyncStateData","state","Prepared","Syncing","isGuest","isGuestAccount","setGuest","guest","getScheduler","retryImmediately","_this$syncApi$retryIm","_this$syncApi3","sendQueue","getNotifTimelineSet","notifTimelineSet","setNotifTimelineSet","set","getCapabilities","_this10","caps","getCachedCapabilities","fetchCapabilities","initCrypto","_this11","startup","reEmitter","reEmit","KeyBackupFailed","KeyBackupSessionsRemaining","RoomKeyRequest","RoomKeyRequestCancellation","Warning","DevicesUpdated","WillUpdateDevices","DeviceVerificationChanged","UserTrustStatusChanged","KeysChanged","init","exportedOlmDevice","olmVersion","getOlmVersion","registerEventHandlers","uploadDeviceKeys","initRustCrypto","_arguments","_this12","_this12$pickleKey","args","length","RustCrypto","rustCrypto","secretStorage","storePrefix","useIndexedDB","storeKey","storageKey","storePassphrase","storagePassword","legacyCryptoStore","legacyPickleKey","legacyMigrationProgressListener","progress","total","emit","LegacyCryptoStoreMigrationProgress","setSupportedVerificationMethods","Membership","onRoomMembership","bind","Event","onLiveEventFromSync","VerificationRequestReceived","KeyBackupStatus","KeyBackupDecryptionKeyCached","getCrypto","isCryptoEnabled","getDeviceEd25519Key","_this$crypto$getDevic","_this$crypto","getDeviceCurve25519Key","_this$crypto$getDevic2","_this$crypto2","uploadKeys","_this13","downloadKeys","userIds","forceDownload","getStoredDevicesForUser","getStoredDevice","setDeviceVerified","verified","setDeviceVerification","checkKeyBackup","setDeviceBlocked","blocked","setDeviceKnown","known","_this14","requestVerificationDM","findVerificationRequestDMInProgress","getVerificationRequestsToDeviceInProgress","requestVerification","devices","beginKeyVerification","method","checkSecretStorageKey","checkKey","setGlobalBlacklistUnverifiedDevices","value","globalBlacklistUnverifiedDevices","getGlobalBlacklistUnverifiedDevices","setGlobalErrorOnUnknownDevices","globalErrorOnUnknownDevices","getGlobalErrorOnUnknownDevices","getCrossSigningId","Master","getStoredCrossSigningForUser","checkUserTrust","checkDeviceTrust","checkIfOwnDeviceCrossSigned","checkOwnCrossSigningTrust","checkCrossSigningPrivateKey","privateKey","expectedPublicKey","legacyDeviceVerification","prepareToEncrypt","userHasCrossSigningKeys","isCrossSigningReady","bootstrapCrossSigning","getCryptoTrustCrossSignedDevices","getTrustCrossSignedDevices","setCryptoTrustCrossSignedDevices","val","setTrustCrossSignedDevices","countSessionsNeedingBackup","getEventEncryptionInfo","createRecoveryKeyFromPassphrase","password","isSecretStorageReady","bootstrapSecretStorage","addSecretStorageKey","keyName","addKey","hasSecretStorageKey","keyId","hasKey","storeSecret","name","secret","keys","getSecret","isSecretStored","isStored","requestSecret","getDefaultSecretStorageKeyId","getDefaultKeyId","setDefaultSecretStorageKeyId","setDefaultKeyId","checkSecretStoragePrivateKey","getEventSenderDeviceInfo","_this15","isEventSenderVerified","_this16","device","isVerified","getOutgoingRoomKeyRequest","wireContent","getWireContent","requestBody","session_id","sender_key","room_id","cancelAndResendEventRoomKeyRequest","cancelAndResendKeyRequest","setRoomEncryption","config","isRoomEncrypted","_this$crypto$isRoomEn","_this$crypto3","hasEncryptionStateEvent","encryptAndSendToDevices","userDeviceInfoArr","payload","forceDiscardSession","exportRoomKeys","importRoomKeys","backupManager","getKeyBackupVersion","_this17","errcode","checkBackupVersion","isKeyBackupTrusted","getKeyBackupEnabled","enableKeyBackup","disableKeyBackup","prepareKeyBackupVersion","_arguments2","_this18","secureSecretStorage","auth_data","recovery_key","isKeyBackupKeyStored","createKeyBackupVersion","_this19","data","signObject","getCrossSigningKey","crossSigningInfo","getId","deleteKeyBackupVersion","version","_this20","makeKeyBackupPath","path","encodeUri","$roomId","$sessionId","queryData","sendKeyBackup","_this21","Put","scheduleAllGroupSessionsForBackup","_this22","flagAllGroupSessionsForBackup","isValidRecoveryKey","recoveryKey","_unused2","keyBackupKeyFromPassword","backupInfo","keyBackupKeyFromRecoveryKey","restoreKeyBackupWithPassword","targetRoomId","targetSessionId","_this23","privKey","restoreKeyBackup","restoreKeyBackupWithSecretStorage","_this24","storedKey","fixedKey","getKey","restoreKeyBackupWithRecoveryKey","restoreKeyBackupWithCache","_this25","getSessionBackupPrivateKey","_this26","cacheCompleteCallback","progressCallback","backupVersion","totalKeyCount","totalFailures","totalImported","backupDecryptor","getBackupDecryptor","untrusted","sourceTrusted","storeSessionBackupPrivateKey","stage","rooms","getTotalKeyCount","handleDecryptionOfAFullBackup","_ref3","chunk","importBackedUpRoomKeys","successes","failures","_x2","Object","decryptSessions","checkKeyBackupAndEnable","imported","roomData","values","chunkSize","block","groupChunkCount","chunkGroupByRoom","handleChunkCallback","_ref4","roomChunks","currentChunk","decryptedSessions","_x3","entries","session","sessionsForRoom","deleteKeysFromBackup","_this27","Delete","getMediaConfig","getVisibleRooms","msc3946ProcessDynamicPredecessor","allRooms","replacedRooms","r","_r$findPredecessor","predecessor","findPredecessor","add","tombstone","currentState","getStateEvents","RoomTombstone","has","getUser","getUsers","setAccountData","eventType","content","$userId","$type","getAccountData","getAccountDataFromServer","_this28","getContent","_data","deleteAccountData","_this29","msc3391DeleteAccountDataServerSupport","canSupport","AccountDataDeletion","Unsupported","options","Unstable","getIgnoredUsers","setIgnoredUsers","ignored_users","forEach","u","isUserIgnored","includes","joinRoom","roomIdOrAlias","_arguments3","_this30","syncRoom","hasMembershipState","Join","signPromise","inviteSignUrl","url","URL","searchParams","requestOtherUrl","viaServers","server_name","via","signedInviteObj","third_party_signed","$roomid","resolvedRoom","createRoom","knockRoom","Knock","$roomIdOrAlias","body","reason","resendEvent","encryptAndSendEvent","cancelPendingEvent","QUEUED","NOT_SENT","ENCRYPTING","eventsBeingEncrypted","delete","removeEventFromQueue","CANCELLED","setRoomName","sendStateEvent","RoomName","setRoomTopic","topic","htmlTopic","makeTopicContent","RoomTopic","getRoomTags","setRoomTag","tagName","metadata","$tag","deleteRoomTag","setRoomAccountData","setPowerLevel","powerLevel","_this31","_content","_this31$getRoom","RoomPowerLevels","getStateEvent","deepCopy","users","Array","isArray","user","unstable_createLiveBeacon","beaconInfoContent","_this32","unstable_setLiveBeacon","_this33","sendEvent","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","threadId","txnId","startsWith","addThreadRelationIfNeeded","sendCompleteEvent","_content$mRelates_to","rel_type","_content$mRelates_to2","_this$getRoom","isReply","_objectSpread","is_falling_back","thread","getThread","_thread$lastReply$get","_thread$lastReply","lastReply","ev","isRelation","eventObject","delayOptsOrTxnId","delayOpts","makeTxnId","localEvent","assign","user_id","sender","origin_server_ts","Date","getTime","setThread","Replaced","VisibilityChange","BeforeRedaction","targetId","getAssociatedId","target","getPendingEvents","find","once","LocalEventIdReplaced","updateAssociatedId","getType","setTxnId","setStatus","addPendingEvent","_this34","cancelled","encryptEventIfNeeded","promise","queueEvent","getQueueForEvent","err","_this35","shouldEncryptEventForRoom","encryptEvent","_this36","_this36$cryptoBackend","isEncrypted","Reaction","isRedaction","isEncryptionEnabledInRoom","getEncryptedIfNeededEventType","_this$getRoom2","RoomMessageEncrypted","newStatus","getTxnId","pathParams","$eventType","getWireType","$stateKey","getStateKey","$txnId","isState","pathTemplate","redacts","$redactsEventId","getUnstableDelayQueryOpts","redactEvent","eventId","_eventId","_opts","_opts2","with_rel_types","RelationBasedRedactions","withRelTypesPropName","Stable","stable","unstable","RoomRedaction","sendMessage","RoomMessage","sendContent","sendTextMessage","_threadId","makeTextMessage","sendNotice","_threadId2","makeNotice","sendEmoteMessage","_threadId3","makeEmoteMessage","sendImageMessage","_threadId4","text","msgtype","Image","sendStickerMessage","_threadId5","Sticker","sendHtmlMessage","htmlBody","_threadId6","makeHtmlMessage","sendHtmlNotice","_threadId7","makeHtmlNotice","sendHtmlEmote","_threadId8","makeHtmlEmote","_unstable_sendDelayedEvent","_this37","doesServerSupportUnstableFeature","_unstable_sendDelayedStateEvent","_arguments4","_this38","stateKey","_unstable_getDelayedEvents","fromToken","_this39","queryDict","from","_unstable_updateDelayedEvent","delayId","action","_this40","$delayId","sendReceipt","receiptType","_arguments5","_this41","unthreaded","$receiptType","$eventId","shouldAddThreadId","supportsThreads","fullBody","thread_id","threadIdForReceipt","addLocalEchoReceipt","sendReadReceipt","_arguments6","_this42","Read","hasPendingEvent","setRoomReadMarkers","rmEventId","rrEvent","rpEvent","_this43","rrEventId","rpEventId","ReadPrivate","setRoomReadMarkersHttpRequest","getUrlPreview","ts","Math","floor","parsed","hash","toString","urlPreviewCache","resp","priority","sendTyping","isTyping","timeoutMs","typing","timeout","getRoomUpgradeHistory","verifyLinks","currentRoom","before","findPredecessorRooms","after","findSuccessorRooms","_room$findPredecessor","ret","seenRoomIDs","predecessorRoomId","_room$findPredecessor2","predecessorRoom","splice","tombstoneEvent","successorRoom","_successorRoom$findPr","roomIds","map","ref","size","slice","invite","membershipChange","Invite","inviteByEmail","email","inviteByThreePid","medium","address","_this44","_this44$identityServe","identityServerUrl","getIdentityServerUrl","params","id_server","getAccessToken","identityAccessToken","leave","Leave","leaveRoomChain","includeFuture","upgradeHistory","eligibleToLeave","populationResults","doLeave","ban","Ban","forget","_arguments7","_this45","deleteRoom","$room_id","response","removeRoom","DeleteRoom","unban","kick","membership","$membership","getPushActionsForEvent","forceRecalculate","getPushActions","actions","rule","pushProcessor","actionsAndRuleForEvent","setPushDetails","getPushDetailsForEvent","getPushDetails","setProfileInfo","$info","setDisplayName","_this46","displayname","displayName","DisplayName","events","presence","setAvatarUrl","_this47","avatar_url","avatarUrl","AvatarUrl","mxcUrlToHttp","mxcUrl","width","height","resizeMethod","allowDirectLinks","allowRedirects","useAuthentication","setSyncPresence","_this48","_this48$syncApi","setPresence","_this49","validStates","indexOf","getPresence","scrollback","limit","timeToWaitMs","ongoingScrollbacks","errorTs","timeWaitedMs","now","max","oldState","paginationToken","numAdded","createMessagesRequest","Backward","_res$end","_res$end2","matrixEvents","getEventMapper","stateEvents","setUnknownStateEvents","timelineEvents","threadedEvents","unknownRelations","partitionThreadedEvents","processAggregatedTimelineEvents","addEventsToTimeline","getLiveTimeline","processThreadEvents","relations","aggregateChildEvent","end","storeEvents","getEventTimeline","timelineSet","_this50","_this50$clientOpts","_ref5","_timelineSet$getTimel","_timelineSet$room$fin","getTimelineForEvent","getThreadTimeline","lazyLoadMembers","JSON","stringify","LAZY_LOADING_MESSAGES_FILTER","mapper","events_after","reverse","events_before","timeline","getState","BACKWARDS","addTimeline","initialiseState","FORWARDS","findThreadForEvent","liveTimeline","_this51","_this51$clientOpts","canContain","recurse","RelationsRecursion","hasServerSideSupport","hasServerSideFwdPaginationSupport","_resOlder$next_batch","_resNewer$next_batch","_timelineSet$getTimel2","resOlder","fetchRelations","id","dir","resNewer","Forward","_timelineSet$thread","processEvent","next_batch","originalEvent","fetchRoomEvent","setPaginationToken","_resOlder$next_batch2","eventsNewer","nextBatch","_resNewer$next_batch2","_timelineSet$thread2","getLatestTimeline","_this52","threadListType","_res$chunk","createThreadListMessagesRequest","getFilter","_res$chunk2","_this52$clientOpts","_res2$chunk","messagesPath","_this$clientOpts","timelineFilter","_timelineFilter$getRo","getRoomTimelineFilterComponent","toJSON","_this$clientOpts2","All","include","_timelineFilter$getRo2","hasServerSideListSupport","V1","_res$chunk3","prev_batch","paginateEventTimeline","eventTimeline","_this53","isNotifTimeline","getTimelineSet","backwards","token","getPaginationToken","pendingRequest","paginationRequests","_opts$limit","only","_ref6","next_token","notifications","i","notification","_x4","finally","roomState","processThreadRoots","_eventTimeline$getRoo","_eventTimeline$getRoo2","_ref7","getSender","getEventReadUpTo","newToken","_thread$rootEvent","_eventTimeline$getRoo3","rootEvent","_x5","it","getServerAggregatedRelation","atEnd","resetNotifTimelineSet","resetLiveTimeline","peekInRoom","_this$peekSync2","peek","setGuestAccess","writePromise","RoomGuestAccess","guest_access","allowJoin","CanJoin","Forbidden","readPromise","allowRead","RoomHistoryVisibility","history_visibility","WorldReadable","requestRegisterEmailToken","clientSecret","sendAttempt","nextLink","requestTokenFromEndpoint","client_secret","send_attempt","next_link","requestRegisterMsisdnToken","phoneCountry","phoneNumber","country","phone_number","requestAdd3pidEmailToken","requestAdd3pidMsisdnToken","requestPasswordEmailToken","requestPasswordMsisdnToken","endpoint","_this54","postParams","request","getRoomPushRule","scope","pushRules","_this$pushRules$scope","rule_id","setRoomMutePushRule","mute","hasDontNotifyRule","roomPushRule","DontNotify","deletePushRule","RoomSpecific","addPushRule","deferred","defer","getPushRules","result","err2","searchMessageText","roomEvents","search_term","query","search","search_categories","room_events","searchRoomEvents","term","order_by","Recent","event_context","before_limit","after_limit","include_profile","searchResults","_query","results","highlights","processRoomEventsSearch","backPaginateRoomEventsSearch","searchOpts","abortSignal","_roomEvents$results$l","_roomEvents$results","count","hl","resultsLength","sr","fromJson","context","getEvent","getTimeline","getMember","syncLeftRooms","syncedLeftRooms","syncLeftRoomsPromise","createFilter","filter_id","storeFilter","filterId","allowCached","$filterId","getOrCreateFilter","filterName","_this55","getFilterIdByName","existingId","existingFilter","oldDef","getDefinition","newDef","deepCompare","setFilterIdByName","createdFilter","getOpenIdToken","turnServer","getTurnServers","turnServers","getTurnServersExpiry","turnServersExpiry","pollingTurnServers","_this56","credentialsGood","remainingTime","uris","ttl","servers","urls","username","credential","TurnServers","httpStatus","TurnServersError","setFallbackICEServerAllowed","allow","isFallbackICEServerAllowed","isSynapseAdministrator","admin","whoisSynapseUser","deactivateSynapseUser","_this57","_this57$getDomain","clientWellKnownPromise","getRawClientConfig","clientWellKnown","ClientWellKnown","getClientWellKnown","waitForClientWellKnown","storeClientOptions","primTypes","serializableOpts","_ref8","reduce","obj","_ref9","_unstable_getSharedRooms","_this58","sharedRoomsSupport","mutualRoomsSupport","queryMutualRoomsSupport","tokenQuery","joined","next_batch_token","_this59","serverVersionsPromise","serverVersions","isVersionSupported","_this60","versions","feature","_this61","unstableFeatures","doesServerForceEncryptionForPreset","presetName","_this62","versionsPresetName","_this63","threadUnstable","threadStable","listUnstable","listStable","fwdPaginationUnstable","fwdPaginationStable","_unused3","None","hasLazyLoadMembersEnabled","_this$clientOpts3","setCanResetTimelineCallback","cb","getCanResetTimelineCallback","relationType","_arguments8","_this64","_result$next_batch","_result$prev_batch","fetchedEventType","eventResult","allEvents","decryptEventIfNeeded","Replace","prevBatch","getCrossSigningCacheCallbacks","_this$crypto4","getCacheCallbacks","generateClientSecret","shouldAttemptDecryption","attemptDecryption","isBeingDecrypted","getDecryptionPromise","termsUrlForService","serviceType","IS","getUrl","V2","IM","getHomeserverUrl","_this$idBaseUrl","_this$idBaseUrl2","stripProto","setIdentityServerUrl","setIdBaseUrl","getRefreshToken","_this$http$opts$refre","setAccessToken","isLoggedIn","txnCtr","isUsernameAvailable","available","register","auth","bindThreepids","guestAccessToken","inhibitLogin","refresh_token","guest_access_token","inhibit_login","registerRequest","registerGuest","kind","performRefreshRequestWithPrefix","inhibitLogoutEmit","loginFlows","login","loginType","access_token","loginWithPassword","getCasLoginUrl","redirectUrl","getSsoLoginUrl","idpId","href","loginWithToken","logout","_arguments9","_this65","_this65$crypto","backupPendingKeys","abort","deactivateAccount","erase","requestLoginToken","_this66","getFallbackAuthUrl","authSessionId","$loginType","_this67","_this67$identityServe","invitesNeedingToken","invite_3pid","id_access_token","Experimental","queryString","encodeParams","templatedUrl","$relationType","members","includeMembership","excludeMembership","atEventId","not_membership","at","upgradeRoom","newVersion","new_version","roomInitialSync","_limit$toString","_this68","FullyRead","getJoinedRooms","getJoinedRoomMembers","publicRooms","_ref10","server","since","_objectWithoutProperties","_excluded","createAlias","alias","$alias","deleteAlias","getLocalAliases","getRoomIdForAlias","getRoomDirectoryVisibility","setRoomDirectoryVisibility","visibility","searchUserDirectory","_ref11","uploadContent","file","cancelUpload","upload","getCurrentUploads","getProfileInfo","doesServerSupportExtendedProfiles","_this69","getExtendedProfileRequestPrefix","_this70","getExtendedProfile","_this71","getExtendedProfileProperty","_this72","profile","$key","setExtendedProfileProperty","_this73","deleteExtendedProfileProperty","_this74","patchExtendedProfile","_this75","Patch","setExtendedProfile","_this76","getThreePids","addThreePidOnly","_this77","bindThreePid","_this78","unbindThreePid","_this79","deleteThreePid","setPassword","authDict","newPassword","logoutDevices","new_password","logout_devices","getDevices","getDevice","$device_id","setDeviceDetails","deleteDevice","deleteMultipleDevices","getPushers","_this80","pushers","pusher","hasOwnProperty","setPusher","removePusher","pushKey","appId","pushkey","app_id","setLocalNotificationSettings","notificationSettings","rules","setPushRules","rewriteDefaultRules","updateCachedPushRuleKeys","ruleId","$kind","$ruleId","setPushRuleEnabled","enabled","setPushRuleActions","_ref12","uploadKeysRequest","uploadKeySignatures","downloadKeysForUsers","device_keys","claimOneTimeKeys","keyAlgorithm","queries","one_time_keys","getKeyChanges","oldToken","qps","to","uploadDeviceSigningKeys","registerWithIdentityServer","hsOpenIdToken","uri","requestEmailToken","idServerRequest","requestMsisdnToken","submitMsisdnToken","sid","msisdnToken","submitMsisdnTokenOtherUrl","getIdentityHashDetails","identityHashedLookup","addressPairs","_this81","hashes","localMapping","_ref13","p","addr","toLowerCase","med","hashBuffer","hashed","_x6","unhashed","foundAddresses","mxid","plainAddress","lookupThreePid","_this82","mapping","bulkLookupThreePids","_this83","v1results","_loop2","originalQuery","threepids","getIdentityAccount","sendToDevice","contentMap","messages","recursiveMapToObject","targets","deviceMessages","queueToDevice","batch","queueBatch","getThirdpartyProtocols","getThirdpartyLocation","protocol","$protocol","getThirdpartyUser","getTerms","agreeToTerms","termsUrls","headers","Authorization","user_accepts","reportEvent","score","getRoomHierarchy","maxDepth","suggestedOnly","suggested_only","String","max_depth","unstableCreateFileTree","_this84","preset","PrivateChat","power_level_content_override","creation_content","Space","initial_state","state_key","RoomEncryption","MEGOLM_ALGORITHM","unstableGetFileTreeSpace","_purposeEvent$getCont","_createEvent$getConte","getMyMembership","createEvent","RoomCreate","purposeEvent","proxyBaseUrl","pos","clientTimeout","_this$clientOpts4","threadSupport","supportsIntentionalMentions","IntentionalMentions","getRoomSummary","_this85","paramOpts","toStartOfTimeline","processThreadedEvents","processBeaconEvents","processPollEvents","whoami","_this86","timestampToEvent","timestamp","_this87","getAuthIssuer","_this88","fromEntries","_ref14","v","cli","_actions$tweaks","ourUserId","findEventById","isThreadEvent","threadRootId","isThreadRoot","hasReadEvent","hasUserReadEvent","newHighlight","tweaks","highlight","newCount","getUnreadCountForEventContext","Highlight","setThreadUnreadNotificationCount","setUnreadNotificationCount","newNotify","notify","inMainTimelineForReceipt","isRelatedToRoot","relationEventId"],"sources":["../src/client.ts"],"sourcesContent":["/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport type { IDeviceKeys, IMegolmSessionData, IOneTimeKey } from \"./@types/crypto.ts\";\nimport { ISyncStateData, SetPresence, SyncApi, SyncApiOptions, SyncState } from \"./sync.ts\";\nimport {\n EventStatus,\n IContent,\n IDecryptOptions,\n IEvent,\n MatrixEvent,\n MatrixEventEvent,\n MatrixEventHandlerMap,\n PushDetails,\n} from \"./models/event.ts\";\nimport { StubStore } from \"./store/stub.ts\";\nimport { CallEvent, CallEventHandlerMap, createNewMatrixCall, MatrixCall, supportsMatrixCall } from \"./webrtc/call.ts\";\nimport { Filter, IFilterDefinition, IRoomEventFilter } from \"./filter.ts\";\nimport { CallEventHandler, CallEventHandlerEvent, CallEventHandlerEventHandlerMap } from \"./webrtc/callEventHandler.ts\";\nimport {\n GroupCallEventHandler,\n GroupCallEventHandlerEvent,\n GroupCallEventHandlerEventHandlerMap,\n} from \"./webrtc/groupCallEventHandler.ts\";\nimport * as utils from \"./utils.ts\";\nimport { noUnsafeEventProps, QueryDict, replaceParam, safeSet, sleep } from \"./utils.ts\";\nimport { Direction, EventTimeline } from \"./models/event-timeline.ts\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor.ts\";\nimport { AutoDiscovery, AutoDiscoveryAction } from \"./autodiscovery.ts\";\nimport * as olmlib from \"./crypto/olmlib.ts\";\nimport { decodeBase64, encodeBase64, encodeUnpaddedBase64Url } from \"./base64.ts\";\nimport { IExportedDevice as IExportedOlmDevice } from \"./crypto/OlmDevice.ts\";\nimport { IOlmDevice } from \"./crypto/algorithms/megolm.ts\";\nimport { TypedReEmitter } from \"./ReEmitter.ts\";\nimport { IRoomEncryption } from \"./crypto/RoomList.ts\";\nimport { logger, Logger } from \"./logger.ts\";\nimport { SERVICE_TYPES } from \"./service-types.ts\";\nimport {\n Body,\n ClientPrefix,\n FileType,\n HttpApiEvent,\n HttpApiEventHandlerMap,\n HTTPError,\n IdentityPrefix,\n IHttpOpts,\n IRequestOpts,\n MatrixError,\n MatrixHttpApi,\n MediaPrefix,\n Method,\n retryNetworkOperation,\n TokenRefreshFunction,\n Upload,\n UploadOpts,\n UploadResponse,\n} from \"./http-api/index.ts\";\nimport {\n Crypto,\n CryptoEvent as LegacyCryptoEvent,\n CryptoEventHandlerMap as LegacyCryptoEventHandlerMap,\n fixBackupKey,\n ICheckOwnCrossSigningTrustOpts,\n IRoomKeyRequestBody,\n isCryptoAvailable,\n} from \"./crypto/index.ts\";\nimport { DeviceInfo } from \"./crypto/deviceinfo.ts\";\nimport { User, UserEvent, UserEventHandlerMap } from \"./models/user.ts\";\nimport { getHttpUriForMxc } from \"./content-repo.ts\";\nimport { SearchResult } from \"./models/search-result.ts\";\nimport { DEHYDRATION_ALGORITHM, IDehydratedDevice, IDehydratedDeviceKeyInfo } from \"./crypto/dehydration.ts\";\nimport {\n IKeyBackupInfo,\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupRoomSessions,\n IKeyBackupSession,\n} from \"./crypto/keybackup.ts\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./models/beacon.ts\";\nimport { AuthDict } from \"./interactive-auth.ts\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent } from \"./sync-accumulator.ts\";\nimport { CrossSigningKey, ICreateSecretStorageOpts, IEncryptedEventInfo, IRecoveryKey } from \"./crypto/api.ts\";\nimport { EventTimelineSet } from \"./models/event-timeline-set.ts\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest.ts\";\nimport { VerificationBase as Verification } from \"./crypto/verification/Base.ts\";\nimport * as ContentHelpers from \"./content-helpers.ts\";\nimport { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from \"./crypto/CrossSigning.ts\";\nimport { NotificationCountType, Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from \"./models/room.ts\";\nimport { RoomMemberEvent, RoomMemberEventHandlerMap } from \"./models/room-member.ts\";\nimport { IPowerLevelsContent, RoomStateEvent, RoomStateEventHandlerMap } from \"./models/room-state.ts\";\nimport {\n DelayedEventInfo,\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n IContextResponse,\n ICreateRoomOpts,\n IEventSearchOpts,\n IFilterResponse,\n IGuestAccessOpts,\n IJoinRoomOpts,\n INotificationsResponse,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRelationsRequestOpts,\n IRelationsResponse,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IStatusResponse,\n ITagsResponse,\n KnockRoomOpts,\n SendDelayedEventRequestOpts,\n SendDelayedEventResponse,\n UpdateDelayedEventAction,\n} from \"./@types/requests.ts\";\nimport {\n EventType,\n LOCAL_NOTIFICATION_SETTINGS_PREFIX,\n MSC3912_RELATION_BASED_REDACTIONS_PROP,\n MsgType,\n PUSHER_ENABLED,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n StateEvents,\n TimelineEvents,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event.ts\";\nimport {\n GuestAccess,\n HistoryVisibility,\n IdServerUnbindResult,\n JoinRule,\n Preset,\n Visibility,\n} from \"./@types/partials.ts\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper.ts\";\nimport { randomString } from \"./randomstring.ts\";\nimport { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup.ts\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace.ts\";\nimport { ISignatures } from \"./@types/signed.ts\";\nimport { IStore } from \"./store/index.ts\";\nimport { ISecretRequest } from \"./crypto/SecretStorage.ts\";\nimport {\n IEventWithRoomId,\n ISearchRequestBody,\n ISearchResponse,\n ISearchResults,\n IStateEventWithRoomId,\n SearchOrderBy,\n} from \"./@types/search.ts\";\nimport { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from \"./@types/synapse.ts\";\nimport { IHierarchyRoom } from \"./@types/spaces.ts\";\nimport {\n IPusher,\n IPusherRequest,\n IPushRule,\n IPushRules,\n PushRuleAction,\n PushRuleActionName,\n PushRuleKind,\n RuleId,\n} from \"./@types/PushRules.ts\";\nimport { IThreepid } from \"./@types/threepids.ts\";\nimport { CryptoStore, OutgoingRoomKeyRequest } from \"./crypto/store/base.ts\";\nimport { GroupCall, GroupCallIntent, GroupCallType, IGroupCallDataChannelOptions } from \"./webrtc/groupCall.ts\";\nimport { MediaHandler } from \"./webrtc/mediaHandler.ts\";\nimport {\n ILoginFlowsResponse,\n IRefreshTokenResponse,\n LoginRequest,\n LoginResponse,\n LoginTokenPostResponse,\n SSOAction,\n} from \"./@types/auth.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts.ts\";\nimport { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from \"./sliding-sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport {\n determineFeatureSupport,\n FeatureSupport,\n Thread,\n THREAD_RELATION_TYPE,\n ThreadFilterType,\n threadFilterTypeToFilter,\n} from \"./models/thread.ts\";\nimport { M_BEACON_INFO, MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { NamespacedValue, UnstableValue } from \"./NamespacedValue.ts\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue.ts\";\nimport { ToDeviceBatch } from \"./models/ToDeviceMessage.ts\";\nimport { IgnoredInvites } from \"./models/invites-ignorer.ts\";\nimport { UIARequest, UIAResponse } from \"./@types/uia.ts\";\nimport { LocalNotificationSettings } from \"./@types/local_notifications.ts\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature.ts\";\nimport { BackupDecryptor, CryptoBackend } from \"./common-crypto/CryptoBackend.ts\";\nimport { RUST_SDK_STORE_PREFIX } from \"./rust-crypto/constants.ts\";\nimport {\n BootstrapCrossSigningOpts,\n CrossSigningKeyInfo,\n CryptoApi,\n decodeRecoveryKey,\n ImportRoomKeysOpts,\n CryptoEvent,\n CryptoEventHandlerMap,\n CryptoCallbacks,\n} from \"./crypto-api/index.ts\";\nimport { DeviceInfoMap } from \"./crypto/DeviceList.ts\";\nimport {\n AddSecretStorageKeyOpts,\n SecretStorageKeyDescription,\n ServerSideSecretStorage,\n ServerSideSecretStorageImpl,\n} from \"./secret-storage.ts\";\nimport { RegisterRequest, RegisterResponse } from \"./@types/registration.ts\";\nimport { MatrixRTCSessionManager } from \"./matrixrtc/MatrixRTCSessionManager.ts\";\nimport { getRelationsThreadFilter } from \"./thread-utils.ts\";\nimport { KnownMembership, Membership } from \"./@types/membership.ts\";\nimport { RoomMessageEventContent, StickerEventContent } from \"./@types/events.ts\";\nimport { ImageInfo } from \"./@types/media.ts\";\nimport { Capabilities, ServerCapabilities } from \"./serverCapabilities.ts\";\nimport { sha256 } from \"./digest.ts\";\nimport { keyFromAuthData } from \"./common-crypto/key-passphrase.ts\";\n\nexport type Store = IStore;\n\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\nexport const CRYPTO_ENABLED: boolean = isCryptoAvailable();\nconst TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes\n\nexport const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\n \"last_seen_user_agent\",\n \"org.matrix.msc3852.last_seen_user_agent\",\n);\n\ninterface IExportedDevice {\n olmDevice: IExportedOlmDevice;\n userId: string;\n deviceId: string;\n}\n\nexport interface IKeysUploadResponse {\n one_time_key_counts: {\n // eslint-disable-line camelcase\n [algorithm: string]: number;\n };\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * A store to be used for end-to-end crypto session data.\n * The `createClient` helper will create a default store if needed. Calls the factory supplied to\n * {@link setCryptoStoreFactory} if unspecified; or if no factory has been\n * specified, uses a default implementation (indexeddb in the browser,\n * in-memory otherwise).\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n cryptoStore?: CryptoStore;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP requests.\n * Most supported environments have a global `fetch` registered to which this will fall back.\n */\n fetchFn?: typeof globalThis.fetch;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n refreshToken?: string;\n\n /**\n * Function used to attempt refreshing access and refresh tokens\n * Called by http-api when a possibly expired token is encountered\n * and a refreshToken is found\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to false to send the access token to the server via a query parameter rather\n * than the Authorization HTTP header.\n *\n * Note that as of v1.11 of the Matrix spec, sending the access token via a query\n * is deprecated.\n *\n * Default true.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support, see {@link MatrixClient#getEventTimeline}.\n * It is disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * `?user_id=`.\n */\n queryParams?: Record<string, string>;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}.\n *\n * This must be set to the same value every time the client is initialised for the same device.\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n pickleKey?: string;\n\n /**\n * Verification methods we should offer to the other side when performing an interactive verification.\n * If unset, we will offer all known methods. Currently these are: showing a QR code, scanning a QR code, and SAS\n * (aka \"emojis\").\n *\n * See {@link types.VerificationMethod} for a set of useful constants for this parameter.\n */\n verificationMethods?: Array<string>;\n\n /**\n * Whether relaying calls through a TURN server should be forced. Default false.\n */\n forceTURN?: boolean;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * True to advertise support for call transfers to other parties on Matrix calls. Default false.\n */\n supportsCallTransfer?: boolean;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n /**\n * If true, to-device signalling for group calls will be encrypted\n * with Olm. Default: true.\n */\n useE2eForGroupCall?: boolean;\n\n livekitServiceURL?: string;\n\n /**\n * Crypto callbacks provided by the application\n */\n cryptoCallbacks?: CryptoCallbacks;\n\n /**\n * Method to generate room names for empty rooms and rooms names based on membership.\n * Defaults to a built-in English handler with basic pluralisation.\n */\n roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;\n\n /**\n * If true, participant can join group call without video and audio this has to be allowed. By default, a local\n * media stream is needed to establish a group call.\n * Default: false.\n */\n isVoipWithNoMediaAllowed?: boolean;\n\n /**\n * If true, group calls will not establish media connectivity and only create the signaling events,\n * so that livekit media can be used in the application layert (js-sdk contains no livekit code).\n */\n useLivekitForGroupCalls?: boolean;\n\n /**\n * A logger to associate with this MatrixClient.\n * Defaults to the built-in global logger.\n */\n logger?: Logger;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event `limit=` to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put `archived=true</code> on the <code>/initialSync` request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"<b>chronological</b>\", messages will\n * appear in the timeline when the call to `sendEvent` was made. If \"<b>detached</b>\",\n * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n\n /**\n * Will organises events in threaded conversations when\n * a thread relation is encountered\n */\n threadSupport?: boolean;\n\n /**\n * @experimental\n */\n slidingSync?: SlidingSync;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts {}\n\nexport const GET_LOGIN_TOKEN_CAPABILITY = new NamespacedValue(\n \"m.get_login_token\",\n \"org.matrix.msc3882.get_login_token\",\n);\n\nexport const UNSTABLE_MSC2666_SHARED_ROOMS = \"uk.half-shot.msc2666\";\nexport const UNSTABLE_MSC2666_MUTUAL_ROOMS = \"uk.half-shot.msc2666.mutual_rooms\";\nexport const UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = \"uk.half-shot.msc2666.query_mutual_rooms\";\n\nexport const UNSTABLE_MSC4140_DELAYED_EVENTS = \"org.matrix.msc4140\";\n\nexport const UNSTABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133\";\n\nenum CrossSigningKeyType {\n MasterKey = \"master_key\",\n SelfSigningKey = \"self_signing_key\",\n UserSigningKey = \"user_signing_key\",\n}\n\nexport type CrossSigningKeys = Record<CrossSigningKeyType, CrossSigningKeyInfo>;\n\nexport type SendToDeviceContentMap = Map<string, Map<string, Record<string, any>>>;\n\nexport interface ISignedKey {\n keys: Record<string, string>;\n signatures: ISignatures;\n user_id: string;\n algorithms: string[];\n device_id: string;\n}\n\nexport type KeySignatures = Record<string, Record<string, CrossSigningKeyInfo | ISignedKey>>;\nexport interface IUploadKeySignaturesResponse {\n failures: Record<\n string,\n Record<\n string,\n {\n errcode: string;\n error: string;\n }\n >\n >;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: undefined | string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\nexport interface ITurnServerResponse {\n uris: string[];\n username: string;\n password: string;\n ttl: number;\n}\n\nexport interface ITurnServer {\n urls: string[];\n username: string;\n credential: string;\n}\n\nexport interface IServerVersions {\n versions: string[];\n unstable_features: Record<string, boolean>;\n}\n\nexport interface IClientWellKnown {\n [key: string]: any;\n \"m.homeserver\"?: IWellKnownConfig;\n \"m.identity_server\"?: IWellKnownConfig;\n}\n\nexport interface IWellKnownConfig<T = IClientWellKnown> {\n raw?: T;\n action?: AutoDiscoveryAction;\n reason?: string;\n error?: Error | string;\n // eslint-disable-next-line\n base_url?: string | null;\n // XXX: this is undocumented\n server_name?: string;\n}\n\ninterface IKeyBackupPath {\n path: string;\n queryData?: {\n version: string;\n };\n}\n\ninterface IMediaConfig {\n [key: string]: any; // extensible\n \"m.upload.size\"?: number;\n}\n\ninterface IThirdPartySigned {\n sender: string;\n mxid: string;\n token: string;\n signatures: ISignatures;\n}\n\ninterface IJoinRequestBody {\n third_party_signed?: IThirdPartySigned;\n}\n\ninterface ITagMetadata {\n [key: string]: any;\n order?: number;\n}\n\ninterface IMessagesResponse {\n start?: string;\n end?: string;\n chunk: IRoomEvent[];\n state?: IStateEvent[];\n}\n\ninterface IThreadedMessagesResponse {\n prev_batch: string;\n next_batch: string;\n chunk: IRoomEvent[];\n state: IStateEvent[];\n}\n\nexport interface IRequestTokenResponse {\n sid: string;\n submit_url?: string;\n}\n\nexport interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {\n msisdn: string;\n success: boolean;\n intl_fmt: string;\n}\n\nexport interface IUploadKeysRequest {\n \"device_keys\"?: Required<IDeviceKeys>;\n \"one_time_keys\"?: Record<string, IOneTimeKey>;\n \"org.matrix.msc2732.fallback_keys\"?: Record<string, IOneTimeKey>;\n}\n\nexport interface IQueryKeysRequest {\n device_keys: { [userId: string]: string[] };\n timeout?: number;\n token?: string;\n}\n\nexport interface IClaimKeysRequest {\n one_time_keys: { [userId: string]: { [deviceId: string]: string } };\n timeout?: number;\n}\n\nexport interface IOpenIDToken {\n access_token: string;\n token_type: \"Bearer\" | string;\n matrix_server_name: string;\n expires_in: number;\n}\n\ninterface IRoomInitialSyncResponse {\n room_id: string;\n membership: Membership;\n messages?: {\n start?: string;\n end?: string;\n chunk: IEventWithRoomId[];\n };\n state?: IStateEventWithRoomId[];\n visibility: Visibility;\n account_data?: IMinimalEvent[];\n presence: Partial<IEvent>; // legacy and undocumented, api is deprecated so this won't get attention\n}\n\ninterface IJoinedRoomsResponse {\n joined_rooms: string[];\n}\n\ninterface IJoinedMembersResponse {\n joined: {\n [userId: string]: {\n display_name: string;\n avatar_url: string;\n };\n };\n}\n\n// Re-export for backwards compatibility\nexport type IRegisterRequestParams = RegisterRequest;\n\nexport interface IPublicRoomsChunkRoom {\n room_id: string;\n name?: string;\n avatar_url?: string;\n topic?: string;\n canonical_alias?: string;\n aliases?: string[];\n world_readable: boolean;\n guest_can_join: boolean;\n num_joined_members: number;\n room_type?: RoomType | string; // Added by MSC3827\n join_rule?: JoinRule.Knock | JoinRule.Public; // Added by MSC2403\n}\n\ninterface IPublicRoomsResponse {\n chunk: IPublicRoomsChunkRoom[];\n next_batch?: string;\n prev_batch?: string;\n total_room_count_estimate?: number;\n}\n\ninterface IUserDirectoryResponse {\n results: {\n user_id: string;\n display_name?: string;\n avatar_url?: string;\n }[];\n limited: boolean;\n}\n\nexport interface IMyDevice {\n \"device_id\": string;\n \"display_name\"?: string;\n \"last_seen_ip\"?: string;\n \"last_seen_ts\"?: number;\n // UNSTABLE_MSC3852_LAST_SEEN_UA\n \"last_seen_user_agent\"?: string;\n \"org.matrix.msc3852.last_seen_user_agent\"?: string;\n}\n\nexport interface Keys {\n keys: { [keyId: string]: string };\n usage: string[];\n user_id: string;\n}\n\nexport interface SigningKeys extends Keys {\n signatures: ISignatures;\n}\n\nexport interface DeviceKeys {\n [deviceId: string]: IDeviceKeys & {\n unsigned?: {\n device_display_name: string;\n };\n };\n}\n\nexport interface IDownloadKeyResult {\n failures: { [serverName: string]: object };\n device_keys: { [userId: string]: DeviceKeys };\n // the following three fields were added in 1.1\n master_keys?: { [userId: string]: Keys };\n self_signing_keys?: { [userId: string]: SigningKeys };\n user_signing_keys?: { [userId: string]: SigningKeys };\n}\n\nexport interface IClaimOTKsResult {\n failures: { [serverName: string]: object };\n one_time_keys: {\n [userId: string]: {\n [deviceId: string]: {\n [keyId: string]: {\n key: string;\n signatures: ISignatures;\n };\n };\n };\n };\n}\n\nexport interface IFieldType {\n regexp: string;\n placeholder: string;\n}\n\nexport interface IInstance {\n desc: string;\n icon?: string;\n fields: object;\n network_id: string;\n // XXX: this is undocumented but we rely on it: https://github.com/matrix-org/matrix-doc/issues/3203\n instance_id: string;\n}\n\nexport interface IProtocol {\n user_fields: string[];\n location_fields: string[];\n icon: string;\n field_types: Record<string, IFieldType>;\n instances: IInstance[];\n}\n\ninterface IThirdPartyLocation {\n alias: string;\n protocol: string;\n fields: object;\n}\n\ninterface IThirdPartyUser {\n userid: string;\n protocol: string;\n fields: object;\n}\n\n/**\n * The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n */\nexport interface RoomSummary extends Omit<IPublicRoomsChunkRoom, \"canonical_alias\" | \"aliases\"> {\n /**\n * The current membership of this user in the room.\n * Usually \"leave\" if the room is fetched over federation.\n */\n \"membership\"?: Membership;\n /**\n * Version of the room.\n */\n \"im.nheko.summary.room_version\"?: string;\n /**\n * The encryption algorithm used for this room, if the room is encrypted.\n */\n \"im.nheko.summary.encryption\"?: string;\n}\n\ninterface IRoomKeysResponse {\n sessions: IKeyBackupRoomSessions;\n}\n\ninterface IRoomsKeysResponse {\n rooms: Record<string, IRoomKeysResponse>;\n}\n\ninterface IRoomHierarchy {\n rooms: IHierarchyRoom[];\n next_batch?: string;\n}\n\nexport interface TimestampToEventResponse {\n event_id: string;\n origin_server_ts: number;\n}\n\ninterface IWhoamiResponse {\n user_id: string;\n device_id?: string;\n is_guest?: boolean;\n}\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nconst EVENT_ID_PREFIX = \"$\";\n\nexport enum ClientEvent {\n Sync = \"sync\",\n Event = \"event\",\n ToDeviceEvent = \"toDeviceEvent\",\n AccountData = \"accountData\",\n Room = \"Room\",\n DeleteRoom = \"deleteRoom\",\n SyncUnexpectedError = \"sync.unexpectedError\",\n ClientWellKnown = \"WellKnown.client\",\n ReceivedVoipEvent = \"received_voip_event\",\n UndecryptableToDeviceEvent = \"toDeviceEvent.undecryptable\",\n TurnServers = \"turnServers\",\n TurnServersError = \"turnServers.error\",\n}\n\ntype RoomEvents =\n | RoomEvent.Name\n | RoomEvent.Redaction\n | RoomEvent.RedactionCancelled\n | RoomEvent.Receipt\n | RoomEvent.Tags\n | RoomEvent.LocalEchoUpdated\n | RoomEvent.HistoryImportedWithinTimeline\n | RoomEvent.AccountData\n | RoomEvent.MyMembership\n | RoomEvent.Timeline\n | RoomEvent.TimelineReset;\n\ntype RoomStateEvents =\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker;\n\ntype LegacyCryptoEvents =\n | LegacyCryptoEvent.KeySignatureUploadFailure\n | LegacyCryptoEvent.KeyBackupStatus\n | LegacyCryptoEvent.KeyBackupFailed\n | LegacyCryptoEvent.KeyBackupSessionsRemaining\n | LegacyCryptoEvent.KeyBackupDecryptionKeyCached\n | LegacyCryptoEvent.RoomKeyRequest\n | LegacyCryptoEvent.RoomKeyRequestCancellation\n | LegacyCryptoEvent.VerificationRequest\n | LegacyCryptoEvent.VerificationRequestReceived\n | LegacyCryptoEvent.DeviceVerificationChanged\n | LegacyCryptoEvent.UserTrustStatusChanged\n | LegacyCryptoEvent.KeysChanged\n | LegacyCryptoEvent.Warning\n | LegacyCryptoEvent.DevicesUpdated\n | LegacyCryptoEvent.WillUpdateDevices\n | LegacyCryptoEvent.LegacyCryptoStoreMigrationProgress;\n\ntype CryptoEvents = (typeof CryptoEvent)[keyof typeof CryptoEvent];\n\ntype MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;\n\ntype RoomMemberEvents =\n | RoomMemberEvent.Name\n | RoomMemberEvent.Typing\n | RoomMemberEvent.PowerLevel\n | RoomMemberEvent.Membership;\n\ntype UserEvents =\n | UserEvent.AvatarUrl\n | UserEvent.DisplayName\n | UserEvent.Presence\n | UserEvent.CurrentlyActive\n | UserEvent.LastPresenceTs;\n\nexport type EmittedEvents =\n | ClientEvent\n | RoomEvents\n | RoomStateEvents\n | LegacyCryptoEvents\n | CryptoEvents\n | MatrixEventEvents\n | RoomMemberEvents\n | UserEvents\n | CallEvent // re-emitted by call.ts using Object.values\n | CallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Outgoing\n | GroupCallEventHandlerEvent.Ended\n | GroupCallEventHandlerEvent.Participants\n | HttpApiEvent.SessionLoggedOut\n | HttpApiEvent.NoConsent\n | BeaconEvent;\n\nexport type ClientEventHandlerMap = {\n /**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n * <ul>\n *\n * <li>PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n * previous API.</i></li>\n *\n * <li>CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.</li>\n *\n * <li>SYNCING : The client is currently polling for new events from the server.\n * This will be called <i>after</i> processing latest events from a sync.</li>\n *\n * <li>ERROR : The client has had a problem syncing with the server. If this is\n * called <i>before</i> PREPARED then there was a problem performing the initial\n * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n * API.</i></li>\n *\n * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n * </li>\n *\n * <li>STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n * </li>\n * </ul>\n * State transition diagram:\n * ```\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * ```\n * Transitions:\n * <ul>\n *\n * <li>`null -> PREPARED` : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n * <li>`null -> ERROR` : Occurs when the initial sync failed first time.\n *\n * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds\n * after previously failing.\n *\n * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.\n *\n * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n *\n * <li>`ERROR -> SYNCING` : Occurs when the client has performed a\n * live update after having previously failed.\n *\n * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive\n * for a second time or more.</li>\n *\n * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live\n * update. This is called <i>after</i> processing.</li>\n *\n * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.</li>\n * </ul>\n *\n * @param state - An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param prevState - An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n *\n * @param data - Data about this transition.\n *\n * @example\n * ```\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n * ```\n */\n [ClientEvent.Sync]: (state: SyncState, prevState: SyncState | null, data?: ISyncStateData) => void;\n /**\n * Fires whenever the SDK receives a new event.\n * <p>\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.Event]: (event: MatrixEvent) => void;\n /**\n * Fires whenever the SDK receives a new to-device event.\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires if a to-device event is received that cannot be decrypted.\n * Encrypted to-device events will (generally) use plain Olm encryption,\n * in which case decryption failures are fatal: the event will never be\n * decryptable, unlike Megolm encrypted events where the key may simply\n * arrive later.\n *\n * An undecryptable to-device event is therefore likley to indicate problems.\n *\n * @param event - The undecyptable to-device event\n */\n [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires whenever new user-scoped account_data is added.\n * @param event - The event describing the account_data just added\n * @param event - The previous account data, if known.\n * @example\n * ```\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n * ```\n */\n [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. <strong>This event is experimental and\n * may change.</strong>\n * @param room - The newly created, fully populated room.\n * @example\n * ```\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n * ```\n */\n [ClientEvent.Room]: (room: Room) => void;\n /**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * <strong>This event is experimental and may change.</strong>\n * @param roomId - The deleted room ID.\n * @example\n * ```\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n * ```\n */\n [ClientEvent.DeleteRoom]: (roomId: string) => void;\n [ClientEvent.SyncUnexpectedError]: (error: Error) => void;\n /**\n * Fires when the client .well-known info is fetched.\n *\n * @param data - The JSON object returned by the server\n */\n [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;\n [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;\n [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;\n [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;\n} & RoomEventHandlerMap &\n RoomStateEventHandlerMap &\n LegacyCryptoEventHandlerMap &\n CryptoEventHandlerMap &\n MatrixEventHandlerMap &\n RoomMemberEventHandlerMap &\n UserEventHandlerMap &\n CallEventHandlerEventHandlerMap &\n GroupCallEventHandlerEventHandlerMap &\n CallEventHandlerMap &\n HttpApiEventHandlerMap &\n BeaconEventHandlerMap;\n\nconst SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = \"RESTORE_BACKUP_ERROR_BAD_KEY\";\n\n private readonly logger: Logger;\n\n public reEmitter = new TypedReEmitter<EmittedEvents, ClientEventHandlerMap>(this);\n public olmVersion: [number, number, number] | null = null; // populated after initCrypto\n public usingExternalCrypto = false;\n private _store!: Store;\n public deviceId: string | null;\n public credentials: { userId: string | null };\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.\n *\n * As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.\n *\n * If unset, either a hardcoded key or no encryption at all is used, depending on the Crypto implementation.\n *\n * @deprecated this should be a private property.\n */\n public pickleKey?: string;\n\n public scheduler?: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse> } = {};\n public identityServer?: IIdentityServerProvider;\n public http: MatrixHttpApi<IHttpOpts & { onlyData: true }>; // XXX: Intended private, used in code.\n\n /**\n * The libolm crypto implementation, if it is in use.\n *\n * @deprecated This should not be used. Instead, use the methods exposed directly on this class or\n * (where they are available) via {@link getCrypto}.\n */\n public crypto?: Crypto; // XXX: Intended private, used in code. Being replaced by cryptoBackend\n\n private cryptoBackend?: CryptoBackend; // one of crypto or rustCrypto\n public cryptoCallbacks: CryptoCallbacks; // XXX: Intended private, used in code.\n public callEventHandler?: CallEventHandler; // XXX: Intended private, used in code.\n public groupCallEventHandler?: GroupCallEventHandler;\n public supportsCallTransfer = false; // XXX: Intended private, used in code.\n public forceTURN = false; // XXX: Intended private, used in code.\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl?: string;\n public baseUrl: string;\n public readonly isVoipWithNoMediaAllowed;\n\n public useLivekitForGroupCalls: boolean;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected canSupportVoip = false;\n protected peekSync: SyncApi | null = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number } } = {};\n protected notifTimelineSet: EventTimelineSet | null = null;\n /* @deprecated */\n protected cryptoStore?: CryptoStore;\n protected verificationMethods?: string[];\n protected fallbackICEServerAllowed = false;\n protected syncApi?: SlidingSyncSdk | SyncApi;\n public roomNameGenerator?: ICreateClientOpts[\"roomNameGenerator\"];\n public pushRules?: IPushRules;\n protected syncLeftRoomsPromise?: Promise<Room[]>;\n protected syncedLeftRooms = false;\n protected clientOpts?: IStoredClientOpts;\n protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>;\n protected canResetTimelineCallback?: ResetTimelineCallback;\n\n public canSupport = new Map<Feature, ServerSupport>();\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise?: Promise<IServerVersions>;\n\n protected clientWellKnown?: IClientWellKnown;\n protected clientWellKnownPromise?: Promise<IClientWellKnown>;\n protected turnServers: ITurnServer[] = [];\n protected turnServersExpiry = 0;\n protected checkTurnServersIntervalID?: ReturnType<typeof setInterval>;\n protected exportedOlmDeviceToImport?: IExportedOlmDevice;\n protected txnCtr = 0;\n protected mediaHandler = new MediaHandler(this);\n protected sessionId: string;\n\n /** IDs of events which are currently being encrypted.\n *\n * This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,\n * that tells us that it has been cancelled, and we should not send it.\n */\n private eventsBeingEncrypted = new Set<string>();\n\n private useE2eForGroupCall = true;\n private toDeviceMessageQueue: ToDeviceMessageQueue;\n public livekitServiceURL?: string;\n\n private _secretStorage: ServerSideSecretStorageImpl;\n\n // A manager for determining which invites should be ignored.\n public readonly ignoredInvites: IgnoredInvites;\n\n public readonly matrixRTC: MatrixRTCSessionManager;\n\n private serverCapabilitiesService: ServerCapabilities;\n\n public constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n // If a custom logger is provided, use it. Otherwise, default to the global\n // one in logger.ts.\n this.logger = opts.logger ?? logger;\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n this.identityServer = opts.identityServer;\n\n this.usingExternalCrypto = opts.usingExternalCrypto ?? false;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n this.sessionId = randomString(10);\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this as ConstructorParameters<typeof MatrixHttpApi>[0], {\n fetchFn: opts.fetchFn,\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n refreshToken: opts.refreshToken,\n tokenRefreshFunction: opts.tokenRefreshFunction,\n prefix: ClientPrefix.V3,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n logger: this.logger,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n this.logger.warn(\n \"not importing device because device ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (this.credentials.userId) {\n this.logger.warn(\n \"not importing device because user ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (!opts.deviceToImport.deviceId) {\n this.logger.warn(\"not importing device because no device ID in exported data\");\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n // will be used during async initialization of the crypto\n this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend: MatrixEvent) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n if (supportsMatrixCall()) {\n this.callEventHandler = new CallEventHandler(this);\n this.groupCallEventHandler = new GroupCallEventHandler(this);\n this.canSupportVoip = true;\n // Start listening for calls after the initial sync is done\n // We do not need to backfill the call event buffer\n // with encrypted events that might never get decrypted\n this.on(ClientEvent.Sync, this.startCallEventHandler);\n }\n\n // NB. We initialise MatrixRTC whether we have call support or not: this is just\n // the underlying session management and doesn't use any actual media capabilities\n this.matrixRTC = new MatrixRTCSessionManager(this);\n\n this.serverCapabilitiesService = new ServerCapabilities(this.http);\n\n this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n\n this.cryptoStore = opts.cryptoStore;\n this.verificationMethods = opts.verificationMethods;\n this.cryptoCallbacks = opts.cryptoCallbacks || {};\n\n this.forceTURN = opts.forceTURN || false;\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.supportsCallTransfer = opts.supportsCallTransfer || false;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n\n if (opts.useE2eForGroupCall !== undefined) this.useE2eForGroupCall = opts.useE2eForGroupCall;\n\n this.livekitServiceURL = opts.livekitServiceURL;\n\n this.roomNameGenerator = opts.roomNameGenerator;\n\n this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);\n\n // The SDK doesn't really provide a clean way for events to recalculate the push\n // actions for themselves, so we have to kinda help them out when they are encrypted.\n // We do this so that push rules are correctly executed on events in their decrypted\n // state, such as highlights when the user's name is mentioned.\n this.on(MatrixEventEvent.Decrypted, (event) => {\n fixNotificationCountOnDecryption(this, event);\n });\n\n this.ignoredInvites = new IgnoredInvites(this);\n this._secretStorage = new ServerSideSecretStorageImpl(this, opts.cryptoCallbacks ?? {});\n\n // having lots of event listeners is not unusual. 0 means \"unlimited\".\n this.setMaxListeners(0);\n }\n\n public set store(newStore: Store) {\n this._store = newStore;\n this._store.setUserCreator((userId) => User.createUser(userId, this));\n }\n\n public get store(): Store {\n return this._store;\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link ClientEvent.Event}\n * via {@link MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param opts - Options to apply when syncing.\n */\n public async startClient(opts?: IStartClientOpts): Promise<void> {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n\n this.on(ClientEvent.Sync, this.startMatrixRTC);\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // periodically poll for turn servers if we support voip\n if (this.canSupportVoip) {\n this.checkTurnServersIntervalID = setInterval(() => {\n this.checkTurnServers();\n }, TURN_CHECK_INTERVAL);\n // noinspection ES6MissingAwait\n this.checkTurnServers();\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n this.logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n try {\n await this.getVersions();\n\n // This should be done with `canSupport`\n // TODO: https://github.com/vector-im/element-web/issues/23643\n const { threads, list, fwdPagination } = await this.doesServerSupportThread();\n Thread.setServerSideSupport(threads);\n Thread.setServerSideListSupport(list);\n Thread.setServerSideFwdPaginationSupport(fwdPagination);\n } catch (e) {\n this.logger.error(\n \"Can't fetch server versions, continuing to initialise sync, this will be retried later\",\n e,\n );\n }\n\n this.clientOpts = opts ?? {};\n if (this.clientOpts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(\n this.clientOpts.slidingSync,\n this,\n this.clientOpts,\n this.buildSyncApiOptions(),\n );\n } else {\n this.syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n }\n\n this.syncApi.sync().catch((e) => this.logger.info(\"Sync startup aborted with an error:\", e));\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID = setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod);\n this.fetchClientWellKnown();\n }\n\n this.toDeviceMessageQueue.start();\n this.serverCapabilitiesService.start();\n }\n\n /**\n * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n */\n protected buildSyncApiOptions(): SyncApiOptions {\n return {\n crypto: this.crypto,\n cryptoCallbacks: this.cryptoBackend,\n canResetEntireTimeline: (roomId: string): boolean => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n },\n };\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient(): void {\n this.cryptoBackend?.stop(); // crypto might have been initialised even if the client wasn't fully started\n\n this.off(ClientEvent.Sync, this.startMatrixRTC);\n\n if (!this.clientRunning) return; // already stopped\n\n this.logger.debug(\"stopping MatrixClient\");\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = undefined;\n\n this.peekSync?.stopPeeking();\n\n this.callEventHandler?.stop();\n this.groupCallEventHandler?.stop();\n this.callEventHandler = undefined;\n this.groupCallEventHandler = undefined;\n\n globalThis.clearInterval(this.checkTurnServersIntervalID);\n this.checkTurnServersIntervalID = undefined;\n\n if (this.clientWellKnownIntervalID !== undefined) {\n globalThis.clearInterval(this.clientWellKnownIntervalID);\n }\n\n this.toDeviceMessageQueue.stop();\n\n this.matrixRTC.stop();\n\n this.serverCapabilitiesService.stop();\n }\n\n /**\n * Try to rehydrate a device if available. The client must have been\n * initialized with a `cryptoCallback.getDehydrationKey` option, and this\n * function must be called before initCrypto and startClient are called.\n *\n * @returns Promise which resolves to undefined if a device could not be dehydrated, or\n * to the new device ID if the dehydration was successful.\n * @returns Rejects: with an error response.\n *\n * @deprecated MSC2697 device dehydration is not supported for rust cryptography.\n */\n public async rehydrateDevice(): Promise<string | undefined> {\n if (this.crypto) {\n throw new Error(\"Cannot rehydrate device after crypto is initialized\");\n }\n\n if (!this.cryptoCallbacks.getDehydrationKey) {\n return;\n }\n\n const getDeviceResult = await this.getDehydratedDevice();\n if (!getDeviceResult) {\n return;\n }\n\n if (!getDeviceResult.device_data || !getDeviceResult.device_id) {\n this.logger.info(\"no dehydrated device found\");\n return;\n }\n\n const account = new globalThis.Olm.Account();\n try {\n const deviceData = getDeviceResult.device_data;\n if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {\n this.logger.warn(\"Wrong algorithm for dehydrated device\");\n return;\n }\n this.logger.debug(\"unpickling dehydrated device\");\n const key = await this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => {\n // copy the key so that it doesn't get clobbered\n account.unpickle(new Uint8Array(k), deviceData.account);\n });\n account.unpickle(key, deviceData.account);\n this.logger.debug(\"unpickled device\");\n\n const rehydrateResult = await this.http.authedRequest<{ success: boolean }>(\n Method.Post,\n \"/dehydrated_device/claim\",\n undefined,\n {\n device_id: getDeviceResult.device_id,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n if (rehydrateResult.success) {\n this.deviceId = getDeviceResult.device_id;\n this.logger.info(\"using dehydrated device\");\n const pickleKey = this.pickleKey || \"DEFAULT_KEY\";\n this.exportedOlmDeviceToImport = {\n pickledAccount: account.pickle(pickleKey),\n sessions: [],\n pickleKey: pickleKey,\n };\n account.free();\n return this.deviceId;\n } else {\n account.free();\n this.logger.info(\"not using dehydrated device\");\n return;\n }\n } catch (e) {\n account.free();\n this.logger.warn(\"could not unpickle\", e);\n }\n }\n\n /**\n * Get the current dehydrated device, if any\n * @returns A promise of an object containing the dehydrated device\n *\n * @deprecated MSC2697 device dehydration is not supported for rust cryptography.\n */\n public async getDehydratedDevice(): Promise<IDehydratedDevice | undefined> {\n try {\n return await this.http.authedRequest<IDehydratedDevice>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n } catch (e) {\n this.logger.info(\"could not get dehydrated device\", e);\n return;\n }\n }\n\n /**\n * Set the dehydration key. This will also periodically dehydrate devices to\n * the server.\n *\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns A promise that resolves when the dehydrated device is stored.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public async setDehydrationKey(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<void> {\n if (!this.crypto) {\n this.logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n return this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName);\n }\n\n /**\n * Creates a new MSC2967 dehydrated device (without queuing periodic dehydration)\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns the device id of the newly created dehydrated device\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.startDehydration}.\n */\n public async createDehydratedDevice(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<string | undefined> {\n if (!this.crypto) {\n this.logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n await this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName);\n return this.crypto.dehydrationManager.dehydrateDevice();\n }\n\n /** @deprecated Not supported for Rust Cryptography. */\n public async exportDevice(): Promise<IExportedDevice | undefined> {\n if (!this.crypto) {\n this.logger.warn(\"not exporting device if crypto is not enabled\");\n return;\n }\n return {\n userId: this.credentials.userId!,\n deviceId: this.deviceId!,\n // XXX: Private member access.\n olmDevice: await this.crypto.olmDevice.export(),\n };\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise<void> {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises: Promise<void>[] = [];\n\n promises.push(this.store.deleteAllData());\n if (this.cryptoStore) {\n promises.push(this.cryptoStore.deleteAllData());\n }\n\n // delete the stores used by the rust matrix-sdk-crypto, in case they were used\n const deleteRustSdkStore = async (): Promise<void> => {\n let indexedDB: IDBFactory;\n try {\n indexedDB = globalThis.indexedDB;\n if (!indexedDB) return; // No indexedDB support\n } catch {\n // No indexedDB support\n return;\n }\n for (const dbname of [\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`,\n ]) {\n const prom = new Promise((resolve, reject) => {\n this.logger.info(`Removing IndexedDB instance ${dbname}`);\n const req = indexedDB.deleteDatabase(dbname);\n req.onsuccess = (_): void => {\n this.logger.info(`Removed IndexedDB instance ${dbname}`);\n resolve(0);\n };\n req.onerror = (e): void => {\n // In private browsing, Firefox has a globalThis.indexedDB, but attempts to delete an indexeddb\n // (even a non-existent one) fail with \"DOMException: A mutation operation was attempted on a\n // database that did not allow mutations.\"\n //\n // it seems like the only thing we can really do is ignore the error.\n this.logger.warn(`Failed to remove IndexedDB instance ${dbname}:`, e);\n resolve(0);\n };\n req.onblocked = (e): void => {\n this.logger.info(`cannot yet remove IndexedDB instance ${dbname}`);\n };\n });\n await prom;\n }\n };\n promises.push(deleteRustSdkStore());\n\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user\n * @throws Error if not logged in\n */\n public getSafeUserId(): string {\n const userId = this.getUserId();\n if (!userId) {\n throw new Error(\"Expected logged in user but found none.\");\n }\n return userId;\n }\n\n /**\n * Get the domain for this client's MXID\n * @returns Domain of this MXID\n */\n public getDomain(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, \"\");\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n * @returns The user ID localpart or null.\n */\n public getUserIdLocalpart(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @returns device ID\n */\n public getDeviceId(): string | null {\n return this.deviceId;\n }\n\n /**\n * Get the session ID of this client\n * @returns session ID\n */\n public getSessionId(): string {\n return this.sessionId;\n }\n\n /**\n * Check if the runtime environment supports VoIP calling.\n * @returns True if VoIP is supported.\n */\n public supportsVoip(): boolean {\n return this.canSupportVoip;\n }\n\n /**\n * @returns\n */\n public getMediaHandler(): MediaHandler {\n return this.mediaHandler;\n }\n\n /**\n * Set whether VoIP calls are forced to use only TURN\n * candidates. This is the same as the forceTURN option\n * when creating the client.\n * @param force - True to force use of TURN servers\n */\n public setForceTURN(force: boolean): void {\n this.forceTURN = force;\n }\n\n /**\n * Set whether to advertise transfer support to other parties on Matrix calls.\n * @param support - True to advertise the 'm.call.transferee' capability\n */\n public setSupportsCallTransfer(support: boolean): void {\n this.supportsCallTransfer = support;\n }\n\n /**\n * Returns true if to-device signalling for group calls will be encrypted with Olm.\n * If false, it will be sent unencrypted.\n * @returns boolean Whether group call signalling will be encrypted\n */\n public getUseE2eForGroupCall(): boolean {\n return this.useE2eForGroupCall;\n }\n\n /**\n * Creates a new call.\n * The place*Call methods on the returned call can be used to actually place a call\n *\n * @param roomId - The room the call is to be placed in.\n * @returns the call or null if the browser doesn't support calling.\n */\n public createCall(roomId: string): MatrixCall | null {\n return createNewMatrixCall(this, roomId);\n }\n\n /**\n * Creates a new group call and sends the associated state event\n * to alert other members that the room now has a group call.\n *\n * @param roomId - The room the call is to be placed in.\n */\n public async createGroupCall(\n roomId: string,\n type: GroupCallType,\n isPtt: boolean,\n intent: GroupCallIntent,\n dataChannelsEnabled?: boolean,\n dataChannelOptions?: IGroupCallDataChannelOptions,\n ): Promise<GroupCall> {\n if (this.getGroupCallForRoom(roomId)) {\n throw new Error(`${roomId} already has an existing group call`);\n }\n\n const room = this.getRoom(roomId);\n\n if (!room) {\n throw new Error(`Cannot find room ${roomId}`);\n }\n\n // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n // no media WebRTC connection anyway.\n return new GroupCall(\n this,\n room,\n type,\n isPtt,\n intent,\n undefined,\n dataChannelsEnabled || this.isVoipWithNoMediaAllowed,\n dataChannelOptions,\n this.isVoipWithNoMediaAllowed,\n this.useLivekitForGroupCalls,\n this.livekitServiceURL,\n ).create();\n }\n\n public getLivekitServiceURL(): string | undefined {\n return this.livekitServiceURL;\n }\n\n // This shouldn't need to exist, but the widget API has startup ordering problems that\n // mean it doesn't know the livekit URL fast enough: remove this once this is fixed.\n public setLivekitServiceURL(newURL: string): void {\n this.livekitServiceURL = newURL;\n }\n\n /**\n * Wait until an initial state for the given room has been processed by the\n * client and the client is aware of any ongoing group calls. Awaiting on\n * the promise returned by this method before calling getGroupCallForRoom()\n * avoids races where getGroupCallForRoom is called before the state for that\n * room has been processed. It does not, however, fix other races, eg. two\n * clients both creating a group call at the same time.\n * @param roomId - The room ID to wait for\n * @returns A promise that resolves once existing group calls in the room\n * have been processed.\n */\n public waitUntilRoomReadyForGroupCalls(roomId: string): Promise<void> {\n return this.groupCallEventHandler!.waitUntilRoomReadyForGroupCalls(roomId);\n }\n\n /**\n * Get an existing group call for the provided room.\n * @returns The group call or null if it doesn't already exist.\n */\n public getGroupCallForRoom(roomId: string): GroupCall | null {\n return this.groupCallEventHandler!.groupCalls.get(roomId) || null;\n }\n\n /**\n * Get the current sync state.\n * @returns the sync state, which may be null.\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncApi?.getSyncState() ?? null;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @returns True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @returns True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. <b>This method is experimental\n * and may change without warning.</b>\n * @param guest - True if this is a guest account.\n * @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'\n * access token, which means that the SDK can determine this entirely without\n * the dev manually flipping this flag.\n */\n public setGuest(guest: boolean): void {\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @returns The scheduler or undefined\n */\n public getScheduler(): MatrixScheduler | undefined {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * Will also retry any outbound to-device messages currently in the queue to be sent\n * (retries of regular outgoing events are handled separately, per-event).\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n // don't await for this promise: we just want to kick it off\n this.toDeviceMessageQueue.sendQueue();\n return this.syncApi?.retryImmediately() ?? false;\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @returns the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet | null {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n */\n public setNotifTimelineSet(set: EventTimelineSet): void {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the cached capabilities of the homeserver, returning cached ones if available.\n * If there are no cached capabilities and none can be fetched, throw an exception.\n *\n * @returns Promise resolving with The capabilities of the homeserver\n */\n public async getCapabilities(): Promise<Capabilities> {\n const caps = this.serverCapabilitiesService.getCachedCapabilities();\n if (caps) return caps;\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Gets the cached capabilities of the homeserver. If none have been fetched yet,\n * return undefined.\n *\n * @returns The capabilities of the homeserver\n */\n public getCachedCapabilities(): Capabilities | undefined {\n return this.serverCapabilitiesService.getCachedCapabilities();\n }\n\n /**\n * Fetches the latest capabilities from the homeserver, ignoring any cached\n * versions. The newly returned version is cached.\n *\n * @returns A promise which resolves to the capabilities of the homeserver\n */\n public fetchCapabilities(): Promise<Capabilities> {\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using libolm.\n *\n * You should call this method after creating the matrixclient, but *before*\n * calling `startClient`, if you want to support end-to-end encryption.\n *\n * It will return a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n *\n * @deprecated libolm is deprecated. Prefer {@link initRustCrypto}.\n */\n public async initCrypto(): Promise<void> {\n if (!isCryptoAvailable()) {\n throw new Error(\n `End-to-end encryption not supported in this js-sdk build: did ` +\n `you remember to load the olm library?`,\n );\n }\n\n if (this.cryptoBackend) {\n this.logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n if (!this.cryptoStore) {\n // the cryptostore is provided by sdk.createClient, so this shouldn't happen\n throw new Error(`Cannot enable encryption: no cryptoStore provided`);\n }\n\n this.logger.debug(\"Crypto: Starting up crypto store...\");\n await this.cryptoStore.startup();\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n if (this.deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n const crypto = new Crypto(this, userId, this.deviceId, this.store, this.cryptoStore, this.verificationMethods!);\n\n this.reEmitter.reEmit(crypto, [\n LegacyCryptoEvent.KeyBackupFailed,\n LegacyCryptoEvent.KeyBackupSessionsRemaining,\n LegacyCryptoEvent.RoomKeyRequest,\n LegacyCryptoEvent.RoomKeyRequestCancellation,\n LegacyCryptoEvent.Warning,\n LegacyCryptoEvent.DevicesUpdated,\n LegacyCryptoEvent.WillUpdateDevices,\n LegacyCryptoEvent.DeviceVerificationChanged,\n LegacyCryptoEvent.UserTrustStatusChanged,\n LegacyCryptoEvent.KeysChanged,\n ]);\n\n this.logger.debug(\"Crypto: initialising crypto object...\");\n await crypto.init({\n exportedOlmDevice: this.exportedOlmDeviceToImport,\n pickleKey: this.pickleKey,\n });\n delete this.exportedOlmDeviceToImport;\n\n this.olmVersion = Crypto.getOlmVersion();\n\n // if crypto initialisation was successful, tell it to attach its event handlers.\n crypto.registerEventHandlers(this as Parameters<Crypto[\"registerEventHandlers\"]>[0]);\n this.cryptoBackend = this.crypto = crypto;\n\n // upload our keys in the background\n this.crypto.uploadDeviceKeys().catch((e) => {\n // TODO: throwing away this error is a really bad idea.\n this.logger.error(\"Error uploading device keys\", e);\n });\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.\n *\n * An alternative to {@link initCrypto}.\n *\n * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.\n * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly\n * 32 bytes of data, and must be the same each time the client is initialised for a given device.\n * If both this and `storagePassword` are unspecified, the store will be unencrypted.\n * @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to\n * encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer\n * to pass a `storageKey` directly where possible.\n *\n * @returns a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n */\n public async initRustCrypto(\n args: {\n useIndexedDB?: boolean;\n storageKey?: Uint8Array;\n storagePassword?: string;\n } = {},\n ): Promise<void> {\n if (this.cryptoBackend) {\n this.logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n const deviceId = this.getDeviceId();\n if (deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n // importing rust-crypto will download the webassembly, so we delay it until we know it will be\n // needed.\n this.logger.debug(\"Downloading Rust crypto library\");\n const RustCrypto = await import(\"./rust-crypto/index.ts\");\n\n const rustCrypto = await RustCrypto.initRustCrypto({\n logger: this.logger,\n http: this.http,\n userId: userId,\n deviceId: deviceId,\n secretStorage: this.secretStorage,\n cryptoCallbacks: this.cryptoCallbacks,\n storePrefix: args.useIndexedDB === false ? null : RUST_SDK_STORE_PREFIX,\n storeKey: args.storageKey,\n storePassphrase: args.storagePassword,\n\n legacyCryptoStore: this.cryptoStore,\n legacyPickleKey: this.pickleKey ?? \"DEFAULT_KEY\",\n legacyMigrationProgressListener: (progress: number, total: number): void => {\n this.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total);\n },\n });\n\n rustCrypto.setSupportedVerificationMethods(this.verificationMethods);\n\n this.cryptoBackend = rustCrypto;\n\n // attach the event listeners needed by RustCrypto\n this.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto));\n this.on(ClientEvent.Event, (event) => {\n rustCrypto.onLiveEventFromSync(event);\n });\n\n // re-emit the events emitted by the crypto impl\n this.reEmitter.reEmit(rustCrypto, [\n CryptoEvent.VerificationRequestReceived,\n CryptoEvent.UserTrustStatusChanged,\n CryptoEvent.KeyBackupStatus,\n CryptoEvent.KeyBackupSessionsRemaining,\n CryptoEvent.KeyBackupFailed,\n CryptoEvent.KeyBackupDecryptionKeyCached,\n CryptoEvent.KeysChanged,\n CryptoEvent.DevicesUpdated,\n CryptoEvent.WillUpdateDevices,\n ]);\n }\n\n /**\n * Access the server-side secret storage API for this client.\n */\n public get secretStorage(): ServerSideSecretStorage {\n return this._secretStorage;\n }\n\n /**\n * Access the crypto API for this client.\n *\n * If end-to-end encryption has been enabled for this client (via {@link initCrypto} or {@link initRustCrypto}),\n * returns an object giving access to the crypto API. Otherwise, returns `undefined`.\n */\n public getCrypto(): CryptoApi | undefined {\n return this.cryptoBackend;\n }\n\n /**\n * Is end-to-end crypto enabled for this client.\n * @returns True if end-to-end is enabled.\n * @deprecated prefer {@link getCrypto}\n */\n public isCryptoEnabled(): boolean {\n return !!this.cryptoBackend;\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @returns base64-encoded ed25519 key. Null if crypto is\n * disabled.\n *\n * @deprecated Not supported for Rust Cryptography.Prefer {@link CryptoApi.getOwnDeviceKeys}\n */\n public getDeviceEd25519Key(): string | null {\n return this.crypto?.getDeviceEd25519Key() ?? null;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @returns base64-encoded curve25519 key. Null if crypto is\n * disabled.\n *\n * @deprecated Not supported for Rust Cryptography. Use {@link CryptoApi.getOwnDeviceKeys}\n */\n public getDeviceCurve25519Key(): string | null {\n return this.crypto?.getDeviceCurve25519Key() ?? null;\n }\n\n /**\n * @deprecated Does nothing.\n */\n public async uploadKeys(): Promise<void> {\n this.logger.warn(\"MatrixClient.uploadKeys is deprecated\");\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map userId-\\>deviceId-\\>`DeviceInfo`\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise<DeviceInfoMap> {\n if (!this.crypto) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.crypto.downloadKeys(userIds, forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevicesForUser(userId) || [];\n }\n\n /**\n * Get the stored device key for a user id and device id\n *\n * @param userId - the user to list keys for.\n * @param deviceId - unique identifier for the device\n *\n * @returns device or null\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getUserDeviceInfo}\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevice(userId, deviceId) || null;\n }\n\n /**\n * Mark the given device as verified\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param verified - whether to mark the device as verified. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n */\n public setDeviceVerified(userId: string, deviceId: string, verified = true): Promise<void> {\n const prom = this.setDeviceVerification(userId, deviceId, verified, null, null);\n\n // if one of the user's own devices is being marked as verified / unverified,\n // check the key backup status, since whether or not we use this depends on\n // whether it has a signature from a verified device\n if (userId == this.credentials.userId) {\n this.checkKeyBackup();\n }\n return prom;\n }\n\n /**\n * Mark the given device as blocked/unblocked\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param blocked - whether to mark the device as blocked. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link LegacyCryptoEvent.DeviceVerificationChanged}\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public setDeviceBlocked(userId: string, deviceId: string, blocked = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, blocked, null);\n }\n\n /**\n * Mark the given device as known/unknown\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param known - whether to mark the device as known. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public setDeviceKnown(userId: string, deviceId: string, known = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, null, known);\n }\n\n private async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified?: boolean | null,\n blocked?: boolean | null,\n known?: boolean | null,\n ): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n await this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);\n }\n\n /**\n * Request a key verification from another user, using a DM.\n *\n * @param userId - the user to request verification with\n * @param roomId - the room to use for verification\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.requestVerificationDM}.\n */\n public requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerificationDM(userId, roomId);\n }\n\n /**\n * Finds a DM verification request that is already in progress for the given room id\n *\n * @param roomId - the room to use for verification\n *\n * @returns the VerificationRequest that is in progress, if any\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.findVerificationRequestDMInProgress}.\n */\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n } else if (!this.crypto) {\n // Hack for element-R to avoid breaking the cypress tests. We can get rid of this once the react-sdk is\n // updated to use CryptoApi.findVerificationRequestDMInProgress.\n return undefined;\n }\n return this.crypto.findVerificationRequestDMInProgress(roomId);\n }\n\n /**\n * Returns all to-device verification requests that are already in progress for the given user id\n *\n * @param userId - the ID of the user to query\n *\n * @returns the VerificationRequests that are in progress\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.getVerificationRequestsToDeviceInProgress}.\n */\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getVerificationRequestsToDeviceInProgress(userId);\n }\n\n /**\n * Request a key verification from another user.\n *\n * @param userId - the user to request verification with\n * @param devices - array of device IDs to send requests to. Defaults to\n * all devices owned by the user\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}.\n */\n public requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerification(userId, devices);\n }\n\n /**\n * Begin a key verification.\n *\n * @param method - the verification method to use\n * @param userId - the user to verify keys with\n * @param deviceId - the device to verify\n *\n * @returns a verification object\n * @deprecated Prefer {@link CryptoApi#requestOwnUserVerification} or {@link CryptoApi#requestDeviceVerification}.\n */\n public beginKeyVerification(method: string, userId: string, deviceId: string): Verification<any, any> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.beginKeyVerification(method, userId, deviceId);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#checkKey}.\n */\n public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise<boolean> {\n return this.secretStorage.checkKey(key, info);\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param value - whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * client.getCrypto().globalBlacklistUnverifiedDevices = value;\n * ```\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalBlacklistUnverifiedDevices = value;\n return value;\n }\n\n /**\n * @returns whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * value = client.getCrypto().globalBlacklistUnverifiedDevices;\n * ```\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Set whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send them message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n *\n * It has no effect with the Rust crypto implementation.\n *\n * @param value - whether error on unknown devices\n *\n * ```ts\n * client.getCrypto().globalErrorOnUnknownDevices = value;\n * ```\n */\n public setGlobalErrorOnUnknownDevices(value: boolean): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalErrorOnUnknownDevices = value;\n }\n\n /**\n * @returns whether to error on unknown devices\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n */\n public getGlobalErrorOnUnknownDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalErrorOnUnknownDevices;\n }\n\n /**\n * Get the ID of one of the user's cross-signing keys\n *\n * @param type - The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the key ID\n * @deprecated Not supported for Rust Cryptography. prefer {@link Crypto.CryptoApi#getCrossSigningKeyId}\n */\n public getCrossSigningId(type: CrossSigningKey | string = CrossSigningKey.Master): string | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCrossSigningId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - the user ID to get the cross-signing info for.\n *\n * @returns the cross signing information for the user.\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#userHasCrossSigningKeys}\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user to check.\n *\n * @deprecated Use {@link Crypto.CryptoApi.getUserVerificationStatus | `CryptoApi.getUserVerificationStatus`}\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkUserTrust(userId);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param deviceId - The ID of the device to check\n *\n * @deprecated Use {@link Crypto.CryptoApi.getDeviceVerificationStatus | `CryptoApi.getDeviceVerificationStatus`}\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkDeviceTrust(userId, deviceId);\n }\n\n /**\n * Check whether one of our own devices is cross-signed by our\n * user's stored keys, regardless of whether we trust those keys yet.\n *\n * @param deviceId - The ID of the device to check\n *\n * @returns true if the device is cross-signed\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public checkIfOwnDeviceCrossSigned(deviceId: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkIfOwnDeviceCrossSigned(deviceId);\n }\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n * @param opts - ICheckOwnCrossSigningTrustOpts object\n *\n * @deprecated Unneeded for the new crypto\n */\n public checkOwnCrossSigningTrust(opts?: ICheckOwnCrossSigningTrustOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkOwnCrossSigningTrust(opts);\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi#requestDeviceVerification}.\n */\n public legacyDeviceVerification(userId: string, deviceId: string, method: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.legacyDeviceVerification(userId, deviceId, method);\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n * @param room - the room the event is in\n *\n * @deprecated Prefer {@link CryptoApi.prepareToEncrypt | `CryptoApi.prepareToEncrypt`}:\n *\n * ```javascript\n * client.getCrypto().prepareToEncrypt(room);\n * ```\n */\n public prepareToEncrypt(room: Room): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.prepareToEncrypt(room);\n }\n\n /**\n * Checks if the user has previously published cross-signing keys\n *\n * This means downloading the devicelist for the user and checking if the list includes\n * the cross-signing pseudo-device.\n *\n * @deprecated Prefer {@link CryptoApi.userHasCrossSigningKeys | `CryptoApi.userHasCrossSigningKeys`}:\n *\n * ```javascript\n * result = client.getCrypto().userHasCrossSigningKeys();\n * ```\n */\n public userHasCrossSigningKeys(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.userHasCrossSigningKeys();\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n * @returns True if cross-signing is ready to be used on this device\n * @deprecated Prefer {@link CryptoApi.isCrossSigningReady | `CryptoApi.isCrossSigningReady`}:\n */\n public isCrossSigningReady(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.isCrossSigningReady();\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been set up)\n *\n * @deprecated Prefer {@link CryptoApi.bootstrapCrossSigning | `CryptoApi.bootstrapCrossSigning`}.\n */\n public bootstrapCrossSigning(opts: BootstrapCrossSigningOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.bootstrapCrossSigning(opts);\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @returns True if trusting cross-signed devices\n *\n * @deprecated Prefer {@link CryptoApi.getTrustCrossSignedDevices | `CryptoApi.getTrustCrossSignedDevices`}.\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getTrustCrossSignedDevices();\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n *\n * @param val - True to trust cross-signed devices\n *\n * @deprecated Prefer {@link CryptoApi.setTrustCrossSignedDevices | `CryptoApi.setTrustCrossSignedDevices`}.\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.setTrustCrossSignedDevices(val);\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public countSessionsNeedingBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.countSessionsNeedingBackup();\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param event - event to be checked\n * @returns The event information.\n * @deprecated Prefer {@link Crypto.CryptoApi.getEncryptionInfoForEvent | `CryptoApi.getEncryptionInfoForEvent`}.\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getEventEncryptionInfo(event);\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n *\n * @deprecated Prefer {@link CryptoApi.createRecoveryKeyFromPassphrase | `CryptoApi.createRecoveryKeyFromPassphrase`}.\n */\n public createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.createRecoveryKeyFromPassphrase(password);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * @returns True if secret storage is ready to be used on this device\n * @deprecated Prefer {@link CryptoApi.isSecretStorageReady | `CryptoApi.isSecretStorageReady`}.\n */\n public isSecretStorageReady(): Promise<boolean> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.isSecretStorageReady();\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * @deprecated Use {@link CryptoApi.bootstrapSecretStorage | `CryptoApi.bootstrapSecretStorage`}.\n */\n public bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.bootstrapSecretStorage(opts);\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param algorithm - the algorithm used by the key\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyName - the name of the key. If not given, a random name will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#addKey}.\n */\n public addSecretStorageKey(\n algorithm: string,\n opts: AddSecretStorageKeyOpts,\n keyName?: string,\n ): Promise<{ keyId: string; keyInfo: SecretStorageKeyDescription }> {\n return this.secretStorage.addKey(algorithm, opts, keyName);\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#hasKey}.\n */\n public hasSecretStorageKey(keyId?: string): Promise<boolean> {\n return this.secretStorage.hasKey(keyId);\n }\n\n /**\n * Store an encrypted secret on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - The name of the secret\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret or null/undefined\n * to use the default (will throw if no default key is set).\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#store}.\n */\n public storeSecret(name: string, secret: string, keys?: string[]): Promise<void> {\n return this.secretStorage.store(name, secret, keys);\n }\n\n /**\n * Get a secret from storage.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n *\n * @returns the contents of the secret\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#get}.\n */\n public getSecret(name: string): Promise<string | undefined> {\n return this.secretStorage.get(name);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#isStored}.\n */\n public isSecretStored(name: string): Promise<Record<string, SecretStorageKeyDescription> | null> {\n return this.secretStorage.isStored(name);\n }\n\n /**\n * Request a secret from another device.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret to request\n * @param devices - the devices to request the secret from\n *\n * @returns the secret request object\n * @deprecated Not supported for Rust Cryptography.\n */\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestSecret(name, devices);\n }\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns The default key ID or null if no default key ID is set\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getDefaultKeyId}.\n */\n public getDefaultSecretStorageKeyId(): Promise<string | null> {\n return this.secretStorage.getDefaultKeyId();\n }\n\n /**\n * Set the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The new default key ID\n *\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#setDefaultKeyId}.\n */\n public setDefaultSecretStorageKeyId(keyId: string): Promise<void> {\n return this.secretStorage.setDefaultKeyId(keyId);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n *\n * @deprecated The use of asymmetric keys for SSSS is deprecated.\n * Use {@link SecretStorage.ServerSideSecretStorage#checkKey} for symmetric keys.\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * Get e2e information on the device that sent an event\n *\n * @param event - event to be checked\n * @deprecated Not supported for Rust Cryptography.\n */\n public async getEventSenderDeviceInfo(event: MatrixEvent): Promise<DeviceInfo | null> {\n if (!this.crypto) {\n return null;\n }\n return this.crypto.getEventSenderDeviceInfo(event);\n }\n\n /**\n * Check if the sender of an event is verified\n *\n * @param event - event to be checked\n *\n * @returns true if the sender of this event has been verified using\n * {@link MatrixClient#setDeviceVerified}.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public async isEventSenderVerified(event: MatrixEvent): Promise<boolean> {\n const device = await this.getEventSenderDeviceInfo(event);\n if (!device) {\n return false;\n }\n return device.isVerified();\n }\n\n /**\n * Get outgoing room key request for this event if there is one.\n * @param event - The event to check for\n *\n * @returns A room key request, or null if there is none\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public getOutgoingRoomKeyRequest(event: MatrixEvent): Promise<OutgoingRoomKeyRequest | null> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n const wireContent = event.getWireContent();\n const requestBody: IRoomKeyRequestBody = {\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key,\n algorithm: wireContent.algorithm,\n room_id: event.getRoomId()!,\n };\n if (!requestBody.session_id || !requestBody.sender_key || !requestBody.algorithm || !requestBody.room_id) {\n return Promise.resolve(null);\n }\n return this.crypto.cryptoStore.getOutgoingRoomKeyRequest(requestBody);\n }\n\n /**\n * Cancel a room key request for this event if one is ongoing and resend the\n * request.\n * @param event - event of which to cancel and resend the room\n * key request.\n * @returns A promise that will resolve when the key request is queued\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return event.cancelAndResendKeyRequest(this.crypto, this.getUserId()!);\n }\n\n /**\n * Enable end-to-end encryption for a room. This does not modify room state.\n * Any messages sent before the returned promise resolves will be sent unencrypted.\n * @param roomId - The room ID to enable encryption in.\n * @param config - The encryption config for the room.\n * @returns A promise that will resolve when encryption is set up.\n *\n * @deprecated Not supported for Rust Cryptography. To enable encryption in a room, send an `m.room.encryption`\n * state event.\n */\n public setRoomEncryption(roomId: string, config: IRoomEncryption): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.setRoomEncryption(roomId, config);\n }\n\n /**\n * Whether encryption is enabled for a room.\n * @param roomId - the room id to query.\n * @returns whether encryption is enabled.\n *\n * @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or\n * {@link Room.hasEncryptionStateEvent}.\n */\n public isRoomEncrypted(roomId: string): boolean {\n const room = this.getRoom(roomId);\n if (!room) {\n // we don't know about this room, so can't determine if it should be\n // encrypted. Let's assume not.\n return false;\n }\n\n // if there is an 'm.room.encryption' event in this room, it should be\n // encrypted (independently of whether we actually support encryption)\n if (room.hasEncryptionStateEvent()) {\n return true;\n }\n\n // we don't have an m.room.encrypted event, but that might be because\n // the server is hiding it from us. Check the store to see if it was\n // previously encrypted.\n return this.crypto?.isRoomEncrypted(roomId) ?? false;\n }\n\n /**\n * Encrypts and sends a given object via Olm to-device messages to a given\n * set of devices.\n *\n * @param userDeviceInfoArr - list of deviceInfo objects representing the devices to send to\n *\n * @param payload - fields to include in the encrypted payload\n *\n * @returns Promise which\n * resolves once the message has been encrypted and sent to the given\n * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }`\n * of the successfully sent messages.\n *\n * @deprecated Instead use {@link CryptoApi.encryptToDeviceMessages} followed by {@link queueToDevice}.\n */\n public encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice<DeviceInfo>[], payload: object): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.encryptAndSendToDevices(userDeviceInfoArr, payload);\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param roomId - The ID of the room to discard the session for\n *\n * @deprecated Prefer {@link CryptoApi.forceDiscardSession | `CryptoApi.forceDiscardSession`}:\n */\n public forceDiscardSession(roomId: string): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n this.cryptoBackend.forceDiscardSession(roomId);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * This should be encrypted before returning it to the user.\n *\n * @returns a promise which resolves to a list of session export objects\n *\n * @deprecated Prefer {@link CryptoApi.exportRoomKeys | `CryptoApi.exportRoomKeys`}:\n *\n * ```javascript\n * sessionData = await client.getCrypto().exportRoomKeys();\n * ```\n */\n public exportRoomKeys(): Promise<IMegolmSessionData[]> {\n if (!this.cryptoBackend) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.cryptoBackend.exportRoomKeys();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param keys - a list of session export objects\n * @param opts - options object\n *\n * @returns a promise which resolves when the keys have been imported\n *\n * @deprecated Prefer {@link CryptoApi.importRoomKeys | `CryptoApi.importRoomKeys`}:\n * ```javascript\n * await client.getCrypto()?.importRoomKeys([..]);\n * ```\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts?: ImportRoomKeysOpts): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.importRoomKeys(keys, opts);\n }\n\n /**\n * Force a re-check of the local key backup status against\n * what's on the server.\n *\n * @returns Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n *\n * @deprecated Prefer {@link Crypto.CryptoApi.checkKeyBackupAndEnable}.\n */\n public checkKeyBackup(): Promise<IKeyBackupCheck | null> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.checkKeyBackup();\n }\n\n /**\n * Get information about the current key backup from the server.\n *\n * Performs some basic validity checks on the shape of the result, and raises an error if it is not as expected.\n *\n * **Note**: there is no (supported) way to distinguish between \"failure to talk to the server\" and \"another client\n * uploaded a key backup version using an algorithm I don't understand.\n *\n * @returns Information object from API, or null if no backup is present on the server.\n *\n * @deprecated Prefer {@link CryptoApi.getKeyBackupInfo}.\n */\n public async getKeyBackupVersion(): Promise<IKeyBackupInfo | null> {\n let res: IKeyBackupInfo;\n try {\n res = await this.http.authedRequest<IKeyBackupInfo>(\n Method.Get,\n \"/room_keys/version\",\n undefined,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n } catch (e) {\n if ((<MatrixError>e).errcode === \"M_NOT_FOUND\") {\n return null;\n } else {\n throw e;\n }\n }\n BackupManager.checkBackupVersion(res);\n return res;\n }\n\n /**\n * @param info - key backup info dict from getKeyBackupVersion()\n *\n * @deprecated Not supported for Rust Cryptography. Prefer {@link CryptoApi.isKeyBackupTrusted | `CryptoApi.isKeyBackupTrusted`}.\n */\n public isKeyBackupTrusted(info: IKeyBackupInfo): Promise<TrustInfo> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.isKeyBackupTrusted(info);\n }\n\n /**\n * @returns true if the client is configured to back up keys to\n * the server, otherwise false. If we haven't completed a successful check\n * of key backup status yet, returns null.\n *\n * @deprecated Not supported for Rust Cryptography. Prefer direct access to {@link Crypto.CryptoApi.getActiveSessionBackupVersion}:\n *\n * ```javascript\n * let enabled = (await client.getCrypto().getActiveSessionBackupVersion()) !== null;\n * ```\n */\n public getKeyBackupEnabled(): boolean | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.getKeyBackupEnabled();\n }\n\n /**\n * Enable backing up of keys, using data previously returned from\n * getKeyBackupVersion.\n *\n * @param info - Backup information object as returned by getKeyBackupVersion\n * @returns Promise which resolves when complete.\n *\n * @deprecated Do not call this directly. Instead call {@link Crypto.CryptoApi.checkKeyBackupAndEnable}.\n */\n public enableKeyBackup(info: IKeyBackupInfo): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.enableKeyBackup(info);\n }\n\n /**\n * Disable backing up of keys.\n *\n * @deprecated Not supported for Rust Cryptography. It should be unnecessary to disable key backup.\n */\n public disableKeyBackup(): void {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n this.crypto.backupManager.disableKeyBackup();\n }\n\n /**\n * Set up the data required to create a new backup version. The backup version\n * will not be created and enabled until createKeyBackupVersion is called.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n *\n * @returns Object that can be passed to createKeyBackupVersion and\n * additionally has a 'recovery_key' member with the user-facing recovery key string.\n *\n * @deprecated Not supported for Rust cryptography. Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}.\n */\n public async prepareKeyBackupVersion(\n password?: string | Uint8Array | null,\n opts: IKeyBackupPrepareOpts = { secureSecretStorage: false },\n ): Promise<Pick<IPreparedKeyBackupVersion, \"algorithm\" | \"auth_data\" | \"recovery_key\">> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // eslint-disable-next-line camelcase\n const { algorithm, auth_data, recovery_key, privateKey } =\n await this.crypto.backupManager.prepareKeyBackupVersion(password);\n\n if (opts.secureSecretStorage) {\n await this.secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n this.logger.info(\"Key backup private key stored in secret storage\");\n }\n\n return {\n algorithm,\n /* eslint-disable camelcase */\n auth_data,\n recovery_key,\n /* eslint-enable camelcase */\n };\n }\n\n /**\n * Check whether the key backup private key is stored in secret storage.\n * @returns map of key name to key info the secret is\n * encrypted with, or null if it is not present or not encrypted with a\n * trusted key\n */\n public isKeyBackupKeyStored(): Promise<Record<string, SecretStorageKeyDescription> | null> {\n return Promise.resolve(this.secretStorage.isStored(\"m.megolm_backup.v1\"));\n }\n\n /**\n * Create a new key backup version and enable it, using the information return\n * from prepareKeyBackupVersion.\n *\n * @param info - Info object from prepareKeyBackupVersion\n * @returns Object with 'version' param indicating the version created\n *\n * @deprecated Use {@link Crypto.CryptoApi.resetKeyBackup | `CryptoApi.resetKeyBackup`}.\n */\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise<IKeyBackupInfo> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.createKeyBackupVersion(info);\n\n const data = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign the backup auth data with the device key for backwards compat with\n // older devices with cross-signing. This can probably go away very soon in\n // favour of just signing with the cross-singing master key.\n // XXX: Private member access\n await this.crypto.signObject(data.auth_data);\n\n if (\n this.cryptoCallbacks.getCrossSigningKey &&\n // XXX: Private member access\n this.crypto.crossSigningInfo.getId()\n ) {\n // now also sign the auth data with the cross-signing master key\n // we check for the callback explicitly here because we still want to be able\n // to create an un-cross-signed key backup if there is a cross-signing key but\n // no callback supplied.\n // XXX: Private member access\n await this.crypto.crossSigningInfo.signObject(data.auth_data, \"master\");\n }\n\n const res = await this.http.authedRequest<IKeyBackupInfo>(Method.Post, \"/room_keys/version\", undefined, data);\n\n // We could assume everything's okay and enable directly, but this ensures\n // we run the same signature verification that will be used for future\n // sessions.\n await this.checkKeyBackup();\n if (!this.getKeyBackupEnabled()) {\n this.logger.error(\"Key backup not usable even though we just created it\");\n }\n\n return res;\n }\n\n /**\n * @deprecated Use {@link Crypto.CryptoApi.deleteKeyBackupVersion | `CryptoApi.deleteKeyBackupVersion`}.\n */\n public async deleteKeyBackupVersion(version: string): Promise<void> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.cryptoBackend.deleteKeyBackupVersion(version);\n }\n\n private makeKeyBackupPath(roomId?: string, sessionId?: string, version?: string): IKeyBackupPath {\n let path: string;\n if (sessionId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId!,\n $sessionId: sessionId,\n });\n } else if (roomId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId\", {\n $roomId: roomId,\n });\n } else {\n path = \"/room_keys/keys\";\n }\n const queryData = version === undefined ? undefined : { version };\n return { path, queryData };\n }\n\n /**\n * Back up session keys to the homeserver.\n * @param roomId - ID of the room that the keys are for Optional.\n * @param sessionId - ID of the session that the keys are for Optional.\n * @param version - backup version Optional.\n * @param data - Object keys to send\n * @returns a promise that will resolve when the keys\n * are uploaded\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public sendKeyBackup(\n roomId: undefined,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public sendKeyBackup(\n roomId: string,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public sendKeyBackup(\n roomId: string,\n sessionId: string,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void>;\n public async sendKeyBackup(\n roomId: string | undefined,\n sessionId: string | undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Put, path.path, path.queryData, data, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n *\n * @deprecated Not supported for Rust Cryptography. This is done automatically as part of\n * {@link CryptoApi.resetKeyBackup}, so there is probably no need to call this manually.\n */\n public async scheduleAllGroupSessionsForBackup(): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.scheduleAllGroupSessionsForBackup();\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n *\n * (This is done automatically as part of {@link CryptoApi.resetKeyBackup},\n * so there is probably no need to call this manually.)\n *\n * @returns Promise which resolves to the number of sessions requiring a backup.\n * @deprecated Not supported for Rust Cryptography.\n */\n public flagAllGroupSessionsForBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.flagAllGroupSessionsForBackup();\n }\n\n /**\n * Return true if recovery key is valid.\n * Try to decode the recovery key and check if it's successful.\n * @param recoveryKey\n * @deprecated Use {@link decodeRecoveryKey} directly\n */\n public isValidRecoveryKey(recoveryKey: string): boolean {\n try {\n decodeRecoveryKey(recoveryKey);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get the raw key for a key backup from the password\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @returns key backup key\n * @deprecated Deriving a backup key from a passphrase is not part of the matrix spec. Instead, a random key is generated and stored/shared via 4S.\n */\n public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise<Uint8Array> {\n return keyFromAuthData(backupInfo.auth_data, password);\n }\n\n /**\n * Get the raw key for a key backup from the recovery key\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param recoveryKey - The recovery key\n * @returns key backup key\n * @deprecated Use {@link decodeRecoveryKey} directly\n */\n public keyBackupKeyFromRecoveryKey(recoveryKey: string): Uint8Array {\n return decodeRecoveryKey(recoveryKey);\n }\n\n /**\n * Restore from an existing key backup via a passphrase.\n *\n * @param password - Passphrase\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `getKeyBackupVersion` or `checkKeyBackup`.`backupInfo`\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackupWithPassphrase | `CryptoApi.restoreKeyBackupWithPassphrase`}.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = await keyFromAuthData(backupInfo.auth_data, password);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via a private key stored in secret\n * storage.\n *\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithSecretStorage(\n backupInfo: IKeyBackupInfo,\n targetRoomId?: string,\n targetSessionId?: string,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const storedKey = await this.secretStorage.get(\"m.megolm_backup.v1\");\n\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const keys = await this.secretStorage.getKey();\n await this.secretStorage.store(\"m.megolm_backup.v1\", fixedKey, [keys![0]]);\n }\n\n const privKey = decodeBase64(fixedKey || storedKey!);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via an encoded recovery key.\n *\n * @param recoveryKey - Encoded recovery key\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param opts - Optional params such as callbacks\n\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = decodeRecoveryKey(recoveryKey);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via a private key stored locally\n * @param targetRoomId\n * @param targetSessionId\n * @param backupInfo\n * @param opts\n *\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n /**\n * @deprecated Prefer {@link CryptoApi.restoreKeyBackup | `CryptoApi.restoreKeyBackup`}.\n */\n public async restoreKeyBackupWithCache(\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const privKey = await this.cryptoBackend.getSessionBackupPrivateKey();\n if (!privKey) {\n throw new Error(\"Couldn't get key\");\n }\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult>;\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const cacheCompleteCallback = opts?.cacheCompleteCallback;\n const progressCallback = opts?.progressCallback;\n\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n if (!backupInfo.version) {\n throw new Error(\"Backup version must be defined\");\n }\n const backupVersion = backupInfo.version!;\n\n let totalKeyCount = 0;\n let totalFailures = 0;\n let totalImported = 0;\n\n const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupVersion);\n\n const backupDecryptor = await this.cryptoBackend.getBackupDecryptor(backupInfo, privKey);\n\n const untrusted = !backupDecryptor.sourceTrusted;\n\n try {\n if (!(privKey instanceof Uint8Array)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n throw new Error(`restoreKeyBackup expects Uint8Array, got ${privKey}`);\n }\n // Cache the key, if possible.\n // This is async.\n this.cryptoBackend\n .storeSessionBackupPrivateKey(privKey, backupVersion)\n .catch((e) => {\n this.logger.warn(\"Error caching session backup key:\", e);\n })\n .then(cacheCompleteCallback);\n\n if (progressCallback) {\n progressCallback({\n stage: \"fetch\",\n });\n }\n\n const res = await this.http.authedRequest<IRoomsKeysResponse | IRoomKeysResponse | IKeyBackupSession>(\n Method.Get,\n path.path,\n path.queryData,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n\n // We have finished fetching the backup, go to next step\n if (progressCallback) {\n progressCallback({\n stage: \"load_keys\",\n });\n }\n\n if ((res as IRoomsKeysResponse).rooms) {\n // We have a full backup here, it can get quite big, so we need to decrypt and import it in chunks.\n\n // Get the total count as a first pass\n totalKeyCount = this.getTotalKeyCount(res as IRoomsKeysResponse);\n // Now decrypt and import the keys in chunks\n await this.handleDecryptionOfAFullBackup(\n res as IRoomsKeysResponse,\n backupDecryptor,\n 200,\n async (chunk) => {\n // We have a chunk of decrypted keys: import them\n try {\n const backupVersion = backupInfo.version!;\n await this.cryptoBackend!.importBackedUpRoomKeys(chunk, backupVersion, {\n untrusted,\n });\n totalImported += chunk.length;\n } catch (e) {\n totalFailures += chunk.length;\n // We failed to import some keys, but we should still try to import the rest?\n // Log the error and continue\n logger.error(\"Error importing keys from backup\", e);\n }\n\n if (progressCallback) {\n progressCallback({\n total: totalKeyCount,\n successes: totalImported,\n stage: \"load_keys\",\n failures: totalFailures,\n });\n }\n },\n );\n } else if ((res as IRoomKeysResponse).sessions) {\n // For now we don't chunk for a single room backup, but we could in the future.\n // Currently it is not used by the application.\n const sessions = (res as IRoomKeysResponse).sessions;\n totalKeyCount = Object.keys(sessions).length;\n const keys = await backupDecryptor.decryptSessions(sessions);\n for (const k of keys) {\n k.room_id = targetRoomId!;\n }\n await this.cryptoBackend.importBackedUpRoomKeys(keys, backupVersion, {\n progressCallback,\n untrusted,\n });\n totalImported = keys.length;\n } else {\n totalKeyCount = 1;\n try {\n const [key] = await backupDecryptor.decryptSessions({\n [targetSessionId!]: res as IKeyBackupSession,\n });\n key.room_id = targetRoomId!;\n key.session_id = targetSessionId!;\n\n await this.cryptoBackend.importBackedUpRoomKeys([key], backupVersion, {\n progressCallback,\n untrusted,\n });\n totalImported = 1;\n } catch (e) {\n this.logger.debug(\"Failed to decrypt megolm session from backup\", e);\n }\n }\n } finally {\n backupDecryptor.free();\n }\n\n /// in case entering the passphrase would add a new signature?\n await this.cryptoBackend.checkKeyBackupAndEnable();\n\n return { total: totalKeyCount, imported: totalImported };\n }\n\n /**\n * This method calculates the total number of keys present in the response of a `/room_keys/keys` call.\n *\n * @param res - The response from the server containing the keys to be counted.\n *\n * @returns The total number of keys in the backup.\n */\n private getTotalKeyCount(res: IRoomsKeysResponse): number {\n const rooms = res.rooms;\n let totalKeyCount = 0;\n for (const roomData of Object.values(rooms)) {\n if (!roomData.sessions) continue;\n totalKeyCount += Object.keys(roomData.sessions).length;\n }\n return totalKeyCount;\n }\n\n /**\n * This method handles the decryption of a full backup, i.e a call to `/room_keys/keys`.\n * It will decrypt the keys in chunks and call the `block` callback for each chunk.\n *\n * @param res - The response from the server containing the keys to be decrypted.\n * @param backupDecryptor - An instance of the BackupDecryptor class used to decrypt the keys.\n * @param chunkSize - The size of the chunks to be processed at a time.\n * @param block - A callback function that is called for each chunk of keys.\n *\n * @returns A promise that resolves when the decryption is complete.\n */\n private async handleDecryptionOfAFullBackup(\n res: IRoomsKeysResponse,\n backupDecryptor: BackupDecryptor,\n chunkSize: number,\n block: (chunk: IMegolmSessionData[]) => Promise<void>,\n ): Promise<void> {\n const rooms = (res as IRoomsKeysResponse).rooms;\n\n let groupChunkCount = 0;\n let chunkGroupByRoom: Map<string, IKeyBackupRoomSessions> = new Map();\n\n const handleChunkCallback = async (roomChunks: Map<string, IKeyBackupRoomSessions>): Promise<void> => {\n const currentChunk: IMegolmSessionData[] = [];\n for (const roomId of roomChunks.keys()) {\n const decryptedSessions = await backupDecryptor.decryptSessions(roomChunks.get(roomId)!);\n for (const sessionId in decryptedSessions) {\n const k = decryptedSessions[sessionId];\n k.room_id = roomId;\n currentChunk.push(k);\n }\n }\n await block(currentChunk);\n };\n\n for (const [roomId, roomData] of Object.entries(rooms)) {\n if (!roomData.sessions) continue;\n\n chunkGroupByRoom.set(roomId, {});\n\n for (const [sessionId, session] of Object.entries(roomData.sessions)) {\n const sessionsForRoom = chunkGroupByRoom.get(roomId)!;\n sessionsForRoom[sessionId] = session;\n groupChunkCount += 1;\n if (groupChunkCount >= chunkSize) {\n // We have enough chunks to decrypt\n await handleChunkCallback(chunkGroupByRoom);\n chunkGroupByRoom = new Map();\n // There might be remaining keys for that room, so add back an entry for the current room.\n chunkGroupByRoom.set(roomId, {});\n groupChunkCount = 0;\n }\n }\n }\n\n // Handle remaining chunk if needed\n if (groupChunkCount > 0) {\n await handleChunkCallback(chunkGroupByRoom);\n }\n }\n\n public deleteKeysFromBackup(roomId: undefined, sessionId: undefined, version?: string): Promise<void>;\n public deleteKeysFromBackup(roomId: string, sessionId: undefined, version?: string): Promise<void>;\n public deleteKeysFromBackup(roomId: string, sessionId: string, version?: string): Promise<void>;\n public async deleteKeysFromBackup(roomId?: string, sessionId?: string, version?: string): Promise<void> {\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Delete, path.path, path.queryData, undefined, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Get the config for the media repository.\n * @returns Promise which resolves with an object containing the config.\n */\n public getMediaConfig(): Promise<IMediaConfig> {\n return this.http.authedRequest(Method.Get, \"/config\", undefined, undefined, {\n prefix: MediaPrefix.V3,\n });\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param roomId - The room ID\n * @returns The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string | undefined): Room | null {\n if (!roomId) {\n return null;\n }\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and\n * use it if found (MSC3946).\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(msc3946ProcessDynamicPredecessor = false): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const predecessor = r.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (predecessor) {\n replacedRooms.add(predecessor);\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param userId - The user ID to retrieve.\n * @returns A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User | null {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param eventType - The event type\n * @param content - the contents object for the event\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: IContent): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n return retryNetworkOperation(5, () => {\n return this.http.authedRequest(Method.Put, path, undefined, content);\n });\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param eventType - The event type\n * @returns The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent | undefined {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param eventType - The event type\n * @returns Promise which resolves: The contents of the given account data event.\n * @returns Rejects: with an error response.\n */\n public async getAccountDataFromServer<T extends { [k: string]: any }>(eventType: string): Promise<T | null> {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent<T>();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(Method.Get, path);\n } catch (e) {\n if ((<MatrixError>e).data?.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw e;\n }\n }\n\n public async deleteAccountData(eventType: string): Promise<void> {\n const msc3391DeleteAccountDataServerSupport = this.canSupport.get(Feature.AccountDataDeletion);\n // if deletion is not supported overwrite with empty content\n if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n await this.setAccountData(eventType, {});\n return;\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.getSafeUserId(),\n $type: eventType,\n });\n const options =\n msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable\n ? { prefix: \"/_matrix/client/unstable/org.matrix.msc3391\" }\n : undefined;\n return await this.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param userIds - the user IDs to ignore\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[]): Promise<{}> {\n const content = { ignored_users: {} as Record<string, object> };\n userIds.forEach((u) => {\n content.ignored_users[u] = {};\n });\n return this.setAccountData(\"m.ignored_user_list\", content);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param userId - the user ID to check\n * @returns true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to join.\n * @param opts - Options when joining the room.\n * @returns Promise which resolves: Room object.\n * @returns Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts: IJoinRoomOpts = {}): Promise<Room> {\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return room;\n\n let signPromise: Promise<IThirdPartySigned | void> = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n const url = new URL(opts.inviteSignUrl);\n url.searchParams.set(\"mxid\", this.credentials.userId!);\n signPromise = this.http.requestOtherUrl<IThirdPartySigned>(Method.Post, url);\n }\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const data: IJoinRequestBody = {};\n const signedInviteObj = await signPromise;\n if (signedInviteObj) {\n data.third_party_signed = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryParams, data);\n\n const roomId = res.room_id;\n // In case we were originally given an alias, check the room cache again\n // with the resolved ID - this method is supposed to no-op if we already\n // were in the room, after all.\n const resolvedRoom = this.getRoom(roomId);\n if (resolvedRoom?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return resolvedRoom;\n\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n const syncRoom = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n return syncRoom;\n }\n\n /**\n * Knock a room. If you have already knocked the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to knock.\n * @param opts - Options when knocking the room.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public knockRoom(roomIdOrAlias: string, opts: KnockRoomOpts = {}): Promise<{ room_id: string }> {\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Knock)) {\n return Promise.resolve({ room_id: room.roomId });\n }\n\n const path = utils.encodeUri(\"/knock/$roomIdOrAlias\", { $roomIdOrAlias: roomIdOrAlias });\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const body: Record<string, string> = {};\n if (opts.reason) {\n body.reason = opts.reason;\n }\n\n return this.http.authedRequest(Method.Post, path, queryParams, body);\n }\n\n /**\n * Resend an event. Will also retry any to-device messages waiting to be sent.\n * @param event - The event to resend.\n * @param room - Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise<ISendEventResponse> {\n // also kick the to-device queue to retry\n this.toDeviceMessageQueue.sendQueue();\n\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param event - Event to cancel\n * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n */\n public cancelPendingEvent(event: MatrixEvent): void {\n if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status!)) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // If the event is currently being encrypted then remove it from the pending list, to indicate that it should\n // not be sent.\n if (event.status === EventStatus.ENCRYPTING) {\n this.eventsBeingEncrypted.delete(event.getId()!);\n } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n // tell the scheduler to forget about it, if it's queued\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, EventType.RoomName, { name: name });\n }\n\n /**\n * @param htmlTopic - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, htmlTopic?: string): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n }\n\n /**\n * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n * @returns Rejects: with an error response.\n */\n public getRoomTags(roomId: string): Promise<ITagsResponse> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param tagName - name of room tag to be set\n * @param metadata - associated with that tag to be stored\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: ITagMetadata = {}): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Put, path, undefined, metadata);\n }\n\n /**\n * @param tagName - name of room tag to be removed\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * @param eventType - event type to be set\n * @param content - event content\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: Record<string, any>): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Set a power level to one or multiple users.\n * Will apply changes atop of current power level event from local state if running & synced, falling back\n * to fetching latest from the `/state/` API.\n * @param roomId - the room to update power levels in\n * @param userId - the ID of the user or users to update power levels of\n * @param powerLevel - the numeric power level to update given users to\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public async setPowerLevel(\n roomId: string,\n userId: string | string[],\n powerLevel: number | undefined,\n ): Promise<ISendEventResponse> {\n let content: IPowerLevelsContent | undefined;\n if (this.clientRunning && this.isInitialSyncComplete()) {\n content = this.getRoom(roomId)?.currentState?.getStateEvents(EventType.RoomPowerLevels, \"\")?.getContent();\n }\n if (!content) {\n try {\n content = await this.getStateEvent(roomId, EventType.RoomPowerLevels, \"\");\n } catch (e) {\n // It is possible for a Matrix room to not have a power levels event\n if (e instanceof MatrixError && e.errcode === \"M_NOT_FOUND\") {\n content = {};\n } else {\n throw e;\n }\n }\n }\n\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(content);\n\n if (!content?.users) {\n content.users = {};\n }\n const users = Array.isArray(userId) ? userId : [userId];\n for (const user of users) {\n if (powerLevel == null) {\n delete content.users[user];\n } else {\n content.users[user] = powerLevel;\n }\n }\n\n return this.sendStateEvent(roomId, EventType.RoomPowerLevels, content, \"\");\n }\n\n /**\n * Create an m.beacon_info event\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_createLiveBeacon(\n roomId: Room[\"roomId\"],\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.unstable_setLiveBeacon(roomId, beaconInfoContent);\n }\n\n /**\n * Upsert a live beacon event\n * using a specific m.beacon_info.* event variable type\n * @param roomId - string\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_setLiveBeacon(\n roomId: string,\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, this.getUserId()!);\n }\n\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent(\n roomId: string,\n threadIdOrEventType: string | null,\n eventTypeOrContent: string | IContent,\n contentOrTxnId?: IContent | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse> {\n let threadId: string | null;\n let eventType: string;\n let content: IContent;\n let txnId: string | undefined;\n if (!threadIdOrEventType?.startsWith(EVENT_ID_PREFIX) && threadIdOrEventType !== null) {\n txnId = contentOrTxnId as string;\n content = eventTypeOrContent as IContent;\n eventType = threadIdOrEventType;\n threadId = null;\n } else {\n txnId = txnIdOrVoid;\n content = contentOrTxnId as IContent;\n eventType = eventTypeOrContent as string;\n threadId = threadIdOrEventType;\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId);\n }\n\n /**\n * If we expect that an event is part of a thread but is missing the relation\n * we need to add it manually, as well as the reply fallback\n */\n private addThreadRelationIfNeeded(content: IContent, threadId: string | null, roomId: string): void {\n if (threadId && !content[\"m.relates_to\"]?.rel_type) {\n const isReply = !!content[\"m.relates_to\"]?.[\"m.in_reply_to\"];\n content[\"m.relates_to\"] = {\n ...content[\"m.relates_to\"],\n rel_type: THREAD_RELATION_TYPE.name,\n event_id: threadId,\n // Set is_falling_back to true unless this is actually intended to be a reply\n is_falling_back: !isReply,\n };\n const thread = this.getRoom(roomId)?.getThread(threadId);\n if (thread && !isReply) {\n content[\"m.relates_to\"][\"m.in_reply_to\"] = {\n event_id:\n thread\n .lastReply((ev: MatrixEvent) => {\n return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n })\n ?.getId() ?? threadId,\n };\n }\n }\n }\n\n /**\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n /**\n * Sends a delayed event (MSC4140).\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param delayOpts - Properties of the delay for this event.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOpts: SendDelayedEventRequestOpts,\n txnId?: string,\n ): Promise<SendDelayedEventResponse>;\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOptsOrTxnId?: SendDelayedEventRequestOpts | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n let txnId: string | undefined;\n if (typeof delayOptsOrTxnId === \"string\") {\n txnId = delayOptsOrTxnId;\n } else {\n delayOpts = delayOptsOrTxnId;\n txnId = txnIdOrVoid;\n }\n\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // We always construct a MatrixEvent when sending because the store and scheduler use them.\n // We'll extract the params back out if it turns out the client has no scheduler or store.\n const localEvent = new MatrixEvent(\n Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }),\n );\n\n const room = this.getRoom(roomId);\n const thread = threadId ? room?.getThread(threadId) : undefined;\n if (thread) {\n localEvent.setThread(thread);\n }\n\n if (!delayOpts) {\n // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n }\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId?.startsWith(\"~\")) {\n const target = room?.getPendingEvents().find((e) => e.getId() === targetId);\n target?.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n localEvent.updateAssociatedId(target.getId()!);\n });\n }\n\n const type = localEvent.getType();\n this.logger.debug(\n `sendEvent of type ${type} in ${roomId} with txnId ${txnId}${delayOpts ? \" (delayed event)\" : \"\"}`,\n );\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // TODO: separate store for delayed events?\n if (!delayOpts) {\n // add this event immediately to the local store as 'sending'.\n room?.addPendingEvent(localEvent, txnId);\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent);\n } else {\n return this.encryptAndSendEvent(room, localEvent, delayOpts);\n }\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @returns returns a promise which resolves with the result of the send request\n */\n protected async encryptAndSendEvent(room: Room | null, event: MatrixEvent): Promise<ISendEventResponse>;\n /**\n * Simply sends a delayed event without encrypting it.\n * TODO: Allow encrypted delayed events, and encrypt them properly\n * @param delayOpts - Properties of the delay for this event.\n * @returns returns a promise which resolves with the result of the delayed send request\n */\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n if (delayOpts) {\n return this.sendEventHttpRequest(event, delayOpts);\n }\n\n try {\n let cancelled: boolean;\n this.eventsBeingEncrypted.add(event.getId()!);\n try {\n await this.encryptEventIfNeeded(event, room ?? undefined);\n } finally {\n cancelled = !this.eventsBeingEncrypted.delete(event.getId()!);\n }\n\n if (cancelled) {\n // cancelled via MatrixClient::cancelPendingEvent\n return {} as ISendEventResponse;\n }\n\n // encryptEventIfNeeded may have updated the status from SENDING to ENCRYPTING. If so, we need\n // to put it back.\n if (event.status === EventStatus.ENCRYPTING) {\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n }\n\n let promise: Promise<ISendEventResponse> | null = null;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event)!.length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then((res) => {\n room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n return res;\n });\n }\n }\n\n return await promise;\n } catch (err) {\n this.logger.error(\"Error sending event\", err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = <MatrixError>err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n } catch (e) {\n this.logger.error(\"Exception in error handler!\", e);\n }\n if (err instanceof MatrixError) {\n err.event = event;\n }\n throw err;\n }\n }\n\n private async encryptEventIfNeeded(event: MatrixEvent, room?: Room): Promise<void> {\n // If the room is unknown, we cannot encrypt for it\n if (!room) return;\n\n if (!(await this.shouldEncryptEventForRoom(event, room))) return;\n\n if (!this.cryptoBackend && this.usingExternalCrypto) {\n // The client has opted to allow sending messages to encrypted\n // rooms even if the room is encrypted, and we haven't set up\n // crypto. This is useful for users of matrix-org/pantalaimon\n return;\n }\n\n if (!this.cryptoBackend) {\n throw new Error(\"This room is configured to use encryption, but your client does not support encryption.\");\n }\n\n this.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);\n await this.cryptoBackend.encryptEvent(event, room);\n }\n\n /**\n * Determine whether a given event should be encrypted when we send it to the given room.\n *\n * This takes into account event type and room configuration.\n */\n private async shouldEncryptEventForRoom(event: MatrixEvent, room: Room): Promise<boolean> {\n if (event.isEncrypted()) {\n // this event has already been encrypted; this happens if the\n // encryption step succeeded, but the send step failed on the first\n // attempt.\n return false;\n }\n\n if (event.getType() === EventType.Reaction) {\n // For reactions, there is a very little gained by encrypting the entire\n // event, as relation data is already kept in the clear. Event\n // encryption for a reaction effectively only obscures the event type,\n // but the purpose is still obvious from the relation data, so nothing\n // is really gained. It also causes quite a few problems, such as:\n // * triggers notifications via default push rules\n // * prevents server-side bundling for reactions\n // The reaction key / content / emoji value does warrant encrypting, but\n // this will be handled separately by encrypting just this value.\n // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642\n return false;\n }\n\n if (event.isRedaction()) {\n // Redactions do not support encryption in the spec at this time.\n // Whilst it mostly worked in some clients, it wasn't compliant.\n return false;\n }\n\n // If the room has an m.room.encryption event, we should encrypt.\n if (room.hasEncryptionStateEvent()) return true;\n\n // If we have a crypto impl, and *it* thinks we should encrypt, then we should.\n if (await this.cryptoBackend?.isEncryptionEnabledInRoom(room.roomId)) return true;\n\n // Otherwise, no need to encrypt.\n return false;\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param roomId - the room for the events `eventType` relates to\n * @param eventType - the event type\n * @returns the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(\n roomId: string,\n eventType?: EventType | string | null,\n ): EventType | string | null | undefined {\n if (eventType === EventType.Reaction) return eventType;\n return this.getRoom(roomId)?.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;\n }\n\n protected updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus): void {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise<ISendEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId()!,\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey()!,\n $txnId: txnId,\n };\n\n let path: string;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey()!.length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction() && event.event.redacts) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, {\n $redactsEventId: event.event.redacts,\n ...pathParams,\n });\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n const content = event.getWireContent();\n if (!delayOpts) {\n return this.http.authedRequest<ISendEventResponse>(Method.Put, path, undefined, content).then((res) => {\n this.logger.debug(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n } else {\n return this.http.authedRequest<SendDelayedEventResponse>(\n Method.Put,\n path,\n getUnstableDelayQueryOpts(delayOpts),\n content,\n );\n }\n }\n\n /**\n * @param txnId - transaction id. One will be made up if not supplied.\n * @param opts - Redact options\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.\n * Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId?: string,\n txnId?: string | IRedactOpts,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse> {\n if (!eventId?.startsWith(EVENT_ID_PREFIX)) {\n opts = txnId as IRedactOpts;\n txnId = eventId;\n eventId = threadId!;\n threadId = null;\n }\n const reason = opts?.reason;\n const content: IContent = { reason };\n\n if (opts?.with_rel_types !== undefined) {\n if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) {\n throw new Error(\n \"Server does not support relation based redactions \" +\n `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`,\n );\n }\n\n const withRelTypesPropName =\n this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable\n ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable!\n : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable!;\n\n content[withRelTypesPropName] = opts.with_rel_types;\n }\n\n return this.sendCompleteEvent(\n roomId,\n threadId,\n {\n type: EventType.RoomRedaction,\n content,\n redacts: eventId,\n },\n txnId as string,\n );\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: RoomMessageEventContent, txnId?: string): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null,\n content: RoomMessageEventContent,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null | RoomMessageEventContent,\n content?: RoomMessageEventContent | string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (typeof threadId !== \"string\" && threadId !== null) {\n txnId = content as string;\n content = threadId as RoomMessageEventContent;\n threadId = null;\n }\n\n const eventType = EventType.RoomMessage;\n const sendContent = content as RoomMessageEventContent;\n\n return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns\n * @returns Rejects: with an error response.\n */\n public sendTextMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendEmoteMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendImageMessage(roomId: string, url: string, info?: ImageInfo, text?: string): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Image\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Image\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n msgtype: MsgType.Image,\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies RoomMessageEventContent;\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Sticker\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Sticker\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies StickerEventContent;\n\n return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlMessage(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlNotice(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlEmote(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * Send a delayed timeline event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedEvent<K extends keyof TimelineEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, delayOpts, txnId);\n }\n\n /**\n * Send a delayed state event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content as Body, opts);\n }\n\n /**\n * Get all pending delayed events for the calling user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_getDelayedEvents(fromToken?: string): Promise<DelayedEventInfo> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const queryDict = fromToken ? { from: fromToken } : undefined;\n return await this.http.authedRequest(Method.Get, \"/delayed_events\", queryDict, undefined, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Manage a delayed event associated with the given delay_id.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<{}> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const path = utils.encodeUri(\"/delayed_events/$delayId\", {\n $delayId: delayId,\n });\n const data = {\n action,\n };\n return await this.http.authedRequest(Method.Post, path, undefined, data, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Send a receipt.\n * @param event - The event being acknowledged\n * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n * ReceiptType.Read are experimental!\n * @param body - Additional content to send alongside the receipt.\n * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReceipt(\n event: MatrixEvent,\n receiptType: ReceiptType,\n body?: Record<string, any>,\n unthreaded = false,\n ): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId()!,\n $receiptType: receiptType,\n $eventId: event.getId()!,\n });\n\n // Unless we're explicitly making an unthreaded receipt or we don't\n // support threads, include the `thread_id` property in the body.\n const shouldAddThreadId = !unthreaded && this.supportsThreads();\n const fullBody = shouldAddThreadId ? { ...body, thread_id: threadIdForReceipt(event) } : body;\n\n const promise = this.http.authedRequest<{}>(Method.Post, path, undefined, fullBody || {});\n\n const room = this.getRoom(event.getRoomId());\n if (room && this.credentials.userId) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType, unthreaded);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param event - The event that has been read.\n * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReadReceipt(\n event: MatrixEvent | null,\n receiptType = ReceiptType.Read,\n unthreaded = false,\n ): Promise<{} | undefined> {\n if (!event) return;\n const eventId = event.getId()!;\n const room = this.getRoom(event.getRoomId());\n if (room?.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n return this.sendReceipt(event, receiptType, {}, unthreaded);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEvent - the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param rpEvent - the m.read.private read receipt event for when we don't\n * want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent?: MatrixEvent,\n rpEvent?: MatrixEvent,\n ): Promise<{}> {\n const room = this.getRoom(roomId);\n if (room?.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId: string | undefined;\n if (rrEvent) {\n rrEventId = rrEvent.getId()!;\n if (room?.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rrEvent, ReceiptType.Read);\n }\n\n // Add the optional private RR update, do local echo like `sendReceipt`\n let rpEventId: string | undefined;\n if (rpEvent) {\n rpEventId = rpEvent.getId()!;\n if (room?.hasPendingEvent(rpEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rpEvent, ReceiptType.ReadPrivate);\n }\n\n return await this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param url - The URL to get preview data for\n * @param ts - The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @returns Promise which resolves: Object of OG metadata.\n * @returns Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number): Promise<IPreviewUrlResponse> {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n if (key in this.urlPreviewCache) {\n return this.urlPreviewCache[key];\n }\n\n const resp = this.http.authedRequest<IPreviewUrlResponse>(\n Method.Get,\n \"/preview_url\",\n {\n url,\n ts: ts.toString(),\n },\n undefined,\n {\n prefix: MediaPrefix.V3,\n priority: \"low\",\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.getUserId()!,\n });\n const data: QueryDict = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param roomId - The room ID to search from\n * @param verifyLinks - If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @param msc3946ProcessDynamicPredecessor - if true, look for\n * m.room.predecessor state events as well as create events, and prefer\n * predecessor events where they exist (MSC3946).\n * @returns An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(\n roomId: string,\n verifyLinks = false,\n msc3946ProcessDynamicPredecessor = false,\n ): Room[] {\n const currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n\n return [...before, currentRoom, ...after];\n }\n\n private findPredecessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n const seenRoomIDs = new Set<string>([room.roomId]);\n\n // Work backwards from newer to older rooms\n let predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n while (predecessorRoomId !== null) {\n if (predecessorRoomId) {\n if (seenRoomIDs.has(predecessorRoomId)) break;\n seenRoomIDs.add(predecessorRoomId);\n }\n const predecessorRoom = this.getRoom(predecessorRoomId);\n if (predecessorRoom === null) {\n break;\n }\n if (verifyLinks) {\n const tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n ret.splice(0, 0, predecessorRoom);\n\n room = predecessorRoom;\n predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n }\n return ret;\n }\n\n private findSuccessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work forwards, looking at tombstone events\n let tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n while (tombstoneEvent) {\n const successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n if (!successorRoom) break; // end of the chain\n if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n if (verifyLinks) {\n const predecessorRoomId = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n break;\n }\n }\n\n // Push to the end because we're looking forwards\n ret.push(successorRoom);\n const roomIds = new Set(ret.map((ref) => ref.roomId));\n if (roomIds.size < ret.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return ret.slice(0, ret.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n room = successorRoom;\n tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n }\n return ret;\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Invite, reason);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param roomId - The room to invite the user to.\n * @param email - The email address to invite.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param roomId - The room to invite the user to.\n * @param medium - The medium to invite the user e.g. \"email\".\n * @param address - The address for the specified medium.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/invite\", { $roomId: roomId });\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(\n new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }),\n );\n }\n const params: Record<string, string> = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params[\"id_access_token\"] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, params);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public leave(roomId: string): Promise<{}> {\n return this.membershipChange(roomId, undefined, KnownMembership.Leave);\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param roomId - The room ID to start leaving at\n * @param includeFuture - If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @returns Promise which resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults: { [roomId: string]: Error } = {};\n const promises: Promise<unknown>[] = [];\n\n const doLeave = (roomId: string): Promise<void> => {\n return this.leave(roomId)\n .then(() => {\n delete populationResults[roomId];\n })\n .catch((err) => {\n // suppress error\n populationResults[roomId] = err;\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);\n }\n\n /**\n * @param deleteRoom - True to delete the room from the store on success.\n * Default: true.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async forget(roomId: string, deleteRoom = true): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/forget\", {\n $room_id: roomId,\n });\n const response = await this.http.authedRequest<{}>(Method.Post, path);\n if (deleteRoom) {\n this.store.removeRoom(roomId);\n this.emit(ClientEvent.DeleteRoom, roomId);\n }\n return response;\n }\n\n /**\n * @returns Promise which resolves: Object (currently empty)\n * @returns Rejects: with an error response.\n */\n public unban(roomId: string, userId: string): Promise<{}> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n reason: reason,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n private membershipChange(\n roomId: string,\n userId: string | undefined,\n membership: Membership,\n reason?: string,\n ): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(Method.Post, path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n });\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent, forceRecalculate = false): IActionsObject | null {\n if (!event.getPushActions() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushActions();\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushDetailsForEvent(event: MatrixEvent, forceRecalculate = false): PushDetails | null {\n if (!event.getPushDetails() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushDetails();\n }\n\n /**\n * @param info - The kind of info to set (e.g. 'avatar_url')\n * @param data - The JSON object to set.\n * @returns\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setProfileInfo(info: \"avatar_url\", data: { avatar_url: string }): Promise<{}>;\n public setProfileInfo(info: \"displayname\", data: { displayname: string }): Promise<{}>;\n public setProfileInfo(info: \"avatar_url\" | \"displayname\", data: object): Promise<{}> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId!,\n $info: info,\n });\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setDisplayName(name: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"displayname\", { displayname: name });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.displayName = name;\n user.emit(UserEvent.DisplayName, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setAvatarUrl(url: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"avatar_url\", { avatar_url: url });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.avatarUrl = url;\n user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n * may change.</strong>\n * @param mxcUrl - The MXC URL\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @returns the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n ): string | null {\n return getHttpUriForMxc(\n this.baseUrl,\n mxcUrl,\n width,\n height,\n resizeMethod,\n allowDirectLinks,\n allowRedirects,\n useAuthentication,\n );\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * This has an advantage over calls to the PUT /presence API in that it\n * doesn't clobber status_msg set by other devices.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public async setSyncPresence(presence?: SetPresence): Promise<void> {\n this.syncApi?.setPresence(presence);\n }\n\n /**\n * @param opts - Options to apply\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public async setPresence(opts: IPresenceOpts): Promise<void> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId!,\n });\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n await this.http.authedRequest(Method.Put, path, undefined, opts);\n }\n\n /**\n * @param userId - The user to get presence for\n * @returns Promise which resolves: The presence state for this user.\n * @returns Rejects: with an error response.\n */\n public getPresence(userId: string): Promise<IStatusResponse> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param room - The room to get older messages in.\n * @param limit - Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @returns Promise which resolves: Room. If you are at the beginning\n * of the timeline, `Room.oldState.paginationToken` will be\n * `null`.\n * @returns Rejects: with an error response.\n */\n public scrollback(room: Room, limit = 30): Promise<Room> {\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const promise = new Promise<Room>((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs)\n .then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n Direction.Backward,\n );\n })\n .then((res: IMessagesResponse) => {\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] =\n room.partitionThreadedEvents(matrixEvents);\n\n this.processAggregatedTimelineEvents(room, timelineEvents);\n room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline());\n this.processThreadEvents(room, threadedEvents, true);\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n room.oldState.paginationToken = res.end ?? null;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end ?? null, true);\n delete this.ongoingScrollbacks[room.roomId];\n resolve(room);\n })\n .catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n reject(err);\n });\n });\n\n info = { promise };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return promise;\n }\n\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n * <p>If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n * If the event does not belong to this EventTimelineSet then undefined will be returned.\n *\n * @param timelineSet - The timelineSet to look for the event in, must be bound to a room\n * @param eventId - The ID of the event to look for\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} including the given event\n */\n public async getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet?.room) {\n throw new Error(\"getEventTimeline only supports room timelines\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n if (timelineSet.thread && this.supportsThreads()) {\n return this.getThreadTimeline(timelineSet, eventId);\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n let params: Record<string, string | string[]> | undefined = undefined;\n if (this.clientOpts?.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n return undefined;\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...res.events_after.reverse().map(mapper),\n event,\n ...res.events_before.map(mapper),\n ];\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(events[0].getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n timeline.getState(EventTimeline.FORWARDS)!.paginationToken = res.end;\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);\n timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start);\n // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n this.processThreadEvents(timelineSet.room, threadedEvents, true);\n this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n unknownRelations.forEach((event) => timelineSet.relations.aggregateChildEvent(event));\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return (\n timelineSet.getTimelineForEvent(eventId) ??\n timelineSet.room.findThreadForEvent(event)?.liveTimeline ?? // for Threads degraded support\n timeline\n );\n }\n\n public async getThreadTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<EventTimeline | undefined> {\n if (!this.supportsThreads()) {\n throw new Error(\"could not get thread timeline: no client support\");\n }\n\n if (!timelineSet.room) {\n throw new Error(\"could not get thread timeline: not a room timeline\");\n }\n\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n const params: Record<string, string | string[]> = {\n limit: \"0\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n\n if (!timelineSet.canContain(event)) {\n return undefined;\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n if (Thread.hasServerSideSupport) {\n if (Thread.hasServerSideFwdPaginationSupport) {\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const thread = timelineSet.thread;\n const resOlder: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Forward, from: res.end, recurse: recurse || undefined },\n );\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper),\n event,\n ...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper),\n ];\n\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(event.getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n }\n\n timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(resNewer.next_batch ?? null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) ?? timeline;\n } else {\n // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n // functions contiguously, so we have to jump through some hoops to get our target event in it.\n // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n const thread = timelineSet.thread;\n\n const resOlder = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const eventsNewer: IEvent[] = [];\n let nextBatch: Optional<string> = res.end;\n while (nextBatch) {\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: nextBatch, recurse: recurse || undefined },\n );\n nextBatch = resNewer.next_batch ?? null;\n eventsNewer.push(...resNewer.chunk);\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...eventsNewer.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread\n // summaries.\n const timeline = timelineSet.getLiveTimeline();\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n\n timelineSet.addEventsToTimeline(events, true, timeline, null);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n return timeline;\n }\n }\n }\n\n /**\n * Get an EventTimeline for the latest events in the room. This will just\n * call `/messages` to get the latest message in the room, then use\n * `client.getEventTimeline(...)` to construct a new timeline from it.\n *\n * @param timelineSet - The timelineSet to find or add the timeline to\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} timeline with the latest events in the room\n */\n public async getLatestTimeline(timelineSet: EventTimelineSet): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet.room) {\n throw new Error(\"getLatestTimeline only supports room timelines\");\n }\n\n let event: IRoomEvent | undefined;\n if (timelineSet.threadListType !== null) {\n const res = await this.createThreadListMessagesRequest(\n timelineSet.room.roomId,\n null,\n 1,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n event = res.chunk?.[0];\n } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n const res = await this.fetchRelations(\n timelineSet.room.roomId,\n timelineSet.thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, limit: 1, recurse: recurse || undefined },\n );\n event = res.chunk?.[0];\n } else {\n const messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n $roomId: timelineSet.room.roomId,\n });\n\n const params: Record<string, string | string[]> = {\n dir: \"b\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n const res = await this.http.authedRequest<IMessagesResponse>(Method.Get, messagesPath, params);\n event = res.chunk?.[0];\n }\n if (!event) {\n throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n }\n\n return this.getEventTimeline(timelineSet, event.event_id);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir: Direction,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/messages\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter | null = null;\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used by room.fetchRoomThreads\n public createThreadListMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir = Direction.Backward,\n threadListType: ThreadFilterType | null = ThreadFilterType.All,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/threads\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n include: threadFilterTypeToFilter(threadListType),\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter = {};\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = {\n ...Filter.LAZY_LOADING_MESSAGES_FILTER,\n };\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = {\n ...filter,\n ...timelineFilter.getRoomTimelineFilterComponent()?.toJSON(),\n };\n }\n if (Object.keys(filter).length) {\n params.filter = JSON.stringify(filter);\n }\n\n const opts = {\n prefix:\n Thread.hasServerSideListSupport === FeatureSupport.Stable\n ? ClientPrefix.V1\n : \"/_matrix/client/unstable/org.matrix.msc3856\",\n };\n\n return this.http\n .authedRequest<IThreadedMessagesResponse>(Method.Get, path, params, undefined, opts)\n .then((res) => ({\n ...res,\n chunk: res.chunk?.reverse(),\n start: res.prev_batch,\n end: res.next_batch,\n }));\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param eventTimeline - timeline object to be updated\n *\n * @returns Promise which resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise<boolean> {\n const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n const room = this.getRoom(eventTimeline.getRoomId()!);\n const threadListType = eventTimeline.getTimelineSet().threadListType;\n const thread = eventTimeline.getTimelineSet().thread;\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path: string;\n let params: Record<string, string>;\n let promise: Promise<boolean>;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: (opts.limit ?? 30).toString(),\n only: \"highlight\",\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http\n .authedRequest<INotificationsResponse>(Method.Get, path, params)\n .then(async (res) => {\n const token = res.next_token;\n const matrixEvents: MatrixEvent[] = [];\n\n res.notifications = res.notifications.filter(noUnsafeEventProps);\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n\n // @TODO(kerrya) reprocessing every notification is ugly\n // remove if we get server MSC3994 support\n this.getPushDetailsForEvent(event, true);\n\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n // No need to partition events for threads here, everything lives\n // in the notification timeline set\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(res.next_token);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (threadListType !== null) {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n }\n\n promise = this.createThreadListMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n threadListType,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, matrixEvents);\n this.processThreadRoots(room, matrixEvents, backwards);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end !== res.start;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (thread) {\n const room = this.getRoom(eventTimeline.getRoomId() ?? undefined);\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n promise = this.fetchRelations(eventTimeline.getRoomId() ?? \"\", thread.id, null, null, {\n dir,\n limit: opts.limit,\n from: token ?? undefined,\n recurse: recurse || undefined,\n })\n .then(async (res) => {\n const mapper = this.getEventMapper();\n const matrixEvents = res.chunk\n .filter(noUnsafeEventProps)\n .filter(getRelationsThreadFilter(thread.id))\n .map(mapper);\n\n // Process latest events first\n for (const event of matrixEvents.slice().reverse()) {\n await thread?.processEvent(event);\n const sender = event.getSender()!;\n if (!backwards || thread?.getEventReadUpTo(sender) === null) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n }\n\n const newToken = res.next_batch;\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken ?? null);\n if (!newToken && backwards) {\n const originalEvent =\n thread.rootEvent ??\n mapper(await this.fetchRoomEvent(eventTimeline.getRoomId() ?? \"\", thread.id));\n timelineSet.addEventsToTimeline([originalEvent], true, eventTimeline, null);\n }\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !newToken) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(newToken);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n const [timelineEvents, , unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, timelineEvents);\n this.processThreadRoots(\n room,\n timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)),\n false,\n );\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n const atEnd = res.end === undefined || res.end === res.start;\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && atEnd) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return !atEnd;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet(): void {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param roomId - The room to attempt to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns Promise which resolves: Room object\n * @returns Rejects: with an error response.\n */\n public peekInRoom(roomId: string, limit: number = 20): Promise<Room> {\n this.peekSync?.stopPeeking();\n this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n return this.peekSync.peek(roomId, limit);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking(): void {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param roomId - The room to configure guest access in.\n * @param opts - Options\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise<void> {\n const writePromise = this.sendStateEvent(\n roomId,\n EventType.RoomGuestAccess,\n {\n guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden,\n },\n \"\",\n );\n\n let readPromise: Promise<unknown> = Promise.resolve();\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(\n roomId,\n EventType.RoomHistoryVisibility,\n {\n history_visibility: HistoryVisibility.WorldReadable,\n },\n \"\",\n );\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international format\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the homeserver).\n *\n * requestEmailToken calls the equivalent API directly on the identity server,\n * therefore bypassing the password reset specific logic.\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param endpoint - The endpoint to send the request to\n * @param params - Parameters for the POST request\n * @returns Promise which resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint<T extends IRequestTokenResponse>(\n endpoint: string,\n params: QueryDict,\n ): Promise<T> {\n const postParams = Object.assign({}, params);\n\n return this.http.request(Method.Post, endpoint, undefined, postParams);\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @returns the rule or undefined.\n */\n public getRoomPushRule(scope: \"global\" | \"device\", roomId: string): IPushRule | undefined {\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n return this.pushRules[scope]?.room?.find((rule) => rule.rule_id === roomId);\n } else {\n throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @param mute - the mute state.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: \"global\" | \"device\", roomId: string, mute: boolean): Promise<void> | undefined {\n let promise: Promise<unknown> | undefined;\n let hasDontNotifyRule = false;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule?.actions.includes(PushRuleActionName.DontNotify)) {\n hasDontNotifyRule = true;\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule!.rule_id);\n }\n } else {\n if (!roomPushRule) {\n promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n const deferred = utils.defer();\n this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n })\n .then(() => {\n deferred.resolve();\n })\n .catch((err) => {\n deferred.reject(err);\n });\n })\n .catch((err) => {\n deferred.reject(err);\n });\n\n promise = deferred.promise;\n }\n }\n\n if (promise) {\n return new Promise<void>((resolve, reject) => {\n // Update this.pushRules when the operation completes\n promise!\n .then(() => {\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n resolve();\n })\n .catch((err) => {\n reject(err);\n });\n })\n .catch((err: Error) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modified from another client\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n reject(err);\n })\n .catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts): Promise<ISearchResponse> {\n const roomEvents: ISearchRequestBody[\"search_categories\"][\"room_events\"] = {\n search_term: opts.query,\n };\n\n if (\"keys\" in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n });\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * count: estimate of the number of results\n * * next_batch: token for back-pagination; if undefined, there are no more results\n * * highlights: a list of words to highlight from the stemming algorithm\n * * results: a list of results\n *\n * Each entry in the results list is a SearchResult.\n *\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise<ISearchResults> {\n // TODO: support search groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: SearchOrderBy.Recent,\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults: ISearchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then((res) => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param searchResults - the results object to be updated\n * @returns Promise which resolves: updated result object\n * @returns Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch<T extends ISearchResults>(searchResults: T): Promise<T> {\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest as Promise<T>;\n }\n\n const searchOpts = {\n body: searchResults._query!,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts, searchResults.abortSignal)\n .then((res) => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = undefined;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @returns searchResults\n * @internal\n */\n // XXX: Intended private, used in code\n public processRoomEventsSearch<T extends ISearchResults>(searchResults: T, response: ISearchResponse): T {\n const roomEvents = response.search_categories.room_events;\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list;\n const highlights = new Set<string>(roomEvents.highlights);\n searchResults.highlights.forEach((hl) => {\n highlights.add(hl);\n });\n\n // turn it back into a list.\n searchResults.highlights = Array.from(highlights);\n\n const mapper = this.getEventMapper();\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results?.length ?? 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results![i], mapper);\n const room = this.getRoom(sr.context.getEvent().getRoomId());\n if (room) {\n // Copy over a known event sender if we can\n for (const ev of sr.context.getTimeline()) {\n const sender = room.getMember(ev.getSender()!);\n if (!ev.sender && sender) ev.sender = sender;\n }\n }\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @returns Promise which resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @returns Rejects: with an error response.\n */\n public syncLeftRooms(): Promise<Room[]> {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise\n .then(() => {\n this.logger.debug(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n })\n .finally(() => {\n this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param content - The HTTP body for the request\n * @returns Promise which resolves to a Filter object.\n * @returns Rejects: with an error response.\n */\n public createFilter(content: IFilterDefinition): Promise<Filter> {\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId!,\n });\n return this.http.authedRequest<IFilterResponse>(Method.Post, path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param userId - The user ID of the filter owner\n * @param filterId - The filter ID to retrieve\n * @param allowCached - True to allow cached filters to be returned.\n * Default: True.\n * @returns Promise which resolves: a Filter object\n * @returns Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise<Filter> {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest<IFilterDefinition>(Method.Get, path).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(userId, filterId, response);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @returns Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise<string> {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId: string | undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter = await this.getFilter(this.credentials.userId!, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if ((<MatrixError>error).errcode !== \"M_UNKNOWN\" && (<MatrixError>error).errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId!;\n }\n\n /**\n * Gets a bearer token from the homeserver that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @returns Promise which resolves: Token object\n * @returns Rejects: with an error response.\n */\n public getOpenIdToken(): Promise<IOpenIDToken> {\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId!,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, {});\n }\n\n private startCallEventHandler = (): void => {\n if (this.isInitialSyncComplete()) {\n if (supportsMatrixCall()) {\n this.callEventHandler!.start();\n this.groupCallEventHandler!.start();\n }\n\n this.off(ClientEvent.Sync, this.startCallEventHandler);\n }\n };\n\n private startMatrixRTC = (): void => {\n if (this.isInitialSyncComplete()) {\n this.matrixRTC.start();\n\n this.off(ClientEvent.Sync, this.startMatrixRTC);\n }\n };\n\n /**\n * Once the client has been initialised, we want to clear notifications we\n * know for a fact should be here.\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * We consider a room or a thread as fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n */\n private fixupRoomNotifications = (): void => {\n if (this.isInitialSyncComplete()) {\n const unreadRooms = (this.getRooms() ?? []).filter((room) => {\n return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n });\n\n for (const room of unreadRooms) {\n const currentUserId = this.getSafeUserId();\n room.fixupNotifications(currentUserId);\n }\n\n this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n }\n };\n\n /**\n * @returns Promise which resolves: ITurnServerResponse object\n * @returns Rejects: with an error response.\n */\n public turnServer(): Promise<ITurnServerResponse> {\n return this.http.authedRequest(Method.Get, \"/voip/turnServer\");\n }\n\n /**\n * Get the TURN servers for this homeserver.\n * @returns The servers or an empty list.\n */\n public getTurnServers(): ITurnServer[] {\n return this.turnServers || [];\n }\n\n /**\n * Get the unix timestamp (in milliseconds) at which the current\n * TURN credentials (from getTurnServers) expire\n * @returns The expiry timestamp in milliseconds\n */\n public getTurnServersExpiry(): number {\n return this.turnServersExpiry;\n }\n\n public get pollingTurnServers(): boolean {\n return this.checkTurnServersIntervalID !== undefined;\n }\n\n // XXX: Intended private, used in code.\n public async checkTurnServers(): Promise<boolean | undefined> {\n if (!this.canSupportVoip) {\n return;\n }\n\n let credentialsGood = false;\n const remainingTime = this.turnServersExpiry - Date.now();\n if (remainingTime > TURN_CHECK_INTERVAL) {\n this.logger.debug(\"TURN creds are valid for another \" + remainingTime + \" ms: not fetching new ones.\");\n credentialsGood = true;\n } else {\n this.logger.debug(\"Fetching new TURN credentials\");\n try {\n const res = await this.turnServer();\n if (res.uris) {\n this.logger.debug(\"Got TURN URIs: \" + res.uris + \" refresh in \" + res.ttl + \" secs\");\n // map the response to a format that can be fed to RTCPeerConnection\n const servers: ITurnServer = {\n urls: res.uris,\n username: res.username,\n credential: res.password,\n };\n this.turnServers = [servers];\n // The TTL is in seconds but we work in ms\n this.turnServersExpiry = Date.now() + res.ttl * 1000;\n credentialsGood = true;\n this.emit(ClientEvent.TurnServers, this.turnServers);\n }\n } catch (err) {\n this.logger.error(\"Failed to get TURN URIs\", err);\n if ((<HTTPError>err).httpStatus === 403) {\n // We got a 403, so there's no point in looping forever.\n this.logger.info(\"TURN access unavailable for this account: stopping credentials checks\");\n if (this.checkTurnServersIntervalID !== null) {\n globalThis.clearInterval(this.checkTurnServersIntervalID);\n }\n this.checkTurnServersIntervalID = undefined;\n this.emit(ClientEvent.TurnServersError, <HTTPError>err, true); // fatal\n } else {\n // otherwise, if we failed for whatever reason, try again the next time we're called.\n this.emit(ClientEvent.TurnServersError, <Error>err, false); // non-fatal\n }\n }\n }\n\n return credentialsGood;\n }\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n */\n public setFallbackICEServerAllowed(allow: boolean): void {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. <strong>This function is implementation specific and may change\n * as a result.</strong>\n * @returns true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise<boolean> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", { $userId: this.getUserId()! });\n return this.http\n .authedRequest<{ admin: boolean }>(Method.Get, path, undefined, undefined, { prefix: \"\" })\n .then((r) => r.admin); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * <strong>This function is implementation specific and may change as a\n * result.</strong>\n * @param userId - the User ID to look up.\n * @returns the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise<ISynapseAdminWhoisResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix: \"\" });\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. <strong>This\n * function is implementation specific and may change as a result.</strong>\n * @param userId - the User ID to deactivate.\n * @returns the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise<ISynapseAdminDeactivateResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Post, path, undefined, undefined, { prefix: \"\" });\n }\n\n protected async fetchClientWellKnown(): Promise<void> {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(this.getDomain() ?? undefined);\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(ClientEvent.ClientWellKnown, this.clientWellKnown);\n }\n\n public getClientWellKnown(): IClientWellKnown | undefined {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise<IClientWellKnown> {\n if (!this.clientRunning) {\n throw new Error(\"Client is not running\");\n }\n return this.clientWellKnownPromise!;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @returns for store operation\n */\n public storeClientOptions(): Promise<void> {\n // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts!)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce<Record<string, any>>((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.\n *\n * @param userId - The userId to check.\n * @returns Promise which resolves to an array of rooms\n * @returns Rejects: with an error response.\n */\n // TODO: on spec release, rename this to getMutualRooms\n // eslint-disable-next-line\n public async _unstable_getSharedRooms(userId: string): Promise<string[]> {\n // Initial variant of the MSC\n const sharedRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);\n\n // Newer variant that renamed shared rooms to mutual rooms\n const mutualRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);\n\n // Latest variant that changed from path elements to query elements\n const queryMutualRoomsSupport = await this.doesServerSupportUnstableFeature(\n UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS,\n );\n\n if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) {\n throw Error(\"Server does not support the Mutual Rooms API\");\n }\n\n let path;\n let query;\n\n // Cascading unstable support switching.\n if (queryMutualRoomsSupport) {\n path = \"/uk.half-shot.msc2666/user/mutual_rooms\";\n query = { user_id: userId };\n } else {\n path = utils.encodeUri(\n `/uk.half-shot.msc2666/user/${mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\"}/$userId`,\n { $userId: userId },\n );\n query = {};\n }\n\n // Accumulated rooms\n const rooms: string[] = [];\n let token = null;\n\n do {\n const tokenQuery: Record<string, string> = {};\n if (token != null && queryMutualRoomsSupport) {\n tokenQuery[\"batch_token\"] = token;\n }\n\n const res = await this.http.authedRequest<{\n joined: string[];\n next_batch_token?: string;\n }>(Method.Get, path, { ...query, ...tokenQuery }, undefined, {\n prefix: ClientPrefix.Unstable,\n });\n\n rooms.push(...res.joined);\n\n if (res.next_batch_token !== undefined) {\n token = res.next_batch_token;\n } else {\n token = null;\n }\n } while (token != null);\n\n return rooms;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @returns The server /versions response\n */\n public async getVersions(): Promise<IServerVersions> {\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n // We send an authenticated request as of MSC4026\n this.serverVersionsPromise = this.http\n .authedRequest<IServerVersions>(Method.Get, \"/_matrix/client/versions\", undefined, undefined, {\n prefix: \"\",\n })\n .catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = undefined;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n const serverVersions = await this.serverVersionsPromise;\n this.canSupport = await buildFeatureSupportMap(serverVersions);\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param version - The spec version (such as \"r0.5.0\") to check for.\n * @returns Whether it is supported\n */\n public async isVersionSupported(version: string): Promise<boolean> {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param feature - the feature name\n * @returns true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param presetName - The name of the preset to check.\n * @returns true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n public async doesServerSupportThread(): Promise<{\n threads: FeatureSupport;\n list: FeatureSupport;\n fwdPagination: FeatureSupport;\n }> {\n if (await this.isVersionSupported(\"v1.4\")) {\n return {\n threads: FeatureSupport.Stable,\n list: FeatureSupport.Stable,\n fwdPagination: FeatureSupport.Stable,\n };\n }\n\n try {\n const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] =\n await Promise.all([\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\"),\n ]);\n\n return {\n threads: determineFeatureSupport(threadStable, threadUnstable),\n list: determineFeatureSupport(listStable, listUnstable),\n fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable),\n };\n } catch {\n return {\n threads: FeatureSupport.None,\n list: FeatureSupport.None,\n fwdPagination: FeatureSupport.None,\n };\n }\n }\n\n /**\n * Get if lazy loading members is being used.\n * @returns Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts?.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param cb - The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback): void {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @returns The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback | undefined {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<{\n originalEvent?: MatrixEvent | null;\n events: MatrixEvent[];\n nextBatch?: string | null;\n prevBatch?: string | null;\n }> {\n const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;\n const [eventResult, result] = await Promise.all([\n this.fetchRoomEvent(roomId, eventId),\n this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts),\n ]);\n const mapper = this.getEventMapper();\n\n const originalEvent = eventResult ? mapper(eventResult) : undefined;\n let events = result.chunk.map(mapper);\n\n if (fetchedEventType === EventType.RoomMessageEncrypted) {\n const allEvents = originalEvent ? events.concat(originalEvent) : events;\n await Promise.all(allEvents.map((e) => this.decryptEventIfNeeded(e)));\n if (eventType !== null) {\n events = events.filter((e) => e.getType() === eventType);\n }\n }\n\n if (originalEvent && relationType === RelationType.Replace) {\n events = events.filter((e) => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent: originalEvent ?? null,\n events,\n nextBatch: result.next_batch ?? null,\n prevBatch: result.prev_batch ?? null,\n };\n }\n\n /**\n * The app may wish to see if we have a key cached without\n * triggering a user interaction.\n *\n * @deprecated Not supported for Rust Cryptography.\n */\n public getCrossSigningCacheCallbacks(): ICacheCallbacks | undefined {\n // XXX: Private member access\n return this.crypto?.crossSigningInfo.getCacheCallbacks();\n }\n\n /**\n * Generates a random string suitable for use as a client secret. <strong>This\n * method is experimental and may change.</strong>\n * @returns A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param event - The event to decrypt\n * @returns A decryption promise\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise<void> {\n if (event.shouldAttemptDecryption() && this.isCryptoEnabled()) {\n event.attemptDecryption(this.cryptoBackend!, options);\n }\n\n if (event.isBeingDecrypted()) {\n return event.getDecryptionPromise()!;\n } else {\n return Promise.resolve();\n }\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string): URL {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n case SERVICE_TYPES.IM:\n return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n default:\n throw new Error(\"Unsupported service type\");\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @returns Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the identity server URL of this client\n * @param stripProto - whether or not to strip the protocol from the URL\n * @returns Identity server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string | undefined {\n if (stripProto && (this.idBaseUrl?.startsWith(\"http://\") || this.idBaseUrl?.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the identity server URL of this client\n * @param url - New identity server URL\n */\n public setIdentityServerUrl(url?: string): void {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @returns The access_token or null\n */\n public getAccessToken(): string | null {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * Get the refresh token associated with this account.\n * @returns The refresh_token or null\n */\n public getRefreshToken(): string | null {\n return this.http.opts.refreshToken ?? null;\n }\n\n /**\n * Set the access token associated with this account.\n * @param token - The new access token.\n */\n public setAccessToken(token: string): void {\n this.http.opts.accessToken = token;\n // The /versions response can vary for different users so clear the cache\n this.serverVersionsPromise = undefined;\n }\n\n /**\n * @returns true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @returns a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param username - The username to check the availability of.\n * @returns Promise which resolves: to boolean of whether the username is available.\n */\n public isUsernameAvailable(username: string): Promise<boolean> {\n return this.http\n .authedRequest<{ available: true }>(Method.Get, \"/register/available\", { username })\n .then((response) => {\n return response.available;\n })\n .catch((response) => {\n if (response.errcode === \"M_USER_IN_USE\") {\n return false;\n }\n return Promise.reject(response);\n });\n }\n\n /**\n * @param bindThreepids - Set key 'email' to true to bind any email\n * threepid uses during registration in the identity server. Set 'msisdn' to\n * true to bind msisdn.\n * @returns Promise which resolves to a RegisterResponse object\n * @returns Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string | null,\n auth: { session?: string; type: string },\n bindThreepids?: { email?: boolean; msisdn?: boolean },\n guestAccessToken?: string,\n inhibitLogin?: boolean,\n ): Promise<RegisterResponse> {\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: RegisterRequest = {\n auth: auth,\n refresh_token: true, // always ask for a refresh token - does nothing if unsupported\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n\n return this.registerRequest(params);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param body - JSON HTTP body to provide.\n * @returns Promise which resolves: JSON object that contains:\n * `{ user_id, device_id, access_token, home_server }`\n * @returns Rejects: with an error response.\n */\n public registerGuest({ body }: { body?: RegisterRequest } = {}): Promise<RegisterResponse> {\n return this.registerRequest(body || {}, \"guest\");\n }\n\n /**\n * @param data - parameters for registration request\n * @param kind - type of user to register. may be \"guest\"\n * @returns Promise which resolves: to the /register response\n * @returns Rejects: with an error response.\n */\n public registerRequest(data: RegisterRequest, kind?: string): Promise<RegisterResponse> {\n const params: { kind?: string } = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(Method.Post, \"/register\", params, data);\n }\n\n /**\n * Refreshes an access token using a provided refresh token. The refresh token\n * must be valid for the current access token known to the client instance.\n *\n * Note that this function will not cause a logout if the token is deemed\n * unknown by the server - the caller is responsible for managing logout\n * actions on error.\n * @param refreshToken - The refresh token.\n * @returns Promise which resolves to the new token.\n * @returns Rejects with an error response.\n */\n public refreshToken(refreshToken: string): Promise<IRefreshTokenResponse> {\n const performRefreshRequestWithPrefix = (prefix: ClientPrefix): Promise<IRefreshTokenResponse> =>\n this.http.authedRequest(\n Method.Post,\n \"/refresh\",\n undefined,\n { refresh_token: refreshToken },\n {\n prefix,\n inhibitLogoutEmit: true, // we don't want to cause logout loops\n },\n );\n\n // First try with the (specced) /v3/ prefix.\n // However, before Synapse 1.72.0, Synapse incorrectly required a /v1/ prefix, so we fall\n // back to that if the request fails, for backwards compatibility.\n return performRefreshRequestWithPrefix(ClientPrefix.V3).catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n return performRefreshRequestWithPrefix(ClientPrefix.V1);\n }\n throw e;\n });\n }\n\n /**\n * @returns Promise which resolves to the available login flows\n * @returns Rejects: with an error response.\n */\n public loginFlows(): Promise<ILoginFlowsResponse> {\n return this.http.request(Method.Get, \"/login\");\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public login(loginType: LoginRequest[\"type\"], data: Omit<LoginRequest, \"type\">): Promise<LoginResponse> {\n return this.http\n .authedRequest<LoginResponse>(Method.Post, \"/login\", undefined, {\n ...data,\n type: loginType,\n })\n .then((response) => {\n if (response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string): Promise<LoginResponse> {\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n });\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with CAS.\n * @returns The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param loginType - The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param idpId - The ID of the Identity Provider being targeted, optional.\n * @param action - the SSO flow to indicate to the IdP, optional.\n * @returns The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string, action?: SSOAction): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n const params = {\n redirectUrl,\n [SSO_ACTION_PARAM.unstable!]: action,\n };\n\n return this.http.getUrl(url, params).href;\n }\n\n /**\n * @param token - Login token previously received from homeserver\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithToken(token: string): Promise<LoginResponse> {\n return this.login(\"m.login.token\", {\n token: token,\n });\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n * @returns Promise which resolves: On success, the empty object `{}`\n */\n public async logout(stopClient = false): Promise<{}> {\n if (this.crypto?.backupManager?.getKeyBackupEnabled()) {\n try {\n while ((await this.crypto.backupManager.backupPendingKeys(200)) > 0);\n } catch (err) {\n this.logger.error(\n \"Key backup request failed when logging out. Some keys may be missing from backup\",\n err,\n );\n }\n }\n\n if (stopClient) {\n this.stopClient();\n this.http.abort();\n }\n\n return this.http.authedRequest(Method.Post, \"/logout\");\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @param erase - Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @returns Promise which resolves: On success, the empty object\n */\n public deactivateAccount(\n auth?: AuthDict,\n erase?: boolean,\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const body: Body = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n }\n\n /**\n * Make a request for an `m.login.token` to be issued as per\n * https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token\n *\n * The server may require User-Interactive auth.\n *\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: On success, the token response\n * or UIA auth data.\n */\n public async requestLoginToken(auth?: AuthDict): Promise<UIAResponse<LoginTokenPostResponse>> {\n const body: UIARequest<{}> = { auth };\n return this.http.authedRequest<UIAResponse<LoginTokenPostResponse>>(\n Method.Post,\n \"/login/get_token\",\n undefined, // no query params\n body,\n { prefix: ClientPrefix.V1 },\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param loginType - the type of stage being attempted\n * @param authSessionId - the auth session ID provided by the homeserver\n *\n * @returns HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(path, {\n session: authSessionId,\n }).href;\n }\n\n /**\n * Create a new room.\n * @param options - a list of options to pass to the /createRoom API.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }> {\n // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);\n if (invitesNeedingToken.length > 0 && this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n }\n\n /**\n * Fetches relations for a given event\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns the response, with chunk, prev_batch and, next_batch.\n */\n public fetchRelations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<IRelationsResponse> {\n let params = opts as QueryDict;\n if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n }\n if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) {\n params = replaceParam(\"recurse\", \"org.matrix.msc3981.recurse\", params);\n }\n const queryString = utils.encodeParams(params);\n\n let templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n if (relationType !== null) {\n templatedUrl += \"/$relationType\";\n if (eventType !== null) {\n templatedUrl += \"/$eventType\";\n }\n } else if (eventType !== null) {\n this.logger.warn(`eventType: ${eventType} ignored when fetching\n relations as relationType is null`);\n eventType = null;\n }\n\n const path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType!,\n $eventType: eventType!,\n });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V1,\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomState(roomId: string): Promise<IStateEventWithRoomId[]> {\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get an event in a room by its event id.\n *\n * @returns Promise which resolves to an object containing the event.\n * @returns Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string): Promise<Partial<IEvent>> {\n const path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param includeMembership - the membership type to include in the response\n * @param excludeMembership - the membership type to exclude from the response\n * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n * @returns Promise which resolves: dictionary of userid to profile information\n * @returns Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string,\n excludeMembership?: string,\n atEventId?: string,\n ): Promise<{ [userId: string]: IStateEventWithRoomId[] }> {\n const queryParams: Record<string, string> = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param newVersion - The target version to upgrade to\n * @returns Promise which resolves: Object with key 'replacement_room'\n * @returns Rejects: with an error response.\n */\n public upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: string }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(Method.Post, path, undefined, { new_version: newVersion });\n }\n\n /**\n * Retrieve a state event.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string): Promise<Record<string, any>> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Send a state event into a room\n * @param roomId - ID of the room to send the event into\n * @param eventType - type of the state event to send\n * @param content - content of the event to send\n * @param stateKey - the stateKey to send into the room\n * @param opts - Options for the request function.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public sendStateEvent<K extends keyof StateEvents>(\n roomId: string,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<ISendEventResponse> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, undefined, content as Body, opts);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number): Promise<IRoomInitialSyncResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\", { $roomId: roomId });\n\n return this.http.authedRequest(Method.Get, path, { limit: limit?.toString() ?? \"30\" });\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEventId - ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n * don't want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId?: string,\n rpEventId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content: IContent = {\n [ReceiptType.FullyRead]: rmEventId,\n [ReceiptType.Read]: rrEventId,\n };\n\n if (\n (await this.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) ||\n (await this.isVersionSupported(\"v1.4\"))\n ) {\n content[ReceiptType.ReadPrivate] = rpEventId;\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * @returns Promise which resolves: A list of the user's current rooms\n * @returns Rejects: with an error response.\n */\n public getJoinedRooms(): Promise<IJoinedRoomsResponse> {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param roomId - ID of the room to get membership for\n * @returns Promise which resolves: A list of currently joined users\n * and their profile data.\n * @returns Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise<IJoinedMembersResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param params - Options for this request\n * @returns Promise which resolves: IPublicRoomsResponse\n * @returns Rejects: with an error response.\n */\n public publicRooms({\n server,\n limit,\n since,\n ...options\n }: IRoomDirectoryOptions = {}): Promise<IPublicRoomsResponse> {\n if (Object.keys(options).length === 0) {\n const queryParams: QueryDict = { server, limit, since };\n return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n } else {\n const queryParams: QueryDict = { server };\n const body = {\n limit,\n since,\n ...options,\n };\n return this.http.authedRequest(Method.Post, \"/publicRooms\", queryParams, body);\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param alias - The room alias to create.\n * @param roomId - The room ID to link the alias to.\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server,\n * and you must have sufficient access to do this operation.\n * @param alias - The room alias to delete.\n * @returns Promise which resolves: an empty object `{}`.\n * @returns Rejects: with an error response.\n */\n public deleteAlias(alias: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n * curated list from the m.room.canonical_alias state event.\n * @param roomId - The room ID to get local aliases for.\n * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n * @returns Rejects: with an error response.\n */\n public getLocalAliases(roomId: string): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\", { $roomId: roomId });\n const prefix = ClientPrefix.V3;\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param alias - The room alias to resolve.\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n public getRoomIdForAlias(alias: string): Promise<{ room_id: string; servers: string[] }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string): Promise<{ visibility: Visibility }> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Set the visibility of a room in the current HS's room directory\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(roomId: string, visibility: Visibility): Promise<{}> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility });\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param options\n * @param options.term - the term with which to search.\n * @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.\n * @returns Promise which resolves: an array of results.\n */\n public searchUserDirectory({ term, limit }: { term: string; limit?: number }): Promise<IUserDirectoryResponse> {\n const body: Body = {\n search_term: term,\n };\n\n if (limit !== undefined) {\n body.limit = limit;\n }\n\n return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n }\n\n /**\n * Upload a file to the media repository on the homeserver.\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts?: UploadOpts): Promise<UploadResponse> {\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param upload - The object returned from uploadContent\n * @returns true if canceled, otherwise false\n */\n public cancelUpload(upload: Promise<UploadResponse>): boolean {\n return this.http.cancelUpload(upload);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @returns Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): Upload[] {\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param info - The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getProfileInfo(\n userId: string,\n info?: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ avatar_url?: string; displayname?: string }> {\n const path = info\n ? utils.encodeUri(\"/profile/$userId/$info\", { $userId: userId, $info: info })\n : utils.encodeUri(\"/profile/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Determine if the server supports extended profiles, as described by MSC4133.\n *\n * @returns `true` if supported, otherwise `false`\n */\n public async doesServerSupportExtendedProfiles(): Promise<boolean> {\n return this.doesServerSupportUnstableFeature(UNSTABLE_MSC4133_EXTENDED_PROFILES);\n }\n\n /**\n * Get the prefix used for extended profile requests.\n *\n * @returns The prefix for use with `authedRequest`\n */\n private async getExtendedProfileRequestPrefix(): Promise<string> {\n if (await this.doesServerSupportUnstableFeature(\"uk.tcpip.msc4133.stable\")) {\n return ClientPrefix.V3;\n }\n return \"/_matrix/client/unstable/uk.tcpip.msc4133\";\n }\n\n /**\n * Fetch a user's *extended* profile, which may include additonal keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @returns A set of keys to property values.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the profile could not be found.\n */\n public async getExtendedProfile(userId: string): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n return this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Fetch a specific key from the user's *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @param key The key of the property to fetch.\n * @returns The property value.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.\n */\n public async getExtendedProfileProperty(userId: string, key: string): Promise<unknown> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const profile = (await this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n )) as Record<string, unknown>;\n return profile[key];\n }\n\n /**\n * Set a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to set.\n * @param value The value to set on the propety.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfileProperty(key: string, value: unknown): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n { [key]: value },\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Delete a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to delete.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async deleteExtendedProfileProperty(key: string): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Delete,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Update multiple properties on your *extended* profile. This will\n * merge with any existing keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to merge with the existing profile.\n * @returns The newly merged profile.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async patchExtendedProfile(profile: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n return this.http.authedRequest(\n Method.Patch,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Set multiple properties on your *extended* profile. This will completely\n * replace the existing profile, removing any unspecified keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to set.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfile(profile: Record<string, unknown>): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * @returns Promise which resolves to a list of the user's threepids.\n * @returns Rejects: with an error response.\n */\n public getThreePids(): Promise<{ threepids: IThreepid[] }> {\n return this.http.authedRequest(Method.Get, \"/account/3pid\");\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * @param data - A object with 3PID validation data from having called\n * `account/3pid/<medium>/requestToken` on the homeserver.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async addThreePidOnly(data: IAddThreePidOnlyBody): Promise<{}> {\n const path = \"/account/3pid/add\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * @param data - A object with 3PID validation data from having called\n * `validate/<medium>/requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async bindThreePid(data: IBindThreePidBody): Promise<{}> {\n const path = \"/account/3pid/bind\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public async unbindThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: The server response on success\n * (generally the empty JSON object)\n * @returns Rejects: with an error response.\n */\n public deleteThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/delete\";\n return this.http.authedRequest(Method.Post, path, undefined, { medium, address });\n }\n\n /**\n * Make a request to change your password.\n * @param newPassword - The new desired password.\n * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPassword(authDict: AuthDict, newPassword: string, logoutDevices?: boolean): Promise<{}> {\n const path = \"/account/password\";\n const data = {\n auth: authDict,\n new_password: newPassword,\n logout_devices: logoutDevices,\n };\n\n return this.http.authedRequest<{}>(Method.Post, path, undefined, data);\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevices(): Promise<{ devices: IMyDevice[] }> {\n return this.http.authedRequest(Method.Get, \"/devices\");\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param deviceId - device to query\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise<IMyDevice> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Update the given device\n *\n * @param deviceId - device to update\n * @param body - body of request\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setDeviceDetails(deviceId: string, body: { display_name: string }): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param deviceId - device to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: AuthDict): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: Body = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(Method.Delete, path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param devices - IDs of the devices to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: AuthDict): Promise<{}> {\n const body: Body = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @returns Promise which resolves: Array of objects representing pushers\n * @returns Rejects: with an error response.\n */\n public async getPushers(): Promise<{ pushers: IPusher[] }> {\n const response = await this.http.authedRequest<{ pushers: IPusher[] }>(Method.Get, \"/pushers\");\n\n // Migration path for clients that connect to a homeserver that does not support\n // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n if (!(await this.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n response.pushers = response.pushers.map((pusher) => {\n if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n pusher[PUSHER_ENABLED.name] = true;\n }\n return pusher;\n });\n }\n\n return response;\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param pusher - Object representing a pusher\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public setPusher(pusher: IPusherRequest): Promise<{}> {\n const path = \"/pushers/set\";\n return this.http.authedRequest(Method.Post, path, undefined, pusher);\n }\n\n /**\n * Removes an existing pusher\n * @param pushKey - pushkey of pusher to remove\n * @param appId - app_id of pusher to remove\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public removePusher(pushKey: string, appId: string): Promise<{}> {\n const path = \"/pushers/set\";\n const body = {\n pushkey: pushKey,\n app_id: appId,\n kind: null, // marks pusher for removal\n };\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Persists local notification settings\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setLocalNotificationSettings(\n deviceId: string,\n notificationSettings: LocalNotificationSettings,\n ): Promise<{}> {\n const key = `${LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${deviceId}`;\n return this.setAccountData(key, notificationSettings);\n }\n\n /**\n * Get the push rules for the account from the server.\n * @returns Promise which resolves to the push rules.\n * @returns Rejects: with an error response.\n */\n public getPushRules(): Promise<IPushRules> {\n return this.http.authedRequest<IPushRules>(Method.Get, \"/pushrules/\").then((rules: IPushRules) => {\n this.setPushRules(rules);\n return this.pushRules!;\n });\n }\n\n /**\n * Update the push rules for the account. This should be called whenever\n * updated push rules are available.\n */\n public setPushRules(rules: IPushRules): void {\n // Fix-up defaults, if applicable.\n this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);\n // Pre-calculate any necessary caches.\n this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public addPushRule(\n scope: string,\n kind: PushRuleKind,\n ruleId: Exclude<string, RuleId>,\n body: Pick<IPushRule, \"actions\" | \"conditions\" | \"pattern\">,\n ): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: PushRuleKind, ruleId: Exclude<string, RuleId>): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n enabled: boolean,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { enabled: enabled });\n }\n\n /**\n * Set the actions for a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n actions: PushRuleAction[],\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { actions: actions });\n }\n\n /**\n * Perform a server-side search.\n * @param params\n * @param params.next_batch - the batch token to pass in the query string\n * @param params.body - the JSON object to pass to the request body.\n * @param abortSignal - optional signal used to cancel the http request.\n * @returns Promise which resolves to the search response object.\n * @returns Rejects: with an error response.\n */\n public search(\n { body, next_batch: nextBatch }: { body: ISearchRequestBody; next_batch?: string },\n abortSignal?: AbortSignal,\n ): Promise<ISearchResponse> {\n const queryParams: QueryDict = {};\n if (nextBatch) {\n queryParams.next_batch = nextBatch;\n }\n return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, { abortSignal });\n }\n\n /**\n * Upload keys\n *\n * @param content - body of upload request\n *\n * @param opts - this method no longer takes any opts,\n * used to take opts.device_id but this was not removed from the spec as a redundant parameter\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public uploadKeysRequest(content: IUploadKeysRequest, opts?: void): Promise<IKeysUploadResponse> {\n return this.http.authedRequest(Method.Post, \"/keys/upload\", undefined, content);\n }\n\n public uploadKeySignatures(content: KeySignatures): Promise<IUploadKeySignaturesResponse> {\n return this.http.authedRequest(Method.Post, \"/keys/signatures/upload\", undefined, content);\n }\n\n /**\n * Download device keys\n *\n * @param userIds - list of users to get keys for\n *\n * @param token - sync token to pass in the query request, to help\n * the HS give the most recent results\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public downloadKeysForUsers(userIds: string[], { token }: { token?: string } = {}): Promise<IDownloadKeyResult> {\n const content: IQueryKeysRequest = {\n device_keys: {},\n };\n if (token !== undefined) {\n content.token = token;\n }\n userIds.forEach((u) => {\n content.device_keys[u] = [];\n });\n\n return this.http.authedRequest(Method.Post, \"/keys/query\", undefined, content);\n }\n\n /**\n * Claim one-time keys\n *\n * @param devices - a list of [userId, deviceId] pairs\n *\n * @param keyAlgorithm - desired key type\n *\n * @param timeout - the time (in milliseconds) to wait for keys from remote\n * servers\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public claimOneTimeKeys(\n devices: [string, string][],\n keyAlgorithm = \"signed_curve25519\",\n timeout?: number,\n ): Promise<IClaimOTKsResult> {\n const queries: Record<string, Record<string, string>> = {};\n\n if (keyAlgorithm === undefined) {\n keyAlgorithm = \"signed_curve25519\";\n }\n\n for (const [userId, deviceId] of devices) {\n const query = queries[userId] || {};\n safeSet(queries, userId, query);\n safeSet(query, deviceId, keyAlgorithm);\n }\n const content: IClaimKeysRequest = { one_time_keys: queries };\n if (timeout) {\n content.timeout = timeout;\n }\n const path = \"/keys/claim\";\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<{ changed: string[]; left: string[] }> {\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n }\n\n public uploadDeviceSigningKeys(auth?: AuthDict, keys?: CrossSigningKeys): Promise<{}> {\n // API returns empty object\n const data = Object.assign({}, keys);\n if (auth) Object.assign(data, { auth });\n return this.http.authedRequest(Method.Post, \"/keys/device_signing/upload\", undefined, data, {\n prefix: ClientPrefix.Unstable,\n });\n }\n\n /**\n * Register with an identity server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @returns Promise which resolves: with object containing an Identity\n * Server access token.\n * @returns Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: IOpenIDToken): Promise<{\n access_token: string;\n token: string;\n }> {\n if (!this.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n const uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param email - The email address to request a token for\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestTokenResponse>(\n Method.Post,\n \"/validate/email/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international\n * format\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves to an object with a sid string\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestMsisdnTokenResponse>(\n Method.Post,\n \"/validate/msisdn/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The identity server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n * Some legacy identity servers had no authentication here.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n * @throws Error if No identity server is set\n */\n public submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string | null,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/submitToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken ?? undefined,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param url - The URL to submit the token to\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n return this.http.requestOtherUrl(Method.Post, url, params);\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param identityAccessToken - The access token for the identity server.\n * @returns The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise<{\n /**\n * The algorithms the server supports. Must contain at least sha256.\n */\n algorithms: string[];\n /**\n * The pepper the client MUST use in hashing identifiers,\n * and MUST supply to the /lookup endpoint when performing lookups.\n */\n lookup_pepper: string;\n }> {\n return this.http.idServerRequest(\n Method.Get,\n \"/hash_details\",\n undefined,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param addressPairs - An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: `[\"email@example.org\", \"email\"]`\n * @param identityAccessToken - The access token for the identity server.\n * @returns A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string; mxid: string }[]> {\n const params: Record<string, string | string[]> = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params[\"pepper\"] = hashes[\"lookup_pepper\"];\n\n const localMapping: Record<string, string> = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes[\"algorithms\"].includes(\"sha256\")) {\n params[\"addresses\"] = await Promise.all(\n addressPairs.map(async (p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashBuffer = await sha256(`${addr} ${med} ${params[\"pepper\"]}`);\n const hashed = encodeUnpaddedBase64Url(hashBuffer);\n\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n }),\n );\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes[\"algorithms\"].includes(\"none\")) {\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case-sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest<{\n mappings: { [address: string]: string };\n }>(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n\n if (!response?.[\"mappings\"]) return []; // no results\n\n const foundAddresses: { address: string; mxid: string }[] = [];\n for (const hashed of Object.keys(response[\"mappings\"])) {\n const mxid = response[\"mappings\"][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the identity server\n *\n * @param medium - The medium of the threepid, eg. 'email'\n * @param address - The textual address of the threepid\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @returns Rejects: with an error response.\n */\n public async lookupThreePid(\n medium: string,\n address: string,\n identityAccessToken: string,\n ): Promise<\n | {\n address: string;\n medium: string;\n mxid: string;\n }\n | {}\n > {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup([[address, medium]], identityAccessToken);\n const result = response.find((p) => p.address === address);\n if (!result) {\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param query - Array of arrays containing\n * [medium, address]\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Lookup results from IS.\n * @returns Rejects: with an error response.\n */\n public async bulkLookupThreePids(\n query: [string, string][],\n identityAccessToken: string,\n ): Promise<{\n threepids: [medium: string, address: string, mxid: string][];\n }> {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map((p) => [p[1], p[0]]),\n identityAccessToken,\n );\n\n const v1results: [medium: string, address: string, mxid: string][] = [];\n for (const mapping of response) {\n const originalQuery = query.find((p) => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the identity server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: an object with account info.\n * @returns Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise<{ user_id: string }> {\n return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n }\n\n /**\n * Send an event to a specific list of devices.\n * This is a low-level API that simply wraps the HTTP API\n * call to send to-device messages. We recommend using\n * queueToDevice() which is a higher level API.\n *\n * @param eventType - type of event to send\n * content to send. Map from user_id to device_id to content object.\n * @param txnId - transaction id. One will be made up if not\n * supplied.\n * @returns Promise which resolves: to an empty object `{}`\n */\n public sendToDevice(eventType: string, contentMap: SendToDeviceContentMap, txnId?: string): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: utils.recursiveMapToObject(contentMap),\n };\n\n const targets = new Map<string, string[]>();\n\n for (const [userId, deviceMessages] of contentMap) {\n targets.set(userId, Array.from(deviceMessages.keys()));\n }\n\n this.logger.debug(`PUT ${path}`, targets);\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Sends events directly to specific devices using Matrix's to-device\n * messaging system. The batch will be split up into appropriately sized\n * batches for sending and stored in the store so they can be retried\n * later if they fail to send. Retries will happen automatically.\n * @param batch - The to-device messages to send\n */\n public queueToDevice(batch: ToDeviceBatch): Promise<void> {\n return this.toDeviceMessageQueue.queueBatch(batch);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<{ [protocol: string]: IProtocol }> {\n return this.http\n .authedRequest<Record<string, IProtocol>>(Method.Get, \"/thirdparty/protocols\")\n .then((response) => {\n // sanity check\n if (!response || typeof response !== \"object\") {\n throw new Error(`/thirdparty/protocols did not return an object: ${response}`);\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyLocation(\n protocol: string,\n params: { searchFields?: string[] },\n ): Promise<IThirdPartyLocation[]> {\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params?: QueryDict): Promise<IThirdPartyUser[]> {\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise<any> {\n // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(Method.Get, url);\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<{}> {\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n Method.Post,\n url,\n {\n user_accepts: termsUrls,\n },\n { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param roomId - The room in which the event being reported is located.\n * @param eventId - The event to report.\n * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param reason - The reason the content is being reported. May be blank.\n * @returns Promise which resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, { score, reason });\n }\n\n /**\n * Fetches or paginates a room hierarchy as defined by MSC2946.\n * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n * @param roomId - The ID of the space-room to use as the root of the summary.\n * @param limit - The maximum number of rooms to return per page.\n * @param maxDepth - The maximum depth in the tree from the root room to return.\n * @param suggestedOnly - Whether to only return rooms with suggested=true.\n * @param fromToken - The opaque token to paginate a previous request.\n * @returns the response, with next_batch & rooms fields.\n */\n public getRoomHierarchy(\n roomId: string,\n limit?: number,\n maxDepth?: number,\n suggestedOnly = false,\n fromToken?: string,\n ): Promise<IRoomHierarchy> {\n const path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n $roomId: roomId,\n });\n\n const queryParams: QueryDict = {\n suggested_only: String(suggestedOnly),\n max_depth: maxDepth?.toString(),\n from: fromToken,\n limit: limit?.toString(),\n };\n\n return this.http\n .authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n })\n .catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n // fall back to the prefixed hierarchy API.\n return this.http.authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n throw e;\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param name - The name of the tree space.\n * @returns Promise which resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise<MSC3089TreeSpace> {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()!]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n {\n type: EventType.RoomEncryption,\n state_key: \"\",\n content: {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param roomId - The room ID to get a tree space reference for.\n * @returns The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace | null {\n const room = this.getRoom(roomId);\n if (room?.getMyMembership() !== KnownMembership.Join) return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n );\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Perform a single MSC3575 sliding sync request.\n * @param req - The request to make.\n * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n * @param abortSignal - Optional signal to abort request mid-flight.\n * @returns The sliding sync response, or a standard error.\n * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n */\n public slidingSync(\n req: MSC3575SlidingSyncRequest,\n proxyBaseUrl?: string,\n abortSignal?: AbortSignal,\n ): Promise<MSC3575SlidingSyncResponse> {\n const qps: QueryDict = {};\n if (req.pos) {\n qps.pos = req.pos;\n delete req.pos;\n }\n if (req.timeout) {\n qps.timeout = req.timeout;\n delete req.timeout;\n }\n const clientTimeout = req.clientTimeout;\n delete req.clientTimeout;\n return this.http.authedRequest<MSC3575SlidingSyncResponse>(Method.Post, \"/sync\", qps, req, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3575\",\n baseUrl: proxyBaseUrl,\n localTimeoutMs: clientTimeout,\n abortSignal,\n });\n }\n\n /**\n * A helper to determine thread support\n * @returns a boolean to determine if threads are enabled\n */\n public supportsThreads(): boolean {\n return this.clientOpts?.threadSupport || false;\n }\n\n /**\n * A helper to determine intentional mentions support\n * @returns a boolean to determine if intentional mentions are enabled on the server\n * @experimental\n */\n public supportsIntentionalMentions(): boolean {\n return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;\n }\n\n /**\n * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n * @param via - The list of servers which know about the room if only an ID was provided.\n */\n public async getRoomSummary(roomIdOrAlias: string, via?: string[]): Promise<RoomSummary> {\n const paramOpts = {\n prefix: \"/_matrix/client/unstable/im.nheko.summary\",\n };\n try {\n const path = utils.encodeUri(\"/summary/$roomid\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } catch (e) {\n if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n const path = utils.encodeUri(\"/rooms/$roomid/summary\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * Processes a list of threaded events and adds them to their respective timelines\n * @param room - the room the adds the threaded events\n * @param threadedEvents - an array of the threaded events\n * @param toStartOfTimeline - the direction in which we want to add the events\n */\n public processThreadEvents(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n }\n\n /**\n * Processes a list of thread roots and creates a thread model\n * @param room - the room to create the threads in\n * @param threadedEvents - an array of thread roots\n * @param toStartOfTimeline - the direction\n */\n public processThreadRoots(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.supportsThreads()) return;\n room.processThreadRoots(threadedEvents, toStartOfTimeline);\n }\n\n public processBeaconEvents(room?: Room, events?: MatrixEvent[]): void {\n this.processAggregatedTimelineEvents(room, events);\n }\n\n /**\n * Calls aggregation functions for event types that are aggregated\n * Polls and location beacons\n * @param room - room the events belong to\n * @param events - timeline events to be processed\n * @returns\n */\n public processAggregatedTimelineEvents(room?: Room, events?: MatrixEvent[]): void {\n if (!events?.length) return;\n if (!room) return;\n\n room.currentState.processBeaconEvents(events, this);\n room.processPollEvents(events);\n }\n\n /**\n * Fetches information about the user for the configured access token.\n */\n public async whoami(): Promise<IWhoamiResponse> {\n return this.http.authedRequest(Method.Get, \"/account/whoami\");\n }\n\n /**\n * Find the event_id closest to the given timestamp in the given direction.\n * @returns Resolves: A promise of an object containing the event_id and\n * origin_server_ts of the closest event to the timestamp in the given direction\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n */\n public async timestampToEvent(\n roomId: string,\n timestamp: number,\n dir: Direction,\n ): Promise<TimestampToEventResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n $roomId: roomId,\n });\n const queryParams = {\n ts: timestamp.toString(),\n dir: dir,\n };\n\n try {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n });\n } catch (err) {\n // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n // new, we should also try the unstable endpoint before giving up. We can\n // remove this fallback request in a year (remove after 2023-11-28).\n if (\n (<MatrixError>err).errcode === \"M_UNRECOGNIZED\" &&\n // XXX: The 400 status code check should be removed in the future\n // when Synapse is compliant with MSC3743.\n ((<MatrixError>err).httpStatus === 400 ||\n // This the correct standard status code for an unsupported\n // endpoint according to MSC3743. Not Found and Method Not Allowed\n // both indicate that this endpoint+verb combination is\n // not supported.\n (<MatrixError>err).httpStatus === 404 ||\n (<MatrixError>err).httpStatus === 405)\n ) {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3030\",\n });\n }\n\n throw err;\n }\n }\n\n /**\n * Get the OIDC issuer responsible for authentication on this server, if any\n * @returns Resolves: A promise of an object containing the OIDC issuer if configured\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n * @experimental - part of MSC2965\n */\n public async getAuthIssuer(): Promise<{\n issuer: string;\n }> {\n return this.http.request(Method.Get, \"/auth_issuer\", undefined, undefined, {\n prefix: ClientPrefix.Unstable + \"/org.matrix.msc2965\",\n });\n }\n}\n\nfunction getUnstableDelayQueryOpts(delayOpts: SendDelayedEventRequestOpts): QueryDict {\n return Object.fromEntries(\n Object.entries(delayOpts).map(([k, v]) => [`${UNSTABLE_MSC4140_DELAYED_EVENTS}.${k}`, v]),\n );\n}\n\n/**\n * recalculates an accurate notifications count on event decryption.\n * Servers do not have enough knowledge about encrypted events to calculate an\n * accurate notification_count\n */\nexport function fixNotificationCountOnDecryption(cli: MatrixClient, event: MatrixEvent): void {\n const ourUserId = cli.getUserId();\n const eventId = event.getId();\n\n const room = cli.getRoom(event.getRoomId());\n if (!room || !ourUserId || !eventId) return;\n\n // Due to threads, we can get relation events (eg. edits & reactions) that never get\n // added to a timeline and so cannot be found in their own room (their edit / reaction\n // still applies to the event it needs to, so it doesn't matter too much). However, if\n // we try to process notification about this event, we'll get very confused because we\n // won't be able to find the event in the room, so will assume it must be unread, even\n // if it's actually read. We therefore skip anything that isn't in the room. This isn't\n // *great*, so if we can fix the homeless events (eg. with MSC4023) then we should probably\n // remove this workaround.\n if (!room.findEventById(eventId)) {\n logger.info(`Decrypted event ${event.getId()} is not in room ${room.roomId}: ignoring`);\n return;\n }\n\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n let hasReadEvent;\n if (isThreadEvent) {\n const thread = room.getThread(event.threadRootId);\n hasReadEvent = thread\n ? thread.hasUserReadEvent(ourUserId, eventId)\n : // If the thread object does not exist in the room yet, we don't\n // want to calculate notification for this event yet. We have not\n // restored the read receipts yet and can't accurately calculate\n // notifications at this stage.\n //\n // This issue can likely go away when MSC3874 is implemented\n true;\n } else {\n hasReadEvent = room.hasUserReadEvent(ourUserId, eventId);\n }\n\n if (hasReadEvent) {\n // If the event has been read, ignore it.\n return;\n }\n\n const actions = cli.getPushActionsForEvent(event, true);\n\n // Ensure the unread counts are kept up to date if the event is encrypted\n // We also want to make sure that the notification count goes up if we already\n // have encrypted events to avoid other code from resetting 'highlight' to zero.\n const newHighlight = !!actions?.tweaks?.highlight;\n\n if (newHighlight) {\n // TODO: Handle mentions received while the client is offline\n // See also https://github.com/vector-im/element-web/issues/9069\n const newCount = room.getUnreadCountForEventContext(NotificationCountType.Highlight, event) + 1;\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Highlight, newCount);\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);\n }\n }\n\n // `notify` is used in practice for incrementing the total count\n const newNotify = !!actions?.notify;\n\n // The room total count is NEVER incremented by the server for encrypted rooms. We basically ignore\n // the server here as it's always going to tell us to increment for encrypted events.\n if (newNotify) {\n // Total count is used to typically increment a room notification counter, but not loudly highlight it.\n const newCount = room.getUnreadCountForEventContext(NotificationCountType.Total, event) + 1;\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Total, newCount);\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Total, newCount);\n }\n }\n}\n\n/**\n * Given an event, figure out the thread ID we should use for it in a receipt.\n *\n * This will either be \"main\", or event.threadRootId. For the thread root, or\n * e.g. reactions to the thread root, this will be main. For events inside the\n * thread, or e.g. reactions to them, this will be event.threadRootId.\n *\n * (Exported for test.)\n */\nexport function threadIdForReceipt(event: MatrixEvent): string {\n return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId!;\n}\n\n/**\n * a) True for non-threaded messages, thread roots and non-thread relations to thread roots.\n * b) False for messages with thread relations to the thread root.\n * c) False for messages with any kind of relation to a message from case b.\n *\n * Note: true for redactions of messages that are in threads. Redacted messages\n * are not really in threads (because their relations are gone), so if they look\n * like they are in threads, that is a sign of a bug elsewhere. (At time of\n * writing, this bug definitely exists - messages are not moved to another\n * thread when they are redacted.)\n *\n * @returns true if this event is considered to be in the main timeline as far\n * as receipts are concerned.\n */\nexport function inMainTimelineForReceipt(event: MatrixEvent): boolean {\n if (!event.threadRootId) {\n // Not in a thread: then it is in the main timeline\n return true;\n }\n\n if (event.isThreadRoot) {\n // Thread roots are in the main timeline. Note: the spec is ambiguous (or\n // wrong) on this - see\n // https://github.com/matrix-org/matrix-spec-proposals/pull/4037\n return true;\n }\n\n if (!event.isRelation()) {\n // If it's not related to anything, it can't be related via a chain of\n // relations to a thread root.\n //\n // Note: this is a bug, because how does it have a threadRootId if it is\n // neither a thread root, nor related to one?\n logger.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${event.getId()}`);\n return true;\n }\n\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n // It's a message in a thread - definitely not in the main timeline.\n return false;\n }\n\n const isRelatedToRoot = event.relationEventId === event.threadRootId;\n\n // If it's related to the thread root (and we already know it's not a thread\n // relation) then it's in the main timeline. If it's related to something\n // else, then it's in the thread (because it has a thread ID).\n return isRelatedToRoot;\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAKA,SAAsCA,OAAO,EAAkBC,SAAS,QAAQ,WAAW;AAC3F,SACIC,WAAW,EAIXC,WAAW,EACXC,gBAAgB,QAGb,mBAAmB;AAC1B,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAAyCC,mBAAmB,EAAcC,kBAAkB,QAAQ,kBAAkB;AACtH,SAASC,MAAM,QAA6C,aAAa;AACzE,SAASC,gBAAgB,QAAgE,8BAA8B;AACvH,SACIC,qBAAqB,QAGlB,mCAAmC;AAC1C,OAAO,KAAKC,KAAK,MAAM,YAAY;AACnC,SAASC,kBAAkB,EAAaC,YAAY,EAAEC,OAAO,EAAEC,KAAK,QAAQ,YAAY;AACxF,SAASC,SAAS,EAAEC,aAAa,QAAQ,4BAA4B;AACrE,SAAyBC,aAAa,QA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