Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Adapt for js-sdk MatrixClient conversion to TS #6132

Merged
merged 3 commits into from
Jun 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions src/ContentMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
UploadStartedPayload,
} from "./dispatcher/payloads/UploadPayload";
import {IUpload} from "./models/IUpload";
import { IImageInfo } from "matrix-js-sdk/src/@types/partials";

const MAX_WIDTH = 800;
const MAX_HEIGHT = 600;
Expand Down Expand Up @@ -208,12 +209,12 @@ function infoForImageFile(matrixClient, roomId, imageFile) {
}

let imageInfo;
return loadImageElement(imageFile).then(function(r) {
return loadImageElement(imageFile).then((r) => {
return createThumbnail(r.img, r.width, r.height, thumbnailType);
}).then(function(result) {
}).then((result) => {
imageInfo = result.info;
return uploadFile(matrixClient, roomId, result.thumbnail);
}).then(function(result) {
}).then((result) => {
imageInfo.thumbnail_url = result.url;
imageInfo.thumbnail_file = result.file;
return imageInfo;
Expand Down Expand Up @@ -264,12 +265,12 @@ function infoForVideoFile(matrixClient, roomId, videoFile) {
const thumbnailType = "image/jpeg";

let videoInfo;
return loadVideoElement(videoFile).then(function(video) {
return loadVideoElement(videoFile).then((video) => {
return createThumbnail(video, video.videoWidth, video.videoHeight, thumbnailType);
}).then(function(result) {
}).then((result) => {
videoInfo = result.info;
return uploadFile(matrixClient, roomId, result.thumbnail);
}).then(function(result) {
}).then((result) => {
videoInfo.thumbnail_url = result.url;
videoInfo.thumbnail_file = result.file;
return videoInfo;
Expand Down Expand Up @@ -308,7 +309,12 @@ function readFileAsArrayBuffer(file: File | Blob): Promise<ArrayBuffer> {
* If the file is unencrypted then the object will have a "url" key.
* If the file is encrypted then the object will have a "file" key.
*/
function uploadFile(matrixClient: MatrixClient, roomId: string, file: File | Blob, progressHandler?: any) {
function uploadFile(
matrixClient: MatrixClient,
roomId: string,
file: File | Blob,
progressHandler?: any, // TODO: Types
): Promise<{url?: string, file?: any}> { // TODO: Types
let canceled = false;
if (matrixClient.isRoomEncrypted(roomId)) {
// If the room is encrypted then encrypt the file before uploading it.
Expand Down Expand Up @@ -355,7 +361,7 @@ function uploadFile(matrixClient: MatrixClient, roomId: string, file: File | Blo
// If the attachment isn't encrypted then include the URL directly.
return {"url": url};
});
promise1.abort = () => {
(promise1 as any).abort = () => {
canceled = true;
MatrixClientPeg.get().cancelUpload(basePromise);
};
Expand All @@ -367,7 +373,7 @@ export default class ContentMessages {
private inprogress: IUpload[] = [];
private mediaConfig: IMediaConfig = null;

sendStickerContentToRoom(url: string, roomId: string, info: string, text: string, matrixClient: MatrixClient) {
sendStickerContentToRoom(url: string, roomId: string, info: IImageInfo, text: string, matrixClient: MatrixClient) {
const startTime = CountlyAnalytics.getTimestamp();
const prom = MatrixClientPeg.get().sendStickerMessage(roomId, url, info, text).catch((e) => {
console.warn(`Failed to send content with URL ${url} to room ${roomId}`, e);
Expand Down Expand Up @@ -441,7 +447,7 @@ export default class ContentMessages {
let uploadAll = false;
// Promise to complete before sending next file into room, used for synchronisation of file-sending
// to match the order the files were specified in
let promBefore = Promise.resolve();
let promBefore: Promise<any> = Promise.resolve();
for (let i = 0; i < okFiles.length; ++i) {
const file = okFiles[i];
if (!uploadAll) {
Expand Down
2 changes: 1 addition & 1 deletion src/Presence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class Presence {
}

try {
await MatrixClientPeg.get().setPresence(this.state);
await MatrixClientPeg.get().setPresence({presence: this.state});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, an actual bug fix?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apaprently we migrated to an object long ago and maintained this signature, but the types don't like it so I fixed it :P

I suspect it's net zero for bugs, unfortunately.

console.info("Presence:", newState);
} catch (err) {
console.error("Failed to set presence:", err);
Expand Down
10 changes: 5 additions & 5 deletions src/Searching.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async function serverSideSearchProcess(term, roomId = undefined) {
highlights: [],
};

return client._processRoomEventsSearch(searchResult, result.response);
return client.processRoomEventsSearch(searchResult, result.response);
}

function compareEvents(a, b) {
Expand Down Expand Up @@ -131,7 +131,7 @@ async function combinedSearch(searchTerm) {
},
};

const result = client._processRoomEventsSearch(emptyResult, response);
const result = client.processRoomEventsSearch(emptyResult, response);

// Restore our encryption info so we can properly re-verify the events.
restoreEncryptionInfo(result.results);
Expand Down Expand Up @@ -185,7 +185,7 @@ async function localSearchProcess(searchTerm, roomId = undefined) {
},
};

const processedResult = MatrixClientPeg.get()._processRoomEventsSearch(emptyResult, response);
const processedResult = MatrixClientPeg.get().processRoomEventsSearch(emptyResult, response);
// Restore our encryption info so we can properly re-verify the events.
restoreEncryptionInfo(processedResult.results);

Expand All @@ -210,7 +210,7 @@ async function localPagination(searchResult) {
},
};

const result = MatrixClientPeg.get()._processRoomEventsSearch(searchResult, response);
const result = MatrixClientPeg.get().processRoomEventsSearch(searchResult, response);

// Restore our encryption info so we can properly re-verify the events.
const newSlice = result.results.slice(Math.max(result.results.length - newResultCount, 0));
Expand Down Expand Up @@ -520,7 +520,7 @@ async function combinedPagination(searchResult) {
const oldResultCount = searchResult.results ? searchResult.results.length : 0;

// Let the client process the combined result.
const result = client._processRoomEventsSearch(searchResult, response);
const result = client.processRoomEventsSearch(searchResult, response);

// Restore our encryption info so we can properly re-verify the events.
const newResultCount = result.results.length - oldResultCount;
Expand Down
2 changes: 1 addition & 1 deletion src/SecurityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ async function onSecretRequested(
}
return key && encodeBase64(key);
} else if (name === "m.megolm_backup.v1") {
const key = await client._crypto.getSessionBackupPrivateKey();
const key = await client.crypto.getSessionBackupPrivateKey();
if (!key) {
console.log(
`session backup key requested by ${deviceId}, but not found in cache`,
Expand Down
2 changes: 1 addition & 1 deletion src/Terms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export async function startTermsFlow(

// fetch the set of agreed policy URLs from account data
const currentAcceptedTerms = await MatrixClientPeg.get().getAccountData('m.accepted_terms');
let agreedUrlSet;
let agreedUrlSet: Set<string>;
if (!currentAcceptedTerms || !currentAcceptedTerms.getContent() || !currentAcceptedTerms.getContent().accepted) {
agreedUrlSet = new Set();
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/LoggedInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ class LoggedInView extends React.Component<IProps, IState> {

const pinnedEventIds = pinStateEvent.getContent().pinned.slice(0, MAX_PINNED_NOTICES_PER_ROOM);
for (const eventId of pinnedEventIds) {
const timeline = await this._matrixClient.getEventTimeline(room.getUnfilteredTimelineSet(), eventId, 0);
const timeline = await this._matrixClient.getEventTimeline(room.getUnfilteredTimelineSet(), eventId);
const event = timeline.getEvents().find(ev => ev.getId() === eventId);
if (event) events.push(event);
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.onLoggedIn();
}

const promisesList = [this.firstSyncPromise.promise];
const promisesList: Promise<any>[] = [this.firstSyncPromise.promise];
if (cryptoEnabled) {
// wait for the client to finish downloading cross-signing keys for us so we
// know whether or not we have keys set up on this account
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/auth/Registration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ interface IProps {
is_url?: string;
session_id: string;
/* eslint-enable camelcase */
}): void;
}): string;
// registration shouldn't know or care how login is done.
onLoginClick(): void;
onServerConfigChange(config: ValidatedServerConfig): void;
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/dialogs/DevtoolsDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,7 @@ class VerificationExplorer extends React.PureComponent<IExplorerProps> {
render() {
const cli = this.context;
const room = this.props.room;
const inRoomChannel = cli._crypto._inRoomVerificationRequests;
const inRoomChannel = cli.crypto._inRoomVerificationRequests;
const inRoomRequests = (inRoomChannel._requestsByRoomId || new Map()).get(room.roomId) || new Map();

return (<div>
Expand Down
4 changes: 2 additions & 2 deletions src/components/views/settings/CrossSigningPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export default class CrossSigningPanel extends React.PureComponent {
async _getUpdatedStatus() {
const cli = MatrixClientPeg.get();
const pkCache = cli.getCrossSigningCacheCallbacks();
const crossSigning = cli._crypto._crossSigningInfo;
const secretStorage = cli._crypto._secretStorage;
const crossSigning = cli.crypto._crossSigningInfo;
const secretStorage = cli.crypto._secretStorage;
const crossSigningPublicKeysOnDevice = crossSigning.getId();
const crossSigningPrivateKeysInStorage = await crossSigning.isStoredInSecretStorage(secretStorage);
const masterPrivateKeyCached = !!(pkCache && await pkCache.getCrossSigningKeyCache("master"));
Expand Down
4 changes: 2 additions & 2 deletions src/components/views/settings/SecureBackupPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ export default class SecureBackupPanel extends React.PureComponent {

async _getUpdatedDiagnostics() {
const cli = MatrixClientPeg.get();
const secretStorage = cli._crypto._secretStorage;
const secretStorage = cli.crypto._secretStorage;

const backupKeyStored = !!(await cli.isKeyBackupKeyStored());
const backupKeyFromCache = await cli._crypto.getSessionBackupPrivateKey();
const backupKeyFromCache = await cli.crypto.getSessionBackupPrivateKey();
const backupKeyCached = !!(backupKeyFromCache);
const backupKeyWellFormed = backupKeyFromCache instanceof Uint8Array;
const secretStorageKeyInAccount = await secretStorage.hasKey();
Expand Down
2 changes: 1 addition & 1 deletion src/indexing/EventIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ export default class EventIndex extends EventEmitter {
let res;

try {
res = await client._createMessagesRequest(
res = await client.createMessagesRequest(
checkpoint.roomId, checkpoint.token, this._eventsPerCrawl,
checkpoint.direction);
} catch (e) {
Expand Down
6 changes: 3 additions & 3 deletions src/rageshake/submit-rageshake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ async function collectBugReport(opts: IOpts = {}, gzipLogs = true) {
body.append('cross_signing_key', client.getCrossSigningId());

// add cross-signing status information
const crossSigning = client._crypto._crossSigningInfo;
const secretStorage = client._crypto._secretStorage;
const crossSigning = client.crypto._crossSigningInfo;
const secretStorage = client.crypto._secretStorage;

body.append("cross_signing_ready", String(await client.isCrossSigningReady()));
body.append("cross_signing_supported_by_hs",
Expand All @@ -114,7 +114,7 @@ async function collectBugReport(opts: IOpts = {}, gzipLogs = true) {
body.append("secret_storage_key_in_account", String(!!(await secretStorage.hasKey())));

body.append("session_backup_key_in_secret_storage", String(!!(await client.isKeyBackupKeyStored())));
const sessionBackupKeyFromCache = await client._crypto.getSessionBackupPrivateKey();
const sessionBackupKeyFromCache = await client.crypto.getSessionBackupPrivateKey();
body.append("session_backup_key_cached", String(!!sessionBackupKeyFromCache));
body.append("session_backup_key_well_formed", String(sessionBackupKeyFromCache instanceof Uint8Array));
}
Expand Down
2 changes: 1 addition & 1 deletion src/stores/CommunityPrototypeStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export class CommunityPrototypeStore extends AsyncStoreWithClient<IState> {
if (membership === EffectiveMembership.Invite) {
try {
const path = utils.encodeUri("/rooms/$roomId/group_info", {$roomId: room.roomId});
const profile = await this.matrixClient._http.authedRequest(
const profile = await this.matrixClient.http.authedRequest(
undefined, "GET", path,
undefined, undefined,
{prefix: "/_matrix/client/unstable/im.vector.custom"});
Expand Down
2 changes: 1 addition & 1 deletion src/stores/SetupEncryptionStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export class SetupEncryptionStore extends EventEmitter {
this.phase = PHASE_FINISHED;
this.emit("update");
// async - ask other clients for keys, if necessary
MatrixClientPeg.get()._crypto.cancelAndResendAllOutgoingKeyRequests();
MatrixClientPeg.get().crypto.cancelAndResendAllOutgoingKeyRequests();
}

async _setActiveVerificationRequest(request) {
Expand Down
2 changes: 1 addition & 1 deletion test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function createTestClient() {
}),

// Used by various internal bits we aren't concerned with (yet)
_sessionStore: {
sessionStore: {
store: {
getItem: jest.fn(),
},
Expand Down