diff --git a/src/stores/widgets/StopGapWidgetDriver.ts b/src/stores/widgets/StopGapWidgetDriver.ts index 6bb3e887da8..94ac9e5f8d9 100644 --- a/src/stores/widgets/StopGapWidgetDriver.ts +++ b/src/stores/widgets/StopGapWidgetDriver.ts @@ -73,6 +73,7 @@ import { navigateToPermalink } from "../../utils/permalinks/navigator"; import { SdkContextClass } from "../../contexts/SDKContext"; import { ModuleRunner } from "../../modules/ModuleRunner"; import SettingsStore from "../../settings/SettingsStore"; +import { Media } from "../../customisations/Media"; // TODO: Purge this from the universe @@ -679,4 +680,18 @@ export class StopGapWidgetDriver extends WidgetDriver { return { contentUri: uploadResult.content_uri }; } + + /** + * Download a file from the media repository on the homeserver. + * + * @param contentUri - the MXC URI of the file to download + * @returns an object with: file - response contents as Blob + */ + public async downloadFile(contentUri: string): Promise<{ file: XMLHttpRequestBodyInit }> { + const client = MatrixClientPeg.safeGet(); + const media = new Media({mxc: contentUri}, client); + const response = await media.downloadSource(); + const blob = await response.blob(); + return { file: blob }; + } } diff --git a/test/stores/widgets/StopGapWidgetDriver-test.ts b/test/stores/widgets/StopGapWidgetDriver-test.ts index 282ce23d6fa..d3751b7b799 100644 --- a/test/stores/widgets/StopGapWidgetDriver-test.ts +++ b/test/stores/widgets/StopGapWidgetDriver-test.ts @@ -15,6 +15,7 @@ limitations under the License. */ import { mocked, MockedObject } from "jest-mock"; +import fetchMockJest from "fetch-mock-jest"; import { MatrixClient, ClientEvent, @@ -616,4 +617,32 @@ describe("StopGapWidgetDriver", () => { expect(client.uploadContent).toHaveBeenCalledWith("data"); }); }); + + describe("downloadFile", () => { + let driver: WidgetDriver; + + beforeEach(() => { + driver = mkDefaultDriver(); + }); + + it("should download a file and return the blob", async () => { + // eslint-disable-next-line no-restricted-properties + client.mxcUrlToHttp.mockImplementation((mxcUrl) => { + if (mxcUrl === "mxc://example.com/test_file") { + return "https://example.com/_matrix/media/v3/download/test_file"; + } + + return null; + }); + + fetchMockJest.get("https://example.com/_matrix/media/v3/download/test_file", "test contents"); + + const result = await driver.downloadFile("mxc://example.com/test_file"); + // A type test is impossible here because of + // https://github.com/jefflau/jest-fetch-mock/issues/209 + // Tell TypeScript that file is a blob. + const file = result.file as Blob; + await expect(file.text()).resolves.toEqual("test contents"); + }); + }); });