Class RoomWidgetClientExperimental

A MatrixClient that routes its requests through the widget API instead of the real CS API. This class is considered unstable!

Hierarchy (view full)

Constructors

Properties

Accessors

Methods

_unstable_getDelayedEvents _unstable_getSharedRooms _unstable_sendDelayedEvent _unstable_sendDelayedStateEvent _unstable_updateDelayedEvent addListener addPushRule addSecretStorageKey addThreePidOnly agreeToTerms backPaginateRoomEventsSearch ban beginKeyVerification bindThreePid bootstrapCrossSigning bootstrapSecretStorage buildSyncApiOptions bulkLookupThreePids cancelAndResendEventRoomKeyRequest cancelPendingEvent cancelUpload checkCrossSigningPrivateKey checkDeviceTrust checkIfOwnDeviceCrossSigned checkKeyBackup checkOwnCrossSigningTrust checkSecretStorageKey checkSecretStoragePrivateKey checkTurnServers checkUserTrust claimOneTimeKeys clearStores countSessionsNeedingBackup createAlias createCall createDehydratedDevice createFilter createGroupCall createKeyBackupVersion createMessagesRequest createRecoveryKeyFromPassphrase createRoom createThreadListMessagesRequest deactivateAccount deactivateSynapseUser decryptEventIfNeeded deleteAccountData deleteAlias deleteDevice deleteExtendedProfileProperty deleteKeyBackupVersion deleteKeysFromBackup deleteMultipleDevices deletePushRule deleteRoomTag deleteThreePid disableKeyBackup doesServerForceEncryptionForPreset doesServerSupportExtendedProfiles doesServerSupportThread doesServerSupportUnstableFeature downloadKeys downloadKeysForUsers emit emitPromised enableKeyBackup encryptAndSendEvent encryptAndSendToDevices exportDevice exportRoomKeys fetchCapabilities fetchClientWellKnown fetchRelations fetchRoomEvent findVerificationRequestDMInProgress flagAllGroupSessionsForBackup forceDiscardSession forget generateClientSecret getAccessToken getAccountData getAccountDataFromServer getAuthIssuer getCachedCapabilities getCanResetTimelineCallback getCapabilities getCasLoginUrl getClientWellKnown getCrossSigningCacheCallbacks getCrossSigningId getCrypto getCryptoTrustCrossSignedDevices getCurrentUploads getDefaultSecretStorageKeyId getDehydratedDevice getDevice getDeviceCurve25519Key getDeviceEd25519Key getDeviceId getDevices getDomain getEventEncryptionInfo getEventMapper getEventSenderDeviceInfo getEventTimeline getExtendedProfile getExtendedProfileProperty getFallbackAuthUrl getFilter getGlobalBlacklistUnverifiedDevices getGlobalErrorOnUnknownDevices getGroupCallForRoom getHomeserverUrl getIdentityAccount getIdentityHashDetails getIdentityServerUrl getIgnoredUsers getJoinedRoomMembers getJoinedRooms getKeyBackupEnabled getKeyBackupVersion getKeyChanges getLatestTimeline getLivekitServiceURL getLocalAliases getMediaConfig getMediaHandler getNotifTimelineSet getOpenIdToken getOrCreateFilter getOutgoingRoomKeyRequest getPresence getProfileInfo getPushActionsForEvent getPushDetailsForEvent getPushers getPushRules getRefreshToken getRoom getRoomDirectoryVisibility getRoomHierarchy getRoomIdForAlias getRoomPushRule getRooms getRoomSummary getRoomTags getRoomUpgradeHistory getSafeUserId getScheduler getSecret getSessionId getSsoLoginUrl getStateEvent getStoredCrossSigningForUser getStoredDevice getStoredDevicesForUser getSyncState getSyncStateData getTerms getThirdpartyLocation getThirdpartyProtocols getThirdpartyUser getThreadTimeline getThreePids getTurnServers getTurnServersExpiry getUrlPreview getUseE2eForGroupCall getUser getUserId getUserIdLocalpart getUsers getVerificationRequestsToDeviceInProgress getVersions getVisibleRooms hasLazyLoadMembersEnabled hasSecretStorageKey identityHashedLookup importRoomKeys initCrypto initRustCrypto invite inviteByEmail inviteByThreePid isCrossSigningReady isCryptoEnabled isEventSenderVerified isFallbackICEServerAllowed isGuest isInitialSyncComplete isKeyBackupKeyStored isKeyBackupTrusted isLoggedIn isRoomEncrypted isSecretStorageReady isSecretStored isSynapseAdministrator isUserIgnored isUsernameAvailable isValidRecoveryKey isVersionSupported joinRoom keyBackupKeyFromPassword keyBackupKeyFromRecoveryKey kick knockRoom leave leaveRoomChain legacyDeviceVerification listenerCount listeners login loginFlows loginWithPassword loginWithToken logout lookupThreePid makeTxnId members mxcUrlToHttp off on once paginateEventTimeline patchExtendedProfile peekInRoom prepareKeyBackupVersion prepareToEncrypt prependListener prependOnceListener processAggregatedTimelineEvents processBeaconEvents processRoomEventsSearch processThreadEvents processThreadRoots publicRooms queueToDevice rawListeners redactEvent refreshToken register registerGuest registerRequest registerWithIdentityServer rehydrateDevice relations removeAllListeners removeListener removePusher reportEvent requestAdd3pidEmailToken requestAdd3pidMsisdnToken requestEmailToken requestLoginToken requestMsisdnToken requestPasswordEmailToken requestPasswordMsisdnToken requestRegisterEmailToken requestRegisterMsisdnToken requestSecret requestVerification requestVerificationDM resendEvent resetNotifTimelineSet restoreKeyBackupWithCache restoreKeyBackupWithPassword restoreKeyBackupWithRecoveryKey restoreKeyBackupWithSecretStorage retryImmediately roomInitialSync roomState scheduleAllGroupSessionsForBackup scrollback search searchMessageText searchRoomEvents searchUserDirectory sendEmoteMessage sendEvent sendHtmlEmote sendHtmlMessage sendHtmlNotice sendImageMessage sendKeyBackup sendMessage sendNotice sendReadReceipt sendReceipt sendStateEvent sendStickerMessage sendTextMessage sendToDevice sendTyping setAccessToken setAccountData setAvatarUrl setCanResetTimelineCallback setCryptoTrustCrossSignedDevices setDefaultSecretStorageKeyId setDehydrationKey setDeviceBlocked setDeviceDetails setDeviceKnown setDeviceVerified setDisplayName setExtendedProfile setExtendedProfileProperty setFallbackICEServerAllowed setForceTURN setGlobalBlacklistUnverifiedDevices setGlobalErrorOnUnknownDevices setGuest setGuestAccess setIdentityServerUrl setIgnoredUsers setLivekitServiceURL setLocalNotificationSettings setNotifTimelineSet setPassword setPowerLevel setPresence setProfileInfo setPusher setPushRuleActions setPushRuleEnabled setPushRules setRoomAccountData setRoomDirectoryVisibility setRoomEncryption setRoomMutePushRule setRoomName setRoomReadMarkers setRoomReadMarkersHttpRequest setRoomTag setRoomTopic setSupportsCallTransfer setSyncPresence slidingSync startClient stopClient stopPeeking storeClientOptions storeSecret submitMsisdnToken submitMsisdnTokenOtherUrl supportsIntentionalMentions supportsThreads supportsVoip syncLeftRooms timestampToEvent turnServer unban unbindThreePid unstable_createLiveBeacon unstable_setLiveBeacon unstableCreateFileTree unstableGetFileTreeSpace updatePendingEventStatus upgradeRoom uploadContent uploadDeviceSigningKeys uploadKeys uploadKeySignatures uploadKeysRequest userHasCrossSigningKeys waitForClientWellKnown waitUntilRoomReadyForGroupCalls whoami whoisSynapseUser

Constructors

  • Experimental

    Parameters

    • widgetApi: WidgetApi

      The widget api to use for communication.

    • capabilities: ICapabilities

      The capabilities the widget client will request.

    • roomId: string

      The room id the widget is associated with.

    • opts: IMatrixClientCreateOpts

      The configuration options for this client.

    • sendContentLoaded: boolean

      Whether to send a content loaded widget action immediately after initial setup. Set to false if the widget uses waitForIFrameLoad=true (in this case the client does not expect a content loaded action at all), or if the the widget wants to send the ContentLoaded action at a later point in time after the initial setup.

    Returns RoomWidgetClient

