UNPKG

matrix-js-sdk

Version:
1,279 lines (1,278 loc) 165 kB
/** * This is an internal module. See {@link MatrixClient} for the public class. */ import { Optional } from "matrix-events-sdk"; import type { IDeviceKeys, IMegolmSessionData, IOneTimeKey } from "./@types/crypto"; import { ISyncStateData, SyncApi, SyncApiOptions, SyncState } from "./sync"; import { EventStatus, IContent, IDecryptOptions, IEvent, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from "./models/event"; import { CallEvent, CallEventHandlerMap, MatrixCall } from "./webrtc/call"; import { Filter, IFilterDefinition } from "./filter"; import { CallEventHandlerEvent, CallEventHandler, CallEventHandlerEventHandlerMap } from "./webrtc/callEventHandler"; import { GroupCallEventHandlerEvent, GroupCallEventHandlerEventHandlerMap } from "./webrtc/groupCallEventHandler"; import { Direction, EventTimeline } from "./models/event-timeline"; import { IActionsObject, PushProcessor } from "./pushprocessor"; import { AutoDiscoveryAction } from "./autodiscovery"; import { IExportedDevice as IExportedOlmDevice } from "./crypto/OlmDevice"; import { IOlmDevice } from "./crypto/algorithms/megolm"; import { TypedReEmitter } from "./ReEmitter"; import { IRoomEncryption, RoomList } from "./crypto/RoomList"; import { SERVICE_TYPES } from "./service-types"; import { HttpApiEvent, HttpApiEventHandlerMap, Upload, UploadOpts, MatrixError, MatrixHttpApi, IHttpOpts, FileType, UploadResponse, IRequestOpts } from "./http-api"; import { Crypto, CryptoEvent, CryptoEventHandlerMap, ICryptoCallbacks, IBootstrapCrossSigningOpts, ICheckOwnCrossSigningTrustOpts, VerificationMethod } from "./crypto"; import { DeviceInfo, IDevice } from "./crypto/deviceinfo"; import { User, UserEvent, UserEventHandlerMap } from "./models/user"; import { IDehydratedDevice, IDehydratedDeviceKeyInfo } from "./crypto/dehydration"; import { IKeyBackupInfo, IKeyBackupPrepareOpts, IKeyBackupRestoreOpts, IKeyBackupRestoreResult } from "./crypto/keybackup"; import { IIdentityServerProvider } from "./@types/IIdentityServerProvider"; import { MatrixScheduler } from "./scheduler"; import { BeaconEvent, BeaconEventHandlerMap } from "./models/beacon"; import { IAuthData, IAuthDict } from "./interactive-auth"; import { IMinimalEvent, IRoomEvent, IStateEvent } from "./sync-accumulator"; import { CrossSigningKey, IAddSecretStorageKeyOpts, ICreateSecretStorageOpts, IEncryptedEventInfo, IImportRoomKeysOpts, IRecoveryKey, ISecretStorageKeyInfo } from "./crypto/api"; import { EventTimelineSet } from "./models/event-timeline-set"; import { VerificationRequest } from "./crypto/verification/request/VerificationRequest"; import { VerificationBase as Verification } from "./crypto/verification/Base"; import { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from "./crypto/CrossSigning"; import { Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from "./models/room"; import { RoomMemberEvent, RoomMemberEventHandlerMap } from "./models/room-member"; import { RoomStateEvent, RoomStateEventHandlerMap } from "./models/room-state"; import { IAddThreePidOnlyBody, IBindThreePidBody, ICreateRoomOpts, IEventSearchOpts, IGuestAccessOpts, IJoinRoomOpts, IPaginateOpts, IPresenceOpts, IRedactOpts, IRelationsRequestOpts, IRelationsResponse, IRoomDirectoryOptions, ISearchOpts, ISendEventResponse, ITagsResponse, IStatusResponse } from "./@types/requests"; import { EventType, RelationType, RoomType } from "./@types/event"; import { IdServerUnbindResult, IImageInfo, Preset, Visibility } from "./@types/partials"; import { EventMapper, MapperOpts } from "./event-mapper"; import { IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from "./crypto/backup"; import { MSC3089TreeSpace } from "./models/MSC3089TreeSpace"; import { ISignatures } from "./@types/signed"; import { IStore } from "./store"; import { ISecretRequest } from "./crypto/SecretStorage"; import { IEventWithRoomId, ISearchRequestBody, ISearchResponse, ISearchResults, IStateEventWithRoomId } from "./@types/search"; import { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from "./@types/synapse"; import { IHierarchyRoom } from "./@types/spaces"; import { IPusher, IPusherRequest, IPushRule, IPushRules, PushRuleAction, PushRuleKind, RuleId } from "./@types/PushRules"; import { IThreepid } from "./@types/threepids"; import { CryptoStore, OutgoingRoomKeyRequest } from "./crypto/store/base"; import { GroupCall, IGroupCallDataChannelOptions, GroupCallIntent, GroupCallType } from "./webrtc/groupCall"; import { MediaHandler } from "./webrtc/mediaHandler"; import { GroupCallEventHandler } from "./webrtc/groupCallEventHandler"; import { LoginTokenPostResponse, ILoginFlowsResponse, IRefreshTokenResponse, SSOAction } from "./@types/auth"; import { TypedEventEmitter } from "./models/typed-event-emitter"; import { ReceiptType } from "./@types/read_receipts"; import { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from "./sliding-sync"; import { SlidingSyncSdk } from "./sliding-sync-sdk"; import { FeatureSupport, ThreadFilterType } from "./models/thread"; import { MBeaconInfoEventContent } from "./@types/beacon"; import { UnstableValue } from "./NamespacedValue"; import { ToDeviceBatch } from "./models/ToDeviceMessage"; import { IgnoredInvites } from "./models/invites-ignorer"; import { UIAResponse } from "./@types/uia"; import { LocalNotificationSettings } from "./@types/local_notifications"; import { Feature, ServerSupport } from "./feature"; export type Store = IStore; export type ResetTimelineCallback = (roomId: string) => boolean; export declare const CRYPTO_ENABLED: boolean; export declare const UNSTABLE_MSC3852_LAST_SEEN_UA: UnstableValue<"last_seen_user_agent", "org.matrix.msc3852.last_seen_user_agent">; interface IExportedDevice { olmDevice: IExportedOlmDevice; userId: string; deviceId: string; } export interface IKeysUploadResponse { one_time_key_counts: { [algorithm: string]: number; }; } export interface ICreateClientOpts { baseUrl: string; idBaseUrl?: string; /** * The data store used for sync data from the homeserver. If not specified, * this client will not store any HTTP responses. The `createClient` helper * will create a default store if needed. */ store?: Store; /** * A store to be used for end-to-end crypto session data. If not specified, * end-to-end crypto will be disabled. The `createClient` helper will create * a default store if needed. Calls the factory supplied to * {@link setCryptoStoreFactory} if unspecified; or if no factory has been * specified, uses a default implementation (indexeddb in the browser, * in-memory otherwise). */ cryptoStore?: CryptoStore; /** * The scheduler to use. If not * specified, this client will not retry requests on failure. This client * will supply its own processing function to * {@link MatrixScheduler#setProcessFunction}. */ scheduler?: MatrixScheduler; /** * The function to invoke for HTTP requests. * Most supported environments have a global `fetch` registered to which this will fall back. */ fetchFn?: typeof global.fetch; userId?: string; /** * A unique identifier for this device; used for tracking things like crypto * keys and access tokens. If not specified, end-to-end encryption will be * disabled. */ deviceId?: string; accessToken?: string; /** * Identity server provider to retrieve the user's access token when accessing * the identity server. See also https://github.com/vector-im/element-web/issues/10615 * which seeks to replace the previous approach of manual access tokens params * with this callback throughout the SDK. */ identityServer?: IIdentityServerProvider; /** * The default maximum amount of * time to wait before timing out HTTP requests. If not specified, there is no timeout. */ localTimeoutMs?: number; /** * Set to true to use * Authorization header instead of query param to send the access token to the server. * * Default false. */ useAuthorizationHeader?: boolean; /** * Set to true to enable * improved timeline support, see {@link MatrixClient#getEventTimeline}. * It is disabled by default for compatibility with older clients - in particular to * maintain support for back-paginating the live timeline after a '/sync' * result with a gap. */ timelineSupport?: boolean; /** * Extra query parameters to append * to all requests with this client. Useful for application services which require * `?user_id=`. */ queryParams?: Record<string, string>; /** * Device data exported with * "exportDevice" method that must be imported to recreate this device. * Should only be useful for devices with end-to-end crypto enabled. * If provided, deviceId and userId should **NOT** be provided at the top * level (they are present in the exported data). */ deviceToImport?: IExportedDevice; /** * Key used to pickle olm objects or other sensitive data. */ pickleKey?: string; verificationMethods?: Array<VerificationMethod>; /** * Whether relaying calls through a TURN server should be forced. Default false. */ forceTURN?: boolean; /** * Up to this many ICE candidates will be gathered when an incoming call arrives. * Gathering does not send data to the caller, but will communicate with the configured TURN * server. Default 0. */ iceCandidatePoolSize?: number; /** * True to advertise support for call transfers to other parties on Matrix calls. Default false. */ supportsCallTransfer?: boolean; /** * 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. */ fallbackICEServerAllowed?: boolean; /** * If true, to-device signalling for group calls will be encrypted * with Olm. Default: true. */ useE2eForGroupCall?: boolean; cryptoCallbacks?: ICryptoCallbacks; /** * Method to generate room names for empty rooms and rooms names based on membership. * Defaults to a built-in English handler with basic pluralisation. */ roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null; } export interface IMatrixClientCreateOpts extends ICreateClientOpts { /** * Whether to allow sending messages to encrypted rooms when encryption * is not available internally within this SDK. This is useful if you are using an external * E2E proxy, for example. Defaults to false. */ usingExternalCrypto?: boolean; } export declare enum PendingEventOrdering { Chronological = "chronological", Detached = "detached" } export interface IStartClientOpts { /** * The event `limit=` to apply to initial sync. Default: 8. */ initialSyncLimit?: number; /** * True to put `archived=true</code> on the <code>/initialSync` request. Default: false. */ includeArchivedRooms?: boolean; /** * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false. */ resolveInvitesToProfiles?: boolean; /** * Controls where pending messages appear in a room's timeline. If "<b>chronological</b>", messages will * appear in the timeline when the call to `sendEvent` was made. If "<b>detached</b>", * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}. * Default: "chronological". */ pendingEventOrdering?: PendingEventOrdering; /** * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds). */ pollTimeout?: number; /** * The filter to apply to /sync calls. */ filter?: Filter; /** * True to perform syncing without automatically updating presence. */ disablePresence?: boolean; /** * True to not load all membership events during initial sync but fetch them when needed by calling * `loadOutOfBandMembers` This will override the filter option at this moment. */ lazyLoadMembers?: boolean; /** * The number of seconds between polls to /.well-known/matrix/client, undefined to disable. * This should be in the order of hours. Default: undefined. */ clientWellKnownPollPeriod?: number; /** * @deprecated use `threadSupport` instead */ experimentalThreadSupport?: boolean; /** * Will organises events in threaded conversations when * a thread relation is encountered */ threadSupport?: boolean; /** * @experimental */ slidingSync?: SlidingSync; } export interface IStoredClientOpts extends IStartClientOpts { } export declare enum RoomVersionStability { Stable = "stable", Unstable = "unstable" } export interface IRoomVersionsCapability { default: string; available: Record<string, RoomVersionStability>; } export interface ICapability { enabled: boolean; } export interface IChangePasswordCapability extends ICapability { } export interface IThreadsCapability extends ICapability { } interface ICapabilities { [key: string]: any; "m.change_password"?: IChangePasswordCapability; "m.room_versions"?: IRoomVersionsCapability; "io.element.thread"?: IThreadsCapability; } export interface ICrossSigningKey { keys: { [algorithm: string]: string; }; signatures?: ISignatures; usage: string[]; user_id: string; } declare enum CrossSigningKeyType { MasterKey = "master_key", SelfSigningKey = "self_signing_key", UserSigningKey = "user_signing_key" } export type CrossSigningKeys = Record<CrossSigningKeyType, ICrossSigningKey>; export interface ISignedKey { keys: Record<string, string>; signatures: ISignatures; user_id: string; algorithms: string[]; device_id: string; } export type KeySignatures = Record<string, Record<string, ICrossSigningKey | ISignedKey>>; export interface IUploadKeySignaturesResponse { failures: Record<string, Record<string, { errcode: string; error: string; }>>; } export interface IPreviewUrlResponse { [key: string]: undefined | string | number; "og:title": string; "og:type": string; "og:url": string; "og:image"?: string; "og:image:type"?: string; "og:image:height"?: number; "og:image:width"?: number; "og:description"?: string; "matrix:image:size"?: number; } export interface ITurnServerResponse { uris: string[]; username: string; password: string; ttl: number; } export interface ITurnServer { urls: string[]; username: string; credential: string; } export interface IServerVersions { versions: string[]; unstable_features: Record<string, boolean>; } export declare const M_AUTHENTICATION: UnstableValue<"m.authentication", "org.matrix.msc2965.authentication">; export interface IClientWellKnown { [key: string]: any; "m.homeserver"?: IWellKnownConfig; "m.identity_server"?: IWellKnownConfig; [M_AUTHENTICATION.name]?: IDelegatedAuthConfig; } export interface IWellKnownConfig { raw?: IClientWellKnown; action?: AutoDiscoveryAction; reason?: string; error?: Error | string; base_url?: string | null; server_name?: string; } export interface IDelegatedAuthConfig { /** The OIDC Provider/issuer the client should use */ issuer: string; /** The optional URL of the web UI where the user can manage their account */ account?: string; } interface IMediaConfig { [key: string]: any; "m.upload.size"?: number; } interface ITagMetadata { [key: string]: any; order: number; } interface IMessagesResponse { start?: string; end?: string; chunk: IRoomEvent[]; state?: IStateEvent[]; } export interface IRequestTokenResponse { sid: string; submit_url?: string; } export interface IRequestMsisdnTokenResponse extends IRequestTokenResponse { msisdn: string; success: boolean; intl_fmt: string; } export interface IUploadKeysRequest { "device_keys"?: Required<IDeviceKeys>; "one_time_keys"?: Record<string, IOneTimeKey>; "org.matrix.msc2732.fallback_keys"?: Record<string, IOneTimeKey>; } export interface IQueryKeysRequest { device_keys: { [userId: string]: string[]; }; timeout?: number; token?: string; } export interface IClaimKeysRequest { one_time_keys: { [userId: string]: { [deviceId: string]: string; }; }; timeout?: number; } export interface IOpenIDToken { access_token: string; token_type: "Bearer" | string; matrix_server_name: string; expires_in: number; } interface IRoomInitialSyncResponse { room_id: string; membership: "invite" | "join" | "leave" | "ban"; messages?: { start?: string; end?: string; chunk: IEventWithRoomId[]; }; state?: IStateEventWithRoomId[]; visibility: Visibility; account_data?: IMinimalEvent[]; presence: Partial<IEvent>; } interface IJoinedRoomsResponse { joined_rooms: string[]; } interface IJoinedMembersResponse { joined: { [userId: string]: { display_name: string; avatar_url: string; }; }; } export interface IRegisterRequestParams { auth?: IAuthData; username?: string; password?: string; refresh_token?: boolean; guest_access_token?: string; x_show_msisdn?: boolean; bind_msisdn?: boolean; bind_email?: boolean; inhibit_login?: boolean; initial_device_display_name?: string; } export interface IPublicRoomsChunkRoom { room_id: string; name?: string; avatar_url?: string; topic?: string; canonical_alias?: string; aliases?: string[]; world_readable: boolean; guest_can_join: boolean; num_joined_members: number; room_type?: RoomType | string; } interface IPublicRoomsResponse { chunk: IPublicRoomsChunkRoom[]; next_batch?: string; prev_batch?: string; total_room_count_estimate?: number; } interface IUserDirectoryResponse { results: { user_id: string; display_name?: string; avatar_url?: string; }[]; limited: boolean; } export interface IMyDevice { "device_id": string; "display_name"?: string; "last_seen_ip"?: string; "last_seen_ts"?: number; "last_seen_user_agent"?: string; "org.matrix.msc3852.last_seen_user_agent"?: string; } export interface Keys { keys: { [keyId: string]: string; }; usage: string[]; user_id: string; } export interface SigningKeys extends Keys { signatures: ISignatures; } export interface DeviceKeys { [deviceId: string]: IDeviceKeys & { unsigned?: { device_display_name: string; }; }; } export interface IDownloadKeyResult { failures: { [serverName: string]: object; }; device_keys: { [userId: string]: DeviceKeys; }; master_keys?: { [userId: string]: Keys; }; self_signing_keys?: { [userId: string]: SigningKeys; }; user_signing_keys?: { [userId: string]: SigningKeys; }; } export interface IClaimOTKsResult { failures: { [serverName: string]: object; }; one_time_keys: { [userId: string]: { [deviceId: string]: { [keyId: string]: { key: string; signatures: ISignatures; }; }; }; }; } export interface IFieldType { regexp: string; placeholder: string; } export interface IInstance { desc: string; icon?: string; fields: object; network_id: string; instance_id: string; } export interface IProtocol { user_fields: string[]; location_fields: string[]; icon: string; field_types: Record<string, IFieldType>; instances: IInstance[]; } interface IThirdPartyLocation { alias: string; protocol: string; fields: object; } interface IThirdPartyUser { userid: string; protocol: string; fields: object; } interface IRoomSummary extends Omit<IPublicRoomsChunkRoom, "canonical_alias" | "aliases"> { room_type?: RoomType; membership?: string; is_encrypted: boolean; } interface IRoomHierarchy { rooms: IHierarchyRoom[]; next_batch?: string; } interface ITimestampToEventResponse { event_id: string; origin_server_ts: string; } interface IWhoamiResponse { user_id: string; device_id?: string; } export declare enum ClientEvent { Sync = "sync", Event = "event", ToDeviceEvent = "toDeviceEvent", AccountData = "accountData", Room = "Room", DeleteRoom = "deleteRoom", SyncUnexpectedError = "sync.unexpectedError", ClientWellKnown = "WellKnown.client", ReceivedVoipEvent = "received_voip_event", UndecryptableToDeviceEvent = "toDeviceEvent.undecryptable", TurnServers = "turnServers", TurnServersError = "turnServers.error" } type RoomEvents = RoomEvent.Name | RoomEvent.Redaction | RoomEvent.RedactionCancelled | RoomEvent.Receipt | RoomEvent.Tags | RoomEvent.LocalEchoUpdated | RoomEvent.HistoryImportedWithinTimeline | RoomEvent.AccountData | RoomEvent.MyMembership | RoomEvent.Timeline | RoomEvent.TimelineReset; type RoomStateEvents = RoomStateEvent.Events | RoomStateEvent.Members | RoomStateEvent.NewMember | RoomStateEvent.Update | RoomStateEvent.Marker; type CryptoEvents = CryptoEvent.KeySignatureUploadFailure | CryptoEvent.KeyBackupStatus | CryptoEvent.KeyBackupFailed | CryptoEvent.KeyBackupSessionsRemaining | CryptoEvent.RoomKeyRequest | CryptoEvent.RoomKeyRequestCancellation | CryptoEvent.VerificationRequest | CryptoEvent.DeviceVerificationChanged | CryptoEvent.UserTrustStatusChanged | CryptoEvent.KeysChanged | CryptoEvent.Warning | CryptoEvent.DevicesUpdated | CryptoEvent.WillUpdateDevices; type MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange; type RoomMemberEvents = RoomMemberEvent.Name | RoomMemberEvent.Typing | RoomMemberEvent.PowerLevel | RoomMemberEvent.Membership; type UserEvents = UserEvent.AvatarUrl | UserEvent.DisplayName | UserEvent.Presence | UserEvent.CurrentlyActive | UserEvent.LastPresenceTs; export type EmittedEvents = ClientEvent | RoomEvents | RoomStateEvents | CryptoEvents | MatrixEventEvents | RoomMemberEvents | UserEvents | CallEvent | CallEventHandlerEvent.Incoming | GroupCallEventHandlerEvent.Incoming | GroupCallEventHandlerEvent.Outgoing | GroupCallEventHandlerEvent.Ended | GroupCallEventHandlerEvent.Participants | HttpApiEvent.SessionLoggedOut | HttpApiEvent.NoConsent | BeaconEvent; export type ClientEventHandlerMap = { /** * Fires whenever the SDK's syncing state is updated. The state can be one of: * <ul> * * <li>PREPARED: The client has synced with the server at least once and is * ready for methods to be called on it. This will be immediately followed by * a state of SYNCING. <i>This is the equivalent of "syncComplete" in the * previous API.</i></li> * * <li>CATCHUP: The client has detected the connection to the server might be * available again and will now try to do a sync again. As this sync might take * a long time (depending how long ago was last synced, and general server * performance) the client is put in this mode so the UI can reflect trying * to catch up with the server after losing connection.</li> * * <li>SYNCING : The client is currently polling for new events from the server. * This will be called <i>after</i> processing latest events from a sync.</li> * * <li>ERROR : The client has had a problem syncing with the server. If this is * called <i>before</i> PREPARED then there was a problem performing the initial * sync. If this is called <i>after</i> PREPARED then there was a problem polling * the server for updates. This may be called multiple times even if the state is * already ERROR. <i>This is the equivalent of "syncError" in the previous * API.</i></li> * * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that * should be considered erroneous. * </li> * * <li>STOPPED: The client has stopped syncing with server due to stopClient * being called. * </li> * </ul> * State transition diagram: * ``` * +---->STOPPED * | * +----->PREPARED -------> SYNCING <--+ * | ^ | ^ | * | CATCHUP ----------+ | | | * | ^ V | | * null ------+ | +------- RECONNECTING | * | V V | * +------->ERROR ---------------------+ * * NB: 'null' will never be emitted by this event. * * ``` * Transitions: * <ul> * * <li>`null -> PREPARED` : Occurs when the initial sync is completed * first time. This involves setting up filters and obtaining push rules. * * <li>`null -> ERROR` : Occurs when the initial sync failed first time. * * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds * after previously failing. * * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning * to PREPARED. Starts listening for live updates rather than catching up. * * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails. * * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls * continue to fail, but the keepalive calls (to /versions) succeed. * * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails * * <li>`ERROR -> SYNCING` : Occurs when the client has performed a * live update after having previously failed. * * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive * for a second time or more.</li> * * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live * update. This is called <i>after</i> processing.</li> * * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or * trying to sync after stopClient has been called.</li> * </ul> * * @param state - An enum representing the syncing state. One of "PREPARED", * "SYNCING", "ERROR", "STOPPED". * * @param prevState - An enum representing the previous syncing state. * One of "PREPARED", "SYNCING", "ERROR", "STOPPED" <b>or null</b>. * * @param data - Data about this transition. * * @example * ``` * matrixClient.on("sync", function(state, prevState, data) { * switch (state) { * case "ERROR": * // update UI to say "Connection Lost" * break; * case "SYNCING": * // update UI to remove any "Connection Lost" message * break; * case "PREPARED": * // the client instance is ready to be queried. * var rooms = matrixClient.getRooms(); * break; * } * }); * ``` */ [ClientEvent.Sync]: (state: SyncState, lastState: SyncState | null, data?: ISyncStateData) => void; /** * Fires whenever the SDK receives a new event. * <p> * This is only fired for live events received via /sync - it is not fired for * events received over context, search, or pagination APIs. * * @param event - The matrix event which caused this event to fire. * @example * ``` * matrixClient.on("event", function(event){ * var sender = event.getSender(); * }); * ``` */ [ClientEvent.Event]: (event: MatrixEvent) => void; /** * Fires whenever the SDK receives a new to-device event. * @param event - The matrix event which caused this event to fire. * @example * ``` * matrixClient.on("toDeviceEvent", function(event){ * var sender = event.getSender(); * }); * ``` */ [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void; /** * Fires if a to-device event is received that cannot be decrypted. * Encrypted to-device events will (generally) use plain Olm encryption, * in which case decryption failures are fatal: the event will never be * decryptable, unlike Megolm encrypted events where the key may simply * arrive later. * * An undecryptable to-device event is therefore likley to indicate problems. * * @param event - The undecyptable to-device event */ [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void; /** * Fires whenever new user-scoped account_data is added. * @param event - The event describing the account_data just added * @param event - The previous account data, if known. * @example * ``` * matrixClient.on("accountData", function(event, oldEvent){ * myAccountData[event.type] = event.content; * }); * ``` */ [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void; /** * Fires whenever a new Room is added. This will fire when you are invited to a * room, as well as when you join a room. <strong>This event is experimental and * may change.</strong> * @param room - The newly created, fully populated room. * @example * ``` * matrixClient.on("Room", function(room){ * var roomId = room.roomId; * }); * ``` */ [ClientEvent.Room]: (room: Room) => void; /** * Fires whenever a Room is removed. This will fire when you forget a room. * <strong>This event is experimental and may change.</strong> * @param roomId - The deleted room ID. * @example * ``` * matrixClient.on("deleteRoom", function(roomId){ * // update UI from getRooms() * }); * ``` */ [ClientEvent.DeleteRoom]: (roomId: string) => void; [ClientEvent.SyncUnexpectedError]: (error: Error) => void; /** * Fires when the client .well-known info is fetched. * * @param data - The JSON object returned by the server */ [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void; [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void; [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void; [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void; } & RoomEventHandlerMap & RoomStateEventHandlerMap & CryptoEventHandlerMap & MatrixEventHandlerMap & RoomMemberEventHandlerMap & UserEventHandlerMap & CallEventHandlerEventHandlerMap & GroupCallEventHandlerEventHandlerMap & CallEventHandlerMap & HttpApiEventHandlerMap & BeaconEventHandlerMap; /** * Represents a Matrix Client. Only directly construct this if you want to use * custom modules. Normally, {@link createClient} should be used * as it specifies 'sensible' defaults for these modules. */ export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> { static readonly RESTORE_BACKUP_ERROR_BAD_KEY = "RESTORE_BACKUP_ERROR_BAD_KEY"; reEmitter: TypedReEmitter<EmittedEvents, ClientEventHandlerMap>; olmVersion: [number, number, number] | null; usingExternalCrypto: boolean; store: Store; deviceId: string | null; credentials: { userId: string | null; }; pickleKey?: string; scheduler?: MatrixScheduler; clientRunning: boolean; timelineSupport: boolean; urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse>; }; identityServer?: IIdentityServerProvider; http: MatrixHttpApi<IHttpOpts & { onlyData: true; }>; crypto?: Crypto; private cryptoBackend?; cryptoCallbacks: ICryptoCallbacks; callEventHandler?: CallEventHandler; groupCallEventHandler?: GroupCallEventHandler; supportsCallTransfer: boolean; forceTURN: boolean; iceCandidatePoolSize: number; idBaseUrl?: string; baseUrl: string; protected canSupportVoip: boolean; protected peekSync: SyncApi | null; protected isGuestAccount: boolean; protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number; }; }; protected notifTimelineSet: EventTimelineSet | null; protected cryptoStore?: CryptoStore; protected verificationMethods?: VerificationMethod[]; protected fallbackICEServerAllowed: boolean; protected roomList: RoomList; protected syncApi?: SlidingSyncSdk | SyncApi; roomNameGenerator?: ICreateClientOpts["roomNameGenerator"]; pushRules?: IPushRules; protected syncLeftRoomsPromise?: Promise<Room[]>; protected syncedLeftRooms: boolean; protected clientOpts?: IStoredClientOpts; protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>; protected canResetTimelineCallback?: ResetTimelineCallback; canSupport: Map<Feature, ServerSupport>; protected pushProcessor: PushProcessor; protected serverVersionsPromise?: Promise<IServerVersions>; cachedCapabilities?: { capabilities: ICapabilities; expiration: number; }; protected clientWellKnown?: IClientWellKnown; protected clientWellKnownPromise?: Promise<IClientWellKnown>; protected turnServers: ITurnServer[]; protected turnServersExpiry: number; protected checkTurnServersIntervalID?: ReturnType<typeof setInterval>; protected exportedOlmDeviceToImport?: IExportedOlmDevice; protected txnCtr: number; protected mediaHandler: MediaHandler; protected sessionId: string; protected pendingEventEncryption: Map<string, Promise<void>>; private useE2eForGroupCall; private toDeviceMessageQueue; readonly ignoredInvites: IgnoredInvites; constructor(opts: IMatrixClientCreateOpts); /** * High level helper method to begin syncing and poll for new events. To listen for these * events, add a listener for {@link ClientEvent.Event} * via {@link MatrixClient#on}. Alternatively, listen for specific * state change events. * @param opts - Options to apply when syncing. */ startClient(opts?: IStartClientOpts): Promise<void>; /** * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor */ protected buildSyncApiOptions(): SyncApiOptions; /** * High level helper method to stop the client from polling and allow a * clean shutdown. */ stopClient(): void; /** * 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 which resolves to undefined if a device could not be dehydrated, or * to the new device ID if the dehydration was successful. * @returns Rejects: with an error response. */ rehydrateDevice(): Promise<string | undefined>; /** * Get the current dehydrated device, if any * @returns A promise of an object containing the dehydrated device */ getDehydratedDevice(): Promise<IDehydratedDevice | undefined>; /** * Set the dehydration key. This will also periodically dehydrate devices to * the server. * * @param key - the dehydration key * @param keyInfo - Information about the key. Primarily for * information about how to generate the key from a passphrase. * @param deviceDisplayName - The device display name for the * dehydrated device. * @returns A promise that resolves when the dehydrated device is stored. */ setDehydrationKey(key: Uint8Array, keyInfo: IDehydratedDeviceKeyInfo, deviceDisplayName?: string): Promise<void>; /** * Creates a new dehydrated device (without queuing periodic dehydration) * @param key - the dehydration key * @param keyInfo - Information about the key. Primarily for * information about how to generate the key from a passphrase. * @param deviceDisplayName - The device display name for the * dehydrated device. * @returns the device id of the newly created dehydrated device */ createDehydratedDevice(key: Uint8Array, keyInfo: IDehydratedDeviceKeyInfo, deviceDisplayName?: string): Promise<string | undefined>; exportDevice(): Promise<IExportedDevice | undefined>; /** * Clear any data out of the persistent stores used by the client. * * @returns Promise which resolves when the stores have been cleared. */ clearStores(): Promise<void>; /** * Get the user-id of the logged-in user * * @returns MXID for the logged-in user, or null if not logged in */ getUserId(): string | null; /** * Get the user-id of the logged-in user * * @returns MXID for the logged-in user * @throws Error if not logged in */ getSafeUserId(): string; /** * Get the domain for this client's MXID * @returns Domain of this MXID */ getDomain(): string | null; /** * Get the local part of the current user ID e.g. "foo" in "\@foo:bar". * @returns The user ID localpart or null. */ getUserIdLocalpart(): string | null; /** * Get the device ID of this client * @returns device ID */ getDeviceId(): string | null; /** * Get the session ID of this client * @returns session ID */ getSessionId(): string; /** * Check if the runtime environment supports VoIP calling. * @returns True if VoIP is supported. */ supportsVoip(): boolean; /** * @returns */ getMediaHandler(): MediaHandler; /** * Set whether VoIP calls are forced to use only TURN * candidates. This is the same as the forceTURN option * when creating the client. * @param force - True to force use of TURN servers */ setForceTURN(force: boolean): void; /** * Set whether to advertise transfer support to other parties on Matrix calls. * @param support - True to advertise the 'm.call.transferee' capability */ setSupportsCallTransfer(support: boolean): void; /** * Returns true if to-device signalling for group calls will be encrypted with Olm. * If false, it will be sent unencrypted. * @returns boolean Whether group call signalling will be encrypted */ getUseE2eForGroupCall(): boolean; /** * Creates a new call. * The place*Call methods on the returned call can be used to actually place a call * * @param roomId - The room the call is to be placed in. * @returns the call or null if the browser doesn't support calling. */ createCall(roomId: string): MatrixCall | null; /** * Creates a new group call and sends the associated state event * to alert other members that the room now has a group call. * * @param roomId - The room the call is to be placed in. */ createGroupCall(roomId: string, type: GroupCallType, isPtt: boolean, intent: GroupCallIntent, dataChannelsEnabled?: boolean, dataChannelOptions?: IGroupCallDataChannelOptions): Promise<GroupCall>; /** * 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. * @param roomId - The room ID to wait for * @returns A promise that resolves once existing group calls in the room * have been processed. */ waitUntilRoomReadyForGroupCalls(roomId: string): Promise<void>; /** * Get an existing group call for the provided room. * @returns The group call or null if it doesn't already exist. */ getGroupCallForRoom(roomId: string): GroupCall | null; /** * Get the current sync state. * @returns the sync state, which may be null. * @see MatrixClient#event:"sync" */ getSyncState(): SyncState | null; /** * Returns the additional data object associated with * the current sync state, or null if there is no * such data. * Sync errors, if available, are put in the 'error' key of * this object. */ getSyncStateData(): ISyncStateData | null; /** * Whether the initial sync has completed. * @returns True if at least one sync has happened. */ isInitialSyncComplete(): boolean; /** * Return whether the client is configured for a guest account. * @returns True if this is a guest access_token (or no token is supplied). */ isGuest(): boolean; /** * Set whether this client is a guest account. <b>This method is experimental * and may change without warning.</b> * @param guest - True if this is a guest account. */ setGuest(guest: boolean): void; /** * Return the provided scheduler, if any. * @returns The scheduler or undefined */ getScheduler(): MatrixScheduler | undefined; /** * Retry a backed off syncing request immediately. This should only be used when * the user <b>explicitly</b> 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 True if this resulted in a request being retried. */ retryImmediately(): boolean; /** * Return the global notification EventTimelineSet, if any * * @returns the globl notification EventTimelineSet */ getNotifTimelineSet(): EventTimelineSet | null; /** * Set the global notification EventTimelineSet * */ setNotifTimelineSet(set: EventTimelineSet): void; /** * Gets the capabilities of the homeserver. Always returns an object of * capability keys and their options, which may be empty. * @param fresh - True to ignore any cached values. * @returns Promise which resolves to the capabilities of the homeserver * @returns Rejects: with an error response. */ getCapabilities(fresh?: boolean): Promise<ICapabilities>; /** * 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. */ initCrypto(): Promise<void>; /** * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto. * * An alternative to {@link initCrypto}. * * *WARNING*: this API is very experimental, should not be used in production, and may change without notice! * Eventually it will be deprecated and `initCrypto` will do the same thing. * * @experimental * * @returns a Promise which will resolve when the crypto layer has been * successfully initialised. */ initRustCrypto(): Promise<void>; /** * Is end-to-end crypto enabled for this client. * @returns True if end-to-end is enabled. */ isCryptoEnabled(): boolean; /** * Get the Ed25519 key for this device * * @returns base64-encoded ed25519 key. Null if crypto is * disabled. */ getDeviceEd25519Key(): string | null; /** * Get the Curve25519 key for this device * * @returns base64-encoded curve25519 key. Null if crypto is * disabled. */ getDeviceCurve25519Key(): string | null; /** * @deprecated Does nothing. */ uploadKeys(): Promise<void>; /** * Download the keys for a list of users and stores the keys in the session * store. * @param userIds - The users to fetch. * @param forceDownload - Always download the keys even if cached. * * @returns A promise which resolves to a map userId-\>deviceId-\>{@link DeviceInfo} */ downloadKeys(userIds: string[], forceDownload?: boolean): Promise<Record<string, Record<string, IDevice>>>; /** * Get the stored device keys for a user id * * @param userId - the user to list keys for. * * @returns list of devices */ getStoredDevicesForUser(userId: string): DeviceInfo[]; /** * Get the stored device key for a user id and device id * * @param userId - the user to list keys for. * @param deviceId - unique identifier for the device * * @returns device or null */ getStoredDevice(userId: string, deviceId: string): DeviceInfo | null; /** * Mark the given device as verified * * @param userId - owner of the device * @param deviceId - unique identifier for the device or user's * cross-signing public key ID. * * @param verified - whether to mark the device as verified. defaults * to 'true'. * * @returns * * @remarks * Fires {@link CryptoEvent#DeviceVerificationChanged} */ setDeviceVerified(userId: string, deviceId: string, verified?: boolean): Promise<void>; /** * Mark the given device as blocked/unblocked * * @param userId - owner of the device * @param deviceId - unique identifier for the device or user's * cross-signing public key ID. * * @param blocked - whether to mark the device as blocked. defaults * to 'true'. * * @returns * * @remarks * Fires {@link CryptoEvent.DeviceVerificationChanged} */ setDeviceBlocked(userId: string, deviceId: string, blocked?: boolean): Promise<void>; /** * Mark the given device as known/unknown * * @param userId - owner of the device * @param deviceId - unique identifier for the device or user's * cross-signing public key ID. * * @param known - whether to mark the device as known. defaults * to 'true'. * * @returns * * @remarks * Fires {@link CryptoEvent#DeviceVerificationChanged} */ setDeviceKnown(userId: string, deviceId: string, known?: boolean): Promise<void>; private setDeviceVerification; /** * Request a key verification from another user, using a DM. * * @param userId - the user to request verification with * @param roomId - the room to use for verification * * @returns resolves to a VerificationRequest * when the request has been sent to the other party. */ requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest>; /** * Finds a DM verification request that is already in progress for the given room id * * @param roomId - the room to use for verification * * @returns the VerificationRequest that is in progress, if any */ findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined; /** * Returns all to-device verification requests that are already in progress for the given user id * * @param userId - the ID of the user to query * * @returns the VerificationRequests that are in progress */ getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[]; /** * Request a key verification from another user. * * @param userId - the user to request verification with * @param devices - array of device IDs to send requests to. Defaults to * all devices owned by the user * * @returns resolves to a VerificationRequest * when the request has been sent to the other party. */ requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest>; /** * Begin a key verification. * * @param method - the verification method to use * @param userId - the user to verify keys with * @param deviceId - the device to verify * * @returns a verification object * @deprecated Use `requestVerification` instead. */ beginKeyVerification(method: string, userId: string, deviceId: string): Verification<any, any>; checkSecretStorageKey(key: Uint8Array, info: ISecretStorageKeyInfo): Promise<boolean>; /** * 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. * * @param value - whether to blacklist all unverified devices by default */ setGlobalBlacklistUnverifiedDevices(value: boolean): boolean; /** * @returns whether to blacklist all unverified devices by default */ getGlobalBlacklistUnverifiedDevices(): boolean; /** * 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. *