Properties

baseUrl: string
callEventHandler?: CallEventHandler
canResetTimelineCallback?: ResetTimelineCallback
canSupport: Map<Feature, ServerSupport> = ...
canSupportVoip: boolean = false
checkTurnServersIntervalID?: Timeout
clientOpts?: IStoredClientOpts
clientRunning: boolean = false
clientWellKnown?: IClientWellKnown
clientWellKnownIntervalID?: Timeout
clientWellKnownPromise?: Promise<IClientWellKnown>
credentials: {
    userId: null | string;
}
crypto?: Crypto

The libolm crypto implementation, if it is in use.

This should not be used. Instead, use the methods exposed directly on this class or (where they are available) via getCrypto.

cryptoCallbacks: CryptoCallbacks
cryptoStore?: CryptoStore
deviceId: null | string
exportedOlmDeviceToImport?: IExportedDevice
fallbackICEServerAllowed: boolean = false
forceTURN: boolean = false
groupCallEventHandler?: GroupCallEventHandler
http: MatrixHttpApi<IHttpOpts & {
    onlyData: true;
}>
iceCandidatePoolSize: number = 0
idBaseUrl?: string
identityServer?: IIdentityServerProvider
ignoredInvites: IgnoredInvites
isGuestAccount: boolean = false
isVoipWithNoMediaAllowed: boolean
livekitServiceURL?: string
mediaHandler: MediaHandler = ...
notifTimelineSet: null | EventTimelineSet = null
olmVersion: null | [number, number, number] = null
ongoingScrollbacks: {
    [roomId: string]: {
        errorTs?: number;
        promise?: Promise<Room>;
    };
} = {}
peekSync: null | SyncApi = null
pickleKey?: string

Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.

As supplied in the constructor via IMatrixClientCreateOpts#pickleKey.

If unset, either a hardcoded key or no encryption at all is used, depending on the Crypto implementation.

this should be a private property.

pushProcessor: PushProcessor = ...
pushRules?: IPushRules
roomNameGenerator?: ((roomId: string, state: RoomNameState) => null | string)
serverVersionsPromise?: Promise<IServerVersions>
sessionId: string
supportsCallTransfer: boolean = false
syncedLeftRooms: boolean = false
syncLeftRoomsPromise?: Promise<Room[]>
timelineSupport: boolean = false
turnServers: ITurnServer[] = []
turnServersExpiry: number = 0
txnCtr: number = 0
urlPreviewCache: {
    [key: string]: Promise<IPreviewUrlResponse>;
} = {}
useLivekitForGroupCalls: boolean
usingExternalCrypto: boolean = false
verificationMethods?: string[]
RESTORE_BACKUP_ERROR_BAD_KEY = "RESTORE_BACKUP_ERROR_BAD_KEY"

Accessors

  • get pollingTurnServers(): boolean
  • Experimental

    Returns boolean

Methods

  • Experimental

    Gets a set of room IDs in common with another user.

    Note: This endpoint is unstable, and can throw an Error. Check progress on MSC2666 for more details.

    Parameters

    • userId: string

      The userId to check.

    Returns Promise<string[]>

    Promise which resolves to an array of rooms

  • Experimental

    Add a 3PID to your homeserver account. This API does not use an identity server, as the homeserver is expected to handle 3PID ownership validation.

    Parameters

    • data: IAddThreePidOnlyBody

      A object with 3PID validation data from having called account/3pid/<medium>/requestToken on the homeserver.

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Bind a 3PID for discovery onto an identity server via the homeserver. The identity server handles 3PID ownership validation and the homeserver records the new binding to track where all 3PIDs for the account are bound.

    Parameters

    • data: IBindThreePidBody

      A object with 3PID validation data from having called validate/<medium>/requestToken on the identity server. It should also contain id_server and id_access_token fields as well.

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Bootstrap Secure Secret Storage if needed by creating a default key. If everything is already set up, then no changes are made, so this is safe to run to ensure secret storage is ready for use.

    This function

    • creates a new Secure Secret Storage key if no default key exists
      • if a key backup exists, it is migrated to store the key in the Secret Storage
    • creates a backup if none exists, and one is requested
    • migrates Secure Secret Storage to use the latest algorithm, if an outdated algorithm is found

    Parameters

    Returns Promise<void>

  • Experimental

    Looks up the public Matrix ID mappings for multiple 3PIDs.

    Parameters

    • query: [string, string][]

      Array of arrays containing [medium, address]

    • identityAccessToken: string

      The access_token field of the Identity Server /account/register response (see registerWithIdentityServer).

    Returns Promise<{
        threepids: [medium: string, address: string, mxid: string][];
    }>

    Promise which resolves: Lookup results from IS.

  • Experimental

    Cancel a room key request for this event if one is ongoing and resend the request.

    Parameters

    • event: MatrixEvent

      event of which to cancel and resend the room key request.

    Returns Promise<void>

    A promise that will resolve when the key request is queued

    Not supported for Rust Cryptography.

  • Experimental

    Checks that a given cross-signing private key matches a given public key. This can be used by the getCrossSigningKey callback to verify that the private key it is about to supply is the one that was requested.

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

    true if the key matches, otherwise false

    Not supported for Rust Cryptography.

  • Experimental

    Check whether one of our own devices is cross-signed by our user's stored keys, regardless of whether we trust those keys yet.

    Parameters

    • deviceId: string

      The ID of the device to check

    Returns boolean

    true if the device is cross-signed

    Not supported for Rust Cryptography.

  • Experimental

    Checks that a given secret storage private key matches a given public key. This can be used by the getSecretStorageKey callback to verify that the private key it is about to supply is the one that was requested.

    The Secure Secret Storage API is currently UNSTABLE and may change without notice.

    Parameters

    • privateKey: Uint8Array

      The private key

    • expectedPublicKey: string

      The public key

    Returns boolean

    true if the key matches, otherwise false

    The use of asymmetric keys for SSSS is deprecated. Use SecretStorage.ServerSideSecretStorage#checkKey for symmetric keys.

  • Experimental

    Claim one-time keys

    Parameters

    • devices: [string, string][]

      a list of [userId, deviceId] pairs

    • keyAlgorithm: string = "signed_curve25519"

      desired key type

    • Optionaltimeout: number

      the time (in milliseconds) to wait for keys from remote servers

    Returns Promise<IClaimOTKsResult>

    Promise which resolves: result object. Rejects: with an error response (MatrixError).

  • Experimental

    Counts the number of end to end session keys that are waiting to be backed up

    Returns Promise<number>

    Promise which resolves to the number of sessions requiring backup

    Not supported for Rust Cryptography.

  • Experimental

    Create an alias to room ID mapping.

    Parameters

    • alias: string

      The room alias to create.

    • roomId: string

      The room ID to link the alias to.

    Returns Promise<{}>

    Promise which resolves: an empty object {}

  • Experimental

    Creates a new call. The place*Call methods on the returned call can be used to actually place a call

    Parameters

    • roomId: string

      The room the call is to be placed in.

    Returns null | MatrixCall

    the call or null if the browser doesn't support calling.

  • Experimental

    Creates a new MSC2967 dehydrated device (without queuing periodic dehydration)

    Parameters

    • key: Uint8Array

      the dehydration key

    • keyInfo: IDehydratedDeviceKeyInfo

      Information about the key. Primarily for information about how to generate the key from a passphrase.

    • OptionaldeviceDisplayName: string

      The device display name for the dehydrated device.

    Returns Promise<undefined | string>

    the device id of the newly created dehydrated device

    Not supported for Rust Cryptography. Prefer CryptoApi.startDehydration.

  • Experimental

    Makes a request to /messages with the appropriate lazy loading filter set. XXX: if we do get rid of scrollback (as it's not used at the moment), we could inline this method again in paginateEventTimeline as that would then be the only call-site

    Parameters

    • roomId: string
    • fromToken: null | string
    • limit: number = 30

      the maximum amount of events the retrieve

    • dir: Direction

      'f' or 'b'

    • OptionaltimelineFilter: Filter

      the timeline filter to pass

    Returns Promise<IMessagesResponse>

  • Experimental

    Create a new room.

    Parameters

    Returns Promise<{
        room_id: string;
    }>

    Promise which resolves: {room_id: {string}}

  • Experimental

    Makes a request to /messages with the appropriate lazy loading filter set. XXX: if we do get rid of scrollback (as it's not used at the moment), we could inline this method again in paginateEventTimeline as that would then be the only call-site

    Parameters

    • roomId: string
    • fromToken: null | string
    • limit: number = 30

      the maximum amount of events the retrieve

    • dir: Direction = Direction.Backward

      'f' or 'b'

    • threadListType: null | ThreadFilterType = ThreadFilterType.All
    • OptionaltimelineFilter: Filter

      the timeline filter to pass

    Returns Promise<IMessagesResponse>

  • Experimental

    Deactivates the logged-in account. Obviously, further calls that require authorisation should fail after this method is called. The state of the MatrixClient object is not affected: it is up to the caller to either reset or destroy the MatrixClient after this method succeeds.

    Parameters

    • Optionalauth: AuthDict

      Optional. Auth data to supply for User-Interactive auth.

    • Optionalerase: boolean

      Optional. If set, send as erase attribute in the JSON request body, indicating whether the account should be erased. Defaults to false.

    Returns Promise<{
        id_server_unbind_result: IdServerUnbindResult;
    }>

    Promise which resolves: On success, the empty object

  • Experimental

    Delete an alias to room ID mapping. This alias must be on your local server, and you must have sufficient access to do this operation.

    Parameters

    • alias: string

      The room alias to delete.

    Returns Promise<{}>

    Promise which resolves: an empty object {}.

  • Experimental

    Delete the given device

    Parameters

    • deviceId: string

      device to delete

    • Optionalauth: AuthDict

      Optional. Auth data to supply for User-Interactive auth.

    Returns Promise<{}>

    Promise which resolves: result object

  • Experimental

    Parameters

    • medium: string

      The threepid medium (eg. 'email')

    • address: string

      The threepid address (eg. 'bob@example.com') this must be as returned by getThreePids.

    Returns Promise<{
        id_server_unbind_result: IdServerUnbindResult;
    }>

    Promise which resolves: The server response on success (generally the empty JSON object)

  • Experimental

    Disable backing up of keys.

    Returns void

    Not supported for Rust Cryptography. It should be unnecessary to disable key backup.

  • Experimental

    Query the server to see if it is forcing encryption to be enabled for a given room preset, based on the /versions response.

    Parameters

    • presetName: Preset

      The name of the preset to check.

    Returns Promise<boolean>

    true if the server is forcing encryption for the preset.

  • Experimental

    Synchronously calls each of the listeners registered for the event named event, in the order they were registered, passing the supplied arguments to each.

    Type Parameters

    Parameters

    Returns boolean

    true if the event had listeners, false otherwise.

  • Experimental

    Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import EventEmitter from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Type Parameters

    Parameters

    Returns boolean

    v0.1.26

  • Experimental

    Encrypts and sends a given object via Olm to-device messages to a given set of devices.

    Parameters

    • userDeviceInfoArr: IOlmDevice<DeviceInfo>[]

      list of deviceInfo objects representing the devices to send to

    • payload: object

      fields to include in the encrypted payload

    Returns Promise<void>

    Promise which resolves once the message has been encrypted and sent to the given userDeviceMap, and returns the { contentMap, deviceInfoByDeviceId } of the successfully sent messages.

    Instead use CryptoApi.encryptToDeviceMessages followed by queueToDevice.

  • Experimental

    Fetches relations for a given event

    Parameters

    • roomId: string

      the room of the event

    • eventId: string

      the id of the event

    • relationType: null | string

      the rel_type of the relations requested

    • OptionaleventType: null | string

      the event type of the relations requested

    • opts: IRelationsRequestOpts = ...

      options with optional values for the request.

    Returns Promise<IRelationsResponse>

    the response, with chunk, prev_batch and, next_batch.

  • Experimental

    Marks all group sessions as needing to be backed up without scheduling them to upload in the background.

    (This is done automatically as part of CryptoApi.resetKeyBackup, so there is probably no need to call this manually.)

    Returns Promise<number>

    Promise which resolves to the number of sessions requiring a backup.

    Not supported for Rust Cryptography.

  • Experimental

    Parameters

    • roomId: string
    • deleteRoom: boolean = true

      True to delete the room from the store on success. Default: true.

    Returns Promise<{}>

    Promise which resolves: {} an empty object.

  • Experimental

    Generates a random string suitable for use as a client secret. This method is experimental and may change.

    Returns string

    A new client secret

  • Experimental

    Get account data event of given type for the current user. This variant gets account data directly from the homeserver if the local store is not ready, which can be useful very early in startup before the initial sync.

    Type Parameters

    • T extends {
          [k: string]: any;
      }

    Parameters

    • eventType: string

      The event type

    Returns Promise<null | T>

    Promise which resolves: The contents of the given account data event.

  • Experimental

    Get the OIDC issuer responsible for authentication on this server, if any

    Returns Promise<{
        issuer: string;
    }>

    Resolves: A promise of an object containing the OIDC issuer if configured

  • Experimental

    Parameters

    • redirectUrl: string

      The URL to redirect to after the HS authenticates with CAS.

    Returns string

    The HS URL to hit to begin the CAS login process.

  • Experimental

    Get the ID of one of the user's cross-signing keys

    Parameters

    • type: string = CrossSigningKey.Master

      The type of key to get the ID of. One of "master", "self_signing", or "user_signing". Defaults to "master".

    Returns null | string

    the key ID

    Not supported for Rust Cryptography. prefer Crypto.CryptoApi#getCrossSigningKeyId

  • Experimental

    Get a list of all file uploads in progress

    Returns Upload[]

    Array of objects representing current uploads. Currently in progress is element 0. Keys:

    • promise: The promise associated with the upload
    • loaded: Number of bytes uploaded
    • total: Total number of bytes to upload
  • Experimental

    Get an EventTimeline for the given event

    If the EventTimelineSet object already has the given event in its store, the corresponding timeline will be returned. Otherwise, a /context request is made, and used to construct an EventTimeline. If the event does not belong to this EventTimelineSet then undefined will be returned.

    Parameters

    • timelineSet: EventTimelineSet

      The timelineSet to look for the event in, must be bound to a room

    • eventId: string

      The ID of the event to look for

    Returns Promise<Optional<EventTimeline>>

    Promise which resolves: EventTimeline including the given event

  • Experimental

    Get the fallback URL to use for unknown interactive-auth stages.

    Parameters

    • loginType: string

      the type of stage being attempted

    • authSessionId: string

      the auth session ID provided by the homeserver

    Returns string

    HS URL to hit to for the fallback interface

  • Experimental

    Retrieve a filter.

    Parameters

    • userId: string

      The user ID of the filter owner

    • filterId: string

      The filter ID to retrieve

    • allowCached: boolean

      True to allow cached filters to be returned. Default: True.

    Returns Promise<Filter>

    Promise which resolves: a Filter object

  • Experimental

    Get account info from the identity server. This is useful as a neutral check to verify that other APIs are likely to approve access by testing that the token is valid, terms have been agreed, etc.

    Parameters

    • identityAccessToken: string

      The access_token field of the Identity Server /account/register response (see registerWithIdentityServer).

    Returns Promise<{
        user_id: string;
    }>

    Promise which resolves: an object with account info.

  • Experimental

    Gets the V2 hashing information from the identity server. Primarily useful for lookups.

    Parameters

    • identityAccessToken: string

      The access token for the identity server.

    Returns Promise<{
        algorithms: string[];
        lookup_pepper: string;
    }>

    The hashing information for the identity server.

  • Experimental

    Get the identity server URL of this client

    Parameters

    • stripProto: boolean = false

      whether or not to strip the protocol from the URL

    Returns undefined | string

    Identity server URL of this client

  • Experimental

    Gets the users that are ignored by this client

    Returns string[]

    The array of users that are ignored (empty if none)

  • Experimental

    Returns null | boolean

    true if the client is configured to back up keys to the server, otherwise false. If we haven't completed a successful check of key backup status yet, returns null.

    Not supported for Rust Cryptography. Prefer direct access to Crypto.CryptoApi.getActiveSessionBackupVersion:

    let enabled = (await client.getCrypto().getActiveSessionBackupVersion()) !== null;
    
  • Experimental

    Get information about the current key backup from the server.

    Performs some basic validity checks on the shape of the result, and raises an error if it is not as expected.

    Note: there is no (supported) way to distinguish between "failure to talk to the server" and "another client uploaded a key backup version using an algorithm I don't understand.

    Returns Promise<null | KeyBackupInfo>

    Information object from API, or null if no backup is present on the server.

  • Experimental

    Ask the server for a list of users who have changed their device lists between a pair of sync tokens

    Parameters

    • oldToken: string
    • newToken: string

    Returns Promise<{
        changed: string[];
        left: string[];
    }>

    Promise which resolves: result object. Rejects: with an error response (MatrixError).

  • Experimental

    Gets the local aliases for the room. Note: this includes all local aliases, unlike the curated list from the m.room.canonical_alias state event.

    Parameters

    • roomId: string

      The room ID to get local aliases for.

    Returns Promise<{
        aliases: string[];
    }>

    Promise which resolves: an object with an aliases property, containing an array of local aliases

  • Experimental

    Parameters

    • userId: string
    • Optionalinfo: string

      The kind of info to retrieve (e.g. 'displayname', 'avatar_url').

    Returns Promise<{
        avatar_url?: string;
        displayname?: string;
    }>

    Promise which resolves: TODO

  • Experimental

    Obtain a dict of actions which should be performed for this event according to the push rules for this user. Caches the dict on the event.

    Parameters

    • event: MatrixEvent

      The event to get push actions for.

    • forceRecalculate: boolean = false

      forces to recalculate actions for an event Useful when an event just got decrypted

    Returns null | IActionsObject

    A dict of actions to perform.

  • Experimental

    Obtain a dict of actions which should be performed for this event according to the push rules for this user. Caches the dict on the event.

    Parameters

    • event: MatrixEvent

      The event to get push actions for.

    • forceRecalculate: boolean = false

      forces to recalculate actions for an event Useful when an event just got decrypted

    Returns null | PushDetails

    A dict of actions to perform.

  • Experimental

    Get the room for the given room ID. This function will return a valid room for any room for which a Room event has been emitted. Note in particular that other events, eg. RoomState.members will be emitted for a room before this function will return the given room.

    Parameters

    • roomId: undefined | string

      The room ID

    Returns null | Room

    The Room or null if it doesn't exist or there is no data store.

  • Experimental

    Fetches or paginates a room hierarchy as defined by MSC2946. Falls back gracefully to sourcing its data from getSpaceSummary if this API is not yet supported by the server.

    Parameters

    • roomId: string

      The ID of the space-room to use as the root of the summary.

    • Optionallimit: number

      The maximum number of rooms to return per page.

    • OptionalmaxDepth: number

      The maximum depth in the tree from the root room to return.

    • suggestedOnly: boolean = false

      Whether to only return rooms with suggested=true.

    • OptionalfromToken: string

      The opaque token to paginate a previous request.

    Returns Promise<IRoomHierarchy>

    the response, with next_batch & rooms fields.

  • Experimental

    Get room info for the given alias.

    Parameters

    • alias: string

      The room alias to resolve.

    Returns Promise<{
        room_id: string;
        servers: string[];
    }>

    Promise which resolves: Object with room_id and servers.

  • Experimental

    Get the room-kind push rule associated with a room.

    Parameters

    • scope: "global" | "device"

      "global" or device-specific.

    • roomId: string

      the id of the room.

    Returns undefined | IPushRule

    the rule or undefined.

  • Experimental

    Determines the history of room upgrades for a given room, as far as the client can see. Returns an array of Rooms where the first entry is the oldest and the last entry is the newest (likely current) room. If the provided room is not found, this returns an empty list. This works in both directions, looking for older and newer rooms of the given room.

    Parameters

    • roomId: string

      The room ID to search from

    • verifyLinks: boolean = false

      If true, the function will only return rooms which can be proven to be linked. For example, rooms which have a create event pointing to an old room which the client is not aware of or doesn't have a matching tombstone would not be returned.

    • msc3946ProcessDynamicPredecessor: boolean = false

      if true, look for m.room.predecessor state events as well as create events, and prefer predecessor events where they exist (MSC3946).

    Returns Room[]

    An array of rooms representing the upgrade history.

  • Experimental

    Parameters

    • redirectUrl: string

      The URL to redirect to after the HS authenticates with the SSO.

    • loginType: string = "sso"

      The type of SSO login we are doing (sso or cas). Defaults to 'sso'.

    • OptionalidpId: string

      The ID of the Identity Provider being targeted, optional.

    • Optionalaction: SSOAction

      the SSO flow to indicate to the IdP, optional.

    Returns string

    The HS URL to hit to begin the SSO login process.

  • Experimental

    Get information on how a specific place on a third party protocol may be reached.

    Parameters

    • protocol: string

      The protocol given in getThirdpartyProtocols()

    • params: {
          searchFields?: string[];
      }

      Protocol-specific parameters, as given in the response to getThirdpartyProtocols()

      • OptionalsearchFields?: string[]

    Returns Promise<IThirdPartyLocation[]>

    Promise which resolves to the result object

  • Experimental

    Get the unix timestamp (in milliseconds) at which the current TURN credentials (from getTurnServers) expire

    Returns number

    The expiry timestamp in milliseconds

  • Experimental

    Get a preview of the given URL as of (roughly) the given point in time, described as an object with OpenGraph keys and associated values. Attributes may be synthesized where actual OG metadata is lacking. Caches results to prevent hammering the server.

    Parameters

    • url: string

      The URL to get preview data for

    • ts: number

      The preferred point in time that the preview should describe (ms since epoch). The preview returned will either be the most recent one preceding this timestamp if available, or failing that the next most recent available preview.

    Returns Promise<IPreviewUrlResponse>

    Promise which resolves: Object of OG metadata.

  • Experimental

    Returns true if to-device signalling for group calls will be encrypted with Olm. If false, it will be sent unencrypted.

    Returns boolean

    boolean Whether group call signalling will be encrypted

  • Experimental

    Retrieve a user.

    Parameters

    • userId: string

      The user ID to retrieve.

    Returns null | User

    A user or null if there is no data store or the user does not exist.

  • Experimental

    Get the user-id of the logged-in user

    Returns null | string

    MXID for the logged-in user, or null if not logged in

  • Experimental

    Get the local part of the current user ID e.g. "foo" in "@foo:bar".

    Returns null | string

    The user ID localpart or null.

  • Experimental

    Retrieve all rooms that should be displayed to the user This is essentially getRooms() with some rooms filtered out, eg. old versions of rooms that have been replaced or (in future) other rooms that have been marked at the protocol level as not to be displayed to the user.

    Parameters

    • msc3946ProcessDynamicPredecessor: boolean = false

      if true, look for an m.room.predecessor state event and use it if found (MSC3946).

    Returns Room[]

    A list of rooms, or an empty list if there is no data store.

  • Experimental

    Performs a hashed lookup of addresses against the identity server. This is only supported on identity servers which have at least the version 2 API.

    Parameters

    • addressPairs: [string, string][]

      An array of 2 element arrays. The first element of each pair is the address, the second is the 3PID medium. Eg: ["email@example.org", "email"]

    • identityAccessToken: string

      The access token for the identity server.

    Returns Promise<{
        address: string;
        mxid: string;
    }[]>

    A collection of address mappings to found MXIDs. Results where no user could be found will not be listed.

  • Experimental

    Initialise support for end-to-end encryption in this client, using libolm.

    You should call this method after creating the matrixclient, but before calling startClient, if you want to support end-to-end encryption.

    It will return a Promise which will resolve when the crypto layer has been successfully initialised.

    Returns Promise<void>

    libolm is deprecated. Prefer initRustCrypto.

  • Experimental

    Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.

    An alternative to initCrypto.

    Parameters

    • args: {
          storageKey?: Uint8Array;
          storagePassword?: string;
          useIndexedDB?: boolean;
      } = {}
      • OptionalstorageKey?: Uint8Array

        A key with which to encrypt the indexeddb store. If provided, it must be exactly 32 bytes of data, and must be the same each time the client is initialised for a given device. If both this and storagePassword are unspecified, the store will be unencrypted.

      • OptionalstoragePassword?: string

        An alternative to storageKey. A password which will be used to derive a key to encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer to pass a storageKey directly where possible.

      • OptionaluseIndexedDB?: boolean

        True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.

    Returns Promise<void>

    a Promise which will resolve when the crypto layer has been successfully initialised.

  • Experimental

    Parameters

    • roomId: string
    • userId: string
    • Optionalreason: string

      Optional.

    Returns Promise<{}>

    Promise which resolves: {} an empty object.

  • Experimental

    Invite a user to a room based on their email address.

    Parameters

    • roomId: string

      The room to invite the user to.

    • email: string

      The email address to invite.

    Returns Promise<{}>

    Promise which resolves: {} an empty object.

  • Experimental

    Invite a user to a room based on a third-party identifier.

    Parameters

    • roomId: string

      The room to invite the user to.

    • medium: string

      The medium to invite the user e.g. "email".

    • address: string

      The address for the specified medium.

    Returns Promise<{}>

    Promise which resolves: {} an empty object.

  • Experimental

    Checks whether cross signing:

    • is enabled on this account and trusted by this device
    • has private keys either cached locally or stored in secret storage

    If this function returns false, bootstrapCrossSigning() can be used to fix things such that it returns true. That is to say, after bootstrapCrossSigning() completes successfully, this function should return true.

    Returns Promise<boolean>

    True if cross-signing is ready to be used on this device

  • Experimental

    Get whether to allow a fallback ICE server should be used for negotiating a WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.

    Returns boolean

  • Experimental

    Return whether the client is configured for a guest account.

    Returns boolean

    True if this is a guest access_token (or no token is supplied).

  • Experimental

    Checks whether secret storage:

    • is enabled on this account
    • is storing cross-signing private keys
    • is storing session backup key (if enabled)

    If this function returns false, bootstrapSecretStorage() can be used to fix things such that it returns true. That is to say, after bootstrapSecretStorage() completes successfully, this function should return true.

    Returns Promise<boolean>

    True if secret storage is ready to be used on this device

  • Experimental

    Determines if the current user is an administrator of the Synapse homeserver. Returns false if untrue or the homeserver does not appear to be a Synapse homeserver. This function is implementation specific and may change as a result.

    Returns Promise<boolean>

    true if the user appears to be a Synapse administrator.

  • Experimental

    Gets whether or not a specific user is being ignored by this client.

    Parameters

    • userId: string

      the user ID to check

    Returns boolean

    true if the user is ignored, false otherwise

  • Experimental

    Check whether a username is available prior to registration. An error response indicates an invalid/unavailable username.

    Parameters

    • username: string

      The username to check the availability of.

    Returns Promise<boolean>

    Promise which resolves: to boolean of whether the username is available.

  • Experimental

    Check if a particular spec version is supported by the server.

    Parameters

    • version: string

      The spec version (such as "r0.5.0") to check for.

    Returns Promise<boolean>

    Whether it is supported

  • Experimental

    Get the raw key for a key backup from the password Used when migrating key backups into SSSS

    The cross-signing API is currently UNSTABLE and may change without notice.

    Parameters

    • password: string

      Passphrase

    • backupInfo: KeyBackupInfo

      Backup metadata from checkKeyBackup

    Returns Promise<Uint8Array>

    key backup key

    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.

  • Experimental

    Parameters

    • roomId: string
    • userId: string
    • Optionalreason: string

      Optional.

    Returns Promise<{}>

    Promise which resolves: {} an empty object.

  • Experimental

    Knock a room. If you have already knocked the room, this will no-op.

    Parameters

    • roomIdOrAlias: string

      The room ID or room alias to knock.

    • opts: KnockRoomOpts = {}

      Options when knocking the room.

    Returns Promise<{
        room_id: string;
    }>

    Promise which resolves: {room_id: {string}}

  • Experimental

    Leaves all rooms in the chain of room upgrades based on the given room. By default, this will leave all the previous and upgraded rooms, including the given room. To only leave the given room and any previous rooms, keeping the upgraded (modern) rooms untouched supply false to includeFuture.

    Parameters

    • roomId: string

      The room ID to start leaving at

    • includeFuture: boolean = true

      If true, the whole chain (past and future) of upgraded rooms will be left.

    Returns Promise<{
        [roomId: string]: Error | MatrixError | null;
    }>

    Promise which resolves when completed with an object keyed by room ID and value of the error encountered when leaving or null.

  • Experimental

    Logs out the current session. Obviously, further calls that require authorisation should fail after this method is called. The state of the MatrixClient object is not affected: it is up to the caller to either reset or destroy the MatrixClient after this method succeeds.

    Parameters

    • stopClient: boolean = false

      whether to stop the client before calling /logout to prevent invalid token errors.

    Returns Promise<{}>

    Promise which resolves: On success, the empty object {}

  • Experimental

    Looks up the public Matrix ID mapping for a given 3rd party identifier from the identity server

    Parameters

    • medium: string

      The medium of the threepid, eg. 'email'

    • address: string

      The textual address of the threepid

    • identityAccessToken: string

      The access_token field of the Identity Server /account/register response (see registerWithIdentityServer).

    Returns Promise<{} | {
        address: string;
        medium: string;
        mxid: string;
    }>

    Promise which resolves: A threepid mapping object or the empty object if no mapping exists

  • Experimental

    Parameters

    • roomId: string
    • OptionalincludeMembership: string

      the membership type to include in the response

    • OptionalexcludeMembership: string

      the membership type to exclude from the response

    • OptionalatEventId: string

      the id of the event for which moment in the timeline the members should be returned for

    Returns Promise<{
        [userId: string]: IStateEventWithRoomId[];
    }>

    Promise which resolves: dictionary of userid to profile information

  • Experimental

    Turn an MXC URL into an HTTP one. This method is experimental and may change.

    Parameters

    • mxcUrl: string

      The MXC URL

    • Optionalwidth: number

      The desired width of the thumbnail.

    • Optionalheight: number

      The desired height of the thumbnail.

    • OptionalresizeMethod: string

      The thumbnail resize method to use, either "crop" or "scale".

    • OptionalallowDirectLinks: boolean

      If true, return any non-mxc URLs directly. Fetching such URLs will leak information about the user to anyone they share a room with. If false, will return null for such URLs.

    • OptionalallowRedirects: boolean

      If true, the caller supports the URL being 307 or 308 redirected to another resource upon request. If false, redirects are not expected. Implied true when useAuthentication is true.

    • OptionaluseAuthentication: boolean

      If true, the caller supports authenticated media and wants an authentication-required URL. Note that server support for authenticated media will not be checked - it is the caller's responsibility to do so before calling this function. Note also that useAuthentication implies allowRedirects. Defaults to false (unauthenticated endpoints).

    Returns null | string

    the avatar URL or null.

  • Experimental

    Adds the listener function to the end of the listeners array for the event named event.

    No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added, and called, multiple times.

    By default, event listeners are invoked in the order they are added. The prependListener method can be used as an alternative to add the event listener to the beginning of the listeners array.

    Type Parameters

    Parameters

    Returns this

    a reference to the EventEmitter, so that calls can be chained.

  • Experimental

    Adds a one-time listener function for the event named event. The next time event is triggered, this listener is removed and then invoked.

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. The prependOnceListener method can be used as an alternative to add the event listener to the beginning of the listeners array.

    Type Parameters

    Parameters

    Returns this

    a reference to the EventEmitter, so that calls can be chained.

  • Experimental

    Peek into a room and receive updates about the room. This only works if the history visibility for the room is world_readable.

    Parameters

    • roomId: string

      The room to attempt to peek into.

    • limit: number = 20

      The number of timeline events to initially retrieve.

    Returns Promise<Room>

    Promise which resolves: Room object

  • Experimental

    Perform any background tasks that can be done before a message is ready to send, in order to speed up sending of the message.

    Parameters

    • room: Room

      the room the event is in

    Returns void

    Prefer CryptoApi.prepareToEncrypt:

    client.getCrypto().prepareToEncrypt(room);
    
  • Experimental

    Processes a list of threaded events and adds them to their respective timelines

    Parameters

    • room: Room

      the room the adds the threaded events

    • threadedEvents: MatrixEvent[]

      an array of the threaded events

    • toStartOfTimeline: boolean

      the direction in which we want to add the events

    Returns void

  • Experimental

    Processes a list of thread roots and creates a thread model

    Parameters

    • room: Room

      the room to create the threads in

    • threadedEvents: MatrixEvent[]

      an array of thread roots

    • toStartOfTimeline: boolean

      the direction

    Returns void

  • Experimental

    Sends events directly to specific devices using Matrix's to-device messaging system. The batch will be split up into appropriately sized batches for sending and stored in the store so they can be retried later if they fail to send. Retries will happen automatically.

    Parameters

    Returns Promise<void>

  • Experimental

    Refreshes an access token using a provided refresh token. The refresh token must be valid for the current access token known to the client instance.

    Note that this function will not cause a logout if the token is deemed unknown by the server - the caller is responsible for managing logout actions on error.

    Parameters

    • refreshToken: string

      The refresh token.

    Returns Promise<IRefreshTokenResponse>

    Promise which resolves to the new token.

  • Experimental

    Parameters

    • username: string
    • password: string
    • sessionId: null | string
    • auth: {
          session?: string;
          type: string;
      }
      • Optionalsession?: string
      • type: string
    • OptionalbindThreepids: {
          email?: boolean;
          msisdn?: boolean;
      }

      Set key 'email' to true to bind any email threepid uses during registration in the identity server. Set 'msisdn' to true to bind msisdn.

      • Optionalemail?: boolean
      • Optionalmsisdn?: boolean
    • OptionalguestAccessToken: string
    • OptionalinhibitLogin: boolean

    Returns Promise<RegisterResponse>

    Promise which resolves to a RegisterResponse object

  • Experimental

    Register a guest account. This method returns the auth info needed to create a new authenticated client, Remember to call setGuest(true) on the (guest-)authenticated client, e.g:

    const tmpClient = await sdk.createClient(MATRIX_INSTANCE);
    const { user_id, device_id, access_token } = tmpClient.registerGuest();
    const client = createClient({
    baseUrl: MATRIX_INSTANCE,
    accessToken: access_token,
    userId: user_id,
    deviceId: device_id,
    })
    client.setGuest(true);

    Parameters

    Returns Promise<RegisterResponse>

    Promise which resolves: JSON object that contains: { user_id, device_id, access_token, home_server }

  • Experimental

    Register with an identity server using the OpenID token from the user's Homeserver, which can be retrieved via MatrixClient#getOpenIdToken.

    Note that the /account/register endpoint (as well as IS authentication in general) was added as part of the v2 API version.

    Parameters

    Returns Promise<{
        access_token: string;
        token: string;
    }>

    Promise which resolves: with object containing an Identity Server access token.

  • Experimental

    Try to rehydrate a device if available. The client must have been initialized with a cryptoCallback.getDehydrationKey option, and this function must be called before initCrypto and startClient are called.

    Returns Promise<undefined | string>

    Promise which resolves to undefined if a device could not be dehydrated, or to the new device ID if the dehydration was successful.

    MSC2697 device dehydration is not supported for rust cryptography.

  • Experimental

    Returns relations for a given event. Handles encryption transparently, with the caveat that the amount of events returned might be 0, even though you get a nextBatch. When the returned promise resolves, all messages should have finished trying to decrypt.

    Parameters

    • roomId: string

      the room of the event

    • eventId: string

      the id of the event

    • relationType: null | string

      the rel_type of the relations requested

    • OptionaleventType: null | string

      the event type of the relations requested

    • opts: IRelationsRequestOpts = ...

      options with optional values for the request.

    Returns Promise<{
        events: MatrixEvent[];
        nextBatch?: null | string;
        originalEvent?: null | MatrixEvent;
        prevBatch?: null | string;
    }>

    an object with events as MatrixEvent[] and optionally nextBatch if more relations are available.

  • Experimental

    Removes all listeners, or those of the specified event.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Parameters

    Returns this

    a reference to the EventEmitter, so that calls can be chained.

  • Experimental

    Removes an existing pusher

    Parameters

    • pushKey: string

      pushkey of pusher to remove

    • appId: string

      app_id of pusher to remove

    Returns Promise<{}>

    Promise which resolves: Empty json object on success

  • Experimental

    Reports an event as inappropriate to the server, which may then notify the appropriate people.

    Parameters

    • roomId: string

      The room in which the event being reported is located.

    • eventId: string

      The event to report.

    • score: number

      The score to rate this content as where -100 is most offensive and 0 is inoffensive.

    • reason: string

      The reason the content is being reported. May be blank.

    Returns Promise<{}>

    Promise which resolves to an empty object if successful

  • Experimental

    Requests an email verification token for the purposes of adding a third party identifier to an account. This API requests a token from the homeserver. The doesServerRequireIdServerParam() method can be used to determine if the server requires the id_server parameter to be provided. If an account with the given email address already exists and is associated with an account other than the one the user is authed as, it will either send an email to the address informing them of this or return M_THREEPID_IN_USE (which one is up to the homeserver).

    Parameters

    • email: string

      As requestEmailToken

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • OptionalnextLink: string

      As requestEmailToken

    Returns Promise<IRequestTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Requests a text message verification token for the purposes of adding a third party identifier to an account. This API proxies the identity server /validate/email/requestToken API, adding specific behaviour for the addition of phone numbers to an account, as requestAdd3pidEmailToken.

    Parameters

    • phoneCountry: string

      As requestRegisterMsisdnToken

    • phoneNumber: string

      As requestRegisterMsisdnToken

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • OptionalnextLink: string

      As requestEmailToken

    Returns Promise<IRequestMsisdnTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Requests an email verification token directly from an identity server.

    This API is used as part of binding an email for discovery on an identity server. The validation data that results should be passed to the bindThreePid method to complete the binding process.

    Parameters

    • email: string

      The email address to request a token for

    • clientSecret: string

      A secret binary string generated by the client. It is recommended this be around 16 ASCII characters.

    • sendAttempt: number

      If an identity server sees a duplicate request with the same sendAttempt, it will not send another email. To request another email to be sent, use a larger value for the sendAttempt param as was used in the previous request.

    • OptionalnextLink: string

      Optional If specified, the client will be redirected to this link after validation.

    • OptionalidentityAccessToken: string

      The access_token field of the identity server /account/register response (see registerWithIdentityServer).

    Returns Promise<IRequestTokenResponse>

    Promise which resolves: TODO

    Error if no identity server is set

  • Experimental

    Requests a MSISDN verification token directly from an identity server.

    This API is used as part of binding a MSISDN for discovery on an identity server. The validation data that results should be passed to the bindThreePid method to complete the binding process.

    Parameters

    • phoneCountry: string

      The ISO 3166-1 alpha-2 code for the country in which phoneNumber should be parsed relative to.

    • phoneNumber: string

      The phone number, in national or international format

    • clientSecret: string

      A secret binary string generated by the client. It is recommended this be around 16 ASCII characters.

    • sendAttempt: number

      If an identity server sees a duplicate request with the same sendAttempt, it will not send another SMS. To request another SMS to be sent, use a larger value for the sendAttempt param as was used in the previous request.

    • OptionalnextLink: string

      Optional If specified, the client will be redirected to this link after validation.

    • OptionalidentityAccessToken: string

      The access_token field of the Identity Server /account/register response (see registerWithIdentityServer).

    Returns Promise<IRequestMsisdnTokenResponse>

    Promise which resolves to an object with a sid string

    Error if no identity server is set

  • Experimental

    Requests an email verification token for the purposes of resetting the password on an account. This API proxies the identity server /validate/email/requestToken API, adding specific behaviour for the password resetting. Specifically, if no account with the given email address exists, it may either return M_THREEPID_NOT_FOUND or send an email to the address informing them of this (which one is up to the homeserver).

    requestEmailToken calls the equivalent API directly on the identity server, therefore bypassing the password reset specific logic.

    Parameters

    • email: string

      As requestEmailToken

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • OptionalnextLink: string

      As requestEmailToken

    Returns Promise<IRequestTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Requests a text message verification token for the purposes of resetting the password on an account. This API proxies the identity server /validate/email/requestToken API, adding specific behaviour for the password resetting, as requestPasswordEmailToken.

    Parameters

    • phoneCountry: string

      As requestRegisterMsisdnToken

    • phoneNumber: string

      As requestRegisterMsisdnToken

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • nextLink: string

      As requestEmailToken

    Returns Promise<IRequestMsisdnTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Requests an email verification token for the purposes of registration. This API requests a token from the homeserver. The doesServerRequireIdServerParam() method can be used to determine if the server requires the id_server parameter to be provided.

    Parameters and return value are as for requestEmailToken

    Parameters

    • email: string

      As requestEmailToken

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • OptionalnextLink: string

      As requestEmailToken

    Returns Promise<IRequestTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Requests a text message verification token for the purposes of registration. This API requests a token from the homeserver. The doesServerRequireIdServerParam() method can be used to determine if the server requires the id_server parameter to be provided.

    Parameters

    • phoneCountry: string

      The ISO 3166-1 alpha-2 code for the country in which phoneNumber should be parsed relative to.

    • phoneNumber: string

      The phone number, in national or international format

    • clientSecret: string

      As requestEmailToken

    • sendAttempt: number

      As requestEmailToken

    • OptionalnextLink: string

      As requestEmailToken

    Returns Promise<IRequestMsisdnTokenResponse>

    Promise which resolves: As requestEmailToken

  • Experimental

    Request a secret from another device.

    The Secure Secret Storage API is currently UNSTABLE and may change without notice.

    Parameters

    • name: string

      the name of the secret to request

    • devices: string[]

      the devices to request the secret from

    Returns ISecretRequest

    the secret request object

    Not supported for Rust Cryptography.

  • Experimental

    Retry a backed off syncing request immediately. This should only be used when the user explicitly attempts to retry their lost connection. Will also retry any outbound to-device messages currently in the queue to be sent (retries of regular outgoing events are handled separately, per-event).

    Returns boolean

    True if this resulted in a request being retried.

  • Experimental

    Retrieve older messages from the given room and put them in the timeline.

    If this is called multiple times whilst a request is ongoing, the same Promise will be returned. If there was a problem requesting scrollback, there will be a small delay before another request can be made (to prevent tight-looping when there is no connection).

    Parameters

    • room: Room

      The room to get older messages in.

    • limit: number = 30

      Optional. The maximum number of previous events to pull in. Default: 30.

    Returns Promise<Room>

    Promise which resolves: Room. If you are at the beginning of the timeline, Room.oldState.paginationToken will be null.

  • Experimental

    Perform a server-side search for room events.

    The returned promise resolves to an object containing the fields:

    • count: estimate of the number of results
    • next_batch: token for back-pagination; if undefined, there are no more results
    • highlights: a list of words to highlight from the stemming algorithm
    • results: a list of results

    Each entry in the results list is a SearchResult.

    Parameters

    Returns Promise<ISearchResults>

    Promise which resolves: result object

  • Experimental

    Query the user directory with a term matching user IDs, display names and domains.

    Parameters

    • options: {
          limit?: number;
          term: string;
      }
      • Optionallimit?: number

        the maximum number of results to return. The server will apply a limit if unspecified.

      • term: string

        the term with which to search.

    Returns Promise<IUserDirectoryResponse>

    Promise which resolves: an array of results.

  • Experimental

    Back up session keys to the homeserver.

    Parameters

    • roomId: undefined

      ID of the room that the keys are for Optional.

    • sessionId: undefined

      ID of the session that the keys are for Optional.

    • version: undefined | string

      backup version Optional.

    • data: IKeyBackup

      Object keys to send

    Returns Promise<void>

    a promise that will resolve when the keys are uploaded

    Not supported for Rust Cryptography.

  • Experimental

    Parameters

    • roomId: string
    • sessionId: undefined
    • version: undefined | string
    • data: IKeyBackup

    Returns Promise<void>

  • Experimental

    Parameters

    • roomId: string
    • sessionId: string
    • version: undefined | string
    • data: IKeyBackup

    Returns Promise<void>

  • Experimental

    Send a read receipt.

    Parameters

    • event: null | MatrixEvent

      The event that has been read.

    • receiptType: ReceiptType = ReceiptType.Read

      other than ReceiptType.Read are experimental! Optional.

    • unthreaded: boolean = false

    Returns Promise<undefined | {}>

    Promise which resolves: to an empty object {}

  • Experimental

    Send a receipt.

    Parameters

    • event: MatrixEvent

      The event being acknowledged

    • receiptType: ReceiptType

      The kind of receipt e.g. "m.read". Other than ReceiptType.Read are experimental!

    • Optionalbody: Record<string, any>

      Additional content to send alongside the receipt.

    • unthreaded: boolean = false

      An unthreaded receipt will clear room+thread notifications

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Send an event to a specific list of devices. This is a low-level API that simply wraps the HTTP API call to send to-device messages. We recommend using queueToDevice() which is a higher level API.

    Parameters

    • eventType: string

      type of event to send content to send. Map from user_id to device_id to content object.

    • contentMap: SendToDeviceContentMap

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Set account data event for the current user. It will retry the request up to 5 times.

    Parameters

    • eventType: string

      The event type

    • content: IContent

      the contents object for the event

    Returns Promise<{}>

    Promise which resolves: an empty object

  • Experimental

    Set a function which is called when /sync returns a 'limited' response. It is called with a room ID and returns a boolean. It should return 'true' if the SDK can SAFELY remove events from this room. It may not be safe to remove events if there are other references to the timelines for this room, e.g because the client is actively viewing events in this room. Default: returns false.

    Parameters

    Returns void

  • Experimental

    Set the dehydration key. This will also periodically dehydrate devices to the server.

    Parameters

    • key: Uint8Array

      the dehydration key

    • keyInfo: IDehydratedDeviceKeyInfo

      Information about the key. Primarily for information about how to generate the key from a passphrase.

    • OptionaldeviceDisplayName: string

      The device display name for the dehydrated device.

    Returns Promise<void>

    A promise that resolves when the dehydrated device is stored.

    Not supported for Rust Cryptography.

  • Experimental

    Mark the given device as blocked/unblocked

    Parameters

    • userId: string

      owner of the device

    • deviceId: string

      unique identifier for the device or user's cross-signing public key ID.

    • blocked: boolean = true

      whether to mark the device as blocked. defaults to 'true'.

    Returns Promise<void>

    Not supported for Rust Cryptography.

  • Experimental

    Update the given device

    Parameters

    • deviceId: string

      device to update

    • body: {
          display_name: string;
      }

      body of request

      • display_name: string

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Mark the given device as known/unknown

    Parameters

    • userId: string

      owner of the device

    • deviceId: string

      unique identifier for the device or user's cross-signing public key ID.

    • known: boolean = true

      whether to mark the device as known. defaults to 'true'.

    Returns Promise<void>

    Not supported for Rust Cryptography.

  • Experimental

    Set whether to allow a fallback ICE server should be used for negotiating a WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.

    Parameters

    • allow: boolean

    Returns void

  • Experimental

    Set whether VoIP calls are forced to use only TURN candidates. This is the same as the forceTURN option when creating the client.

    Parameters

    • force: boolean

      True to force use of TURN servers

    Returns void

  • Experimental

    Set the global override for whether the client should ever send encrypted messages to unverified devices. This provides the default for rooms which do not specify a value.

    Parameters

    • value: boolean

      whether to blacklist all unverified devices by default

    Returns boolean

    Prefer direct access to CryptoApi.globalBlacklistUnverifiedDevices:

    client.getCrypto().globalBlacklistUnverifiedDevices = value;
    
  • Experimental

    Set whether sendMessage in a room with unknown and unverified devices should throw an error and not send them message. This has 'Global' for symmetry with setGlobalBlacklistUnverifiedDevices but there is currently no room-level equivalent for this setting.

    This API is currently UNSTABLE and may change or be removed without notice.

    It has no effect with the Rust crypto implementation.

    Parameters

    • value: boolean

      whether error on unknown devices

      client.getCrypto().globalErrorOnUnknownDevices = value;
      

    Returns void

  • Experimental

    Set whether this client is a guest account. This method is experimental and may change without warning.

    Parameters

    • guest: boolean

      True if this is a guest account. if the token is a macaroon, it should be encoded in it that it is a 'guest' access token, which means that the SDK can determine this entirely without the dev manually flipping this flag.

    Returns void

  • Experimental

    Make a request to change your password.

    Parameters

    • authDict: AuthDict
    • newPassword: string

      The new desired password.

    • OptionallogoutDevices: boolean

      Should all sessions be logged out after the password change. Defaults to true.

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Set a power level to one or multiple users. Will apply changes atop of current power level event from local state if running & synced, falling back to fetching latest from the /state/ API.

    Parameters

    • roomId: string

      the room to update power levels in

    • userId: string | string[]

      the ID of the user or users to update power levels of

    • powerLevel: undefined | number

      the numeric power level to update given users to

    Returns Promise<ISendEventResponse>

    Promise which resolves: to an ISendEventResponse object

  • Experimental

    Set the visibility of a room in the current HS's room directory

    Parameters

    • roomId: string
    • visibility: Visibility

      "public" to make the room visible in the public directory, or "private" to make it invisible.

    Returns Promise<{}>

    Promise which resolves: to an empty object {}

  • Experimental

    Enable end-to-end encryption for a room. This does not modify room state. Any messages sent before the returned promise resolves will be sent unencrypted.

    Parameters

    • roomId: string

      The room ID to enable encryption in.

    • config: IRoomEncryption

      The encryption config for the room.

    Returns Promise<void>

    A promise that will resolve when encryption is set up.

    Not supported for Rust Cryptography. To enable encryption in a room, send an m.room.encryption state event.

  • Experimental

    Set a room-kind muting push rule in a room. The operation also updates MatrixClient.pushRules at the end.

    Parameters

    • scope: "global" | "device"

      "global" or device-specific.

    • roomId: string

      the id of the room.

    • mute: boolean

      the mute state.

    Returns undefined | Promise<void>

    Promise which resolves: result object

  • Experimental

    Set a marker to indicate the point in a room before which the user has read every event. This can be retrieved from room account data (the event type is m.fully_read) and displayed as a horizontal line in the timeline that is visually distinct to the position of the user's own read receipt.

    Parameters

    • roomId: string

      ID of the room that has been read

    • rmEventId: string

      ID of the event that has been read

    • OptionalrrEvent: MatrixEvent

      the event tracked by the read receipt. This is here for convenience because the RR and the RM are commonly updated at the same time as each other. The local echo of this receipt will be done if set. Optional.

    • OptionalrpEvent: MatrixEvent

      the m.read.private read receipt event for when we don't want other users to see the read receipts. This is experimental. Optional.

    Returns Promise<{}>

    Promise which resolves: the empty object, {}.

  • Experimental

    Set a marker to indicate the point in a room before which the user has read every event. This can be retrieved from room account data (the event type is m.fully_read) and displayed as a horizontal line in the timeline that is visually distinct to the position of the user's own read receipt.

    Parameters

    • roomId: string

      ID of the room that has been read

    • rmEventId: string

      ID of the event that has been read

    • OptionalrrEventId: string

      ID of the event tracked by the read receipt. This is here for convenience because the RR and the RM are commonly updated at the same time as each other. Optional.

    • OptionalrpEventId: string

      rpEvent the m.read.private read receipt event for when we don't want other users to see the read receipts. This is experimental. Optional.

    Returns Promise<{}>

    Promise which resolves: the empty object, {}.

  • Experimental

    Set whether to advertise transfer support to other parties on Matrix calls.

    Parameters

    • support: boolean

      True to advertise the 'm.call.transferee' capability

    Returns void

  • Experimental

    Specify the set_presence value to be used for subsequent calls to the Sync API. This has an advantage over calls to the PUT /presence API in that it doesn't clobber status_msg set by other devices.

    Parameters

    • Optionalpresence: SetPresence

      the presence to specify to set_presence of sync calls

    Returns Promise<void>

  • Experimental

    Submits a MSISDN token to the identity server

    This is used when submitting the code sent by SMS to a phone number. The identity server has an equivalent API for email but the js-sdk does not expose this, since email is normally validated by the user clicking a link rather than entering a code.

    Parameters

    • sid: string

      The sid given in the response to requestToken

    • clientSecret: string

      A secret binary string generated by the client. This must be the same value submitted in the requestToken call.

    • msisdnToken: string

      The MSISDN token, as enetered by the user.

    • identityAccessToken: null | string

      The access_token field of the Identity Server /account/register response (see registerWithIdentityServer). Some legacy identity servers had no authentication here.

    Returns Promise<{
        success: boolean;
    }>

    Promise which resolves: Object, containing success boolean.

    Error if No identity server is set

  • Experimental

    Submits a MSISDN token to an arbitrary URL.

    This is used when submitting the code sent by SMS to a phone number in the newer 3PID flow where the homeserver validates 3PID ownership (as part of requestAdd3pidMsisdnToken). The homeserver response may include a submit_url to specify where the token should be sent, and this helper can be used to pass the token to this URL.

    Parameters

    • url: string

      The URL to submit the token to

    • sid: string

      The sid given in the response to requestToken

    • clientSecret: string

      A secret binary string generated by the client. This must be the same value submitted in the requestToken call.

    • msisdnToken: string

      The MSISDN token, as enetered by the user.

    Returns Promise<{
        success: boolean;
    }>

    Promise which resolves: Object, containing success boolean.

  • Experimental

    Unbind a 3PID for discovery on an identity server via the homeserver. The homeserver removes its record of the binding to keep an updated record of where all 3PIDs for the account are bound.

    Parameters

    • medium: string

      The threepid medium (eg. 'email')

    • address: string

      The threepid address (eg. 'bob@example.com') this must be as returned by getThreePids.

    Returns Promise<{
        id_server_unbind_result: IdServerUnbindResult;
    }>

    Promise which resolves: on success

  • Experimental

    Creates a new file tree space with the given name. The client will pick defaults for how it expects to be able to support the remaining API offered by the returned class.

    Note that this is UNSTABLE and may have breaking changes without notice.

    Parameters

    • name: string

      The name of the tree space.

    Returns Promise<MSC3089TreeSpace>

    Promise which resolves to the created space.

  • Experimental

    Gets a reference to a tree space, if the room ID given is a tree space. If the room does not appear to be a tree space then null is returned.

    Note that this is UNSTABLE and may have breaking changes without notice.

    Parameters

    • roomId: string

      The room ID to get a tree space reference for.

    Returns null | MSC3089TreeSpace

    The tree space, or null if not a tree space.

  • Experimental

    Upgrades a room to a new protocol version

    Parameters

    • roomId: string
    • newVersion: string

      The target version to upgrade to

    Returns Promise<{
        replacement_room: string;
    }>

    Promise which resolves: Object with key 'replacement_room'

  • Experimental

    Upload a file to the media repository on the homeserver.

    Parameters

    • file: XMLHttpRequestBodyInit

      The object to upload. On a browser, something that can be sent to XMLHttpRequest.send (typically a File). Under node.js, a a Buffer, String or ReadStream.

    • Optionalopts: UploadOpts

      options object

    Returns Promise<UploadResponse>

    Promise which resolves to response object, as determined by this.opts.onlyData, opts.rawResponse, and opts.onlyContentUri. Rejects with an error (usually a MatrixError).

  • Experimental

    Wait until an initial state for the given room has been processed by the client and the client is aware of any ongoing group calls. Awaiting on the promise returned by this method before calling getGroupCallForRoom() avoids races where getGroupCallForRoom is called before the state for that room has been processed. It does not, however, fix other races, eg. two clients both creating a group call at the same time.

    Parameters

    • roomId: string

      The room ID to wait for

    Returns Promise<void>

    A promise that resolves once existing group calls in the room have been processed.