Files
ThreadNet-Web/src/components/views/messages/MFileBody.tsx
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

350 lines
15 KiB
TypeScript
Raw Normal View History

2015-07-08 16:25:27 +01:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2015-2021 The Matrix.org Foundation C.I.C.
2015-07-08 16:25:27 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2015-07-08 16:25:27 +01:00
*/
2025-02-05 13:25:06 +00:00
import React, { type AllHTMLAttributes, createRef } from "react";
2021-10-22 17:23:32 -05:00
import { logger } from "matrix-js-sdk/src/logger";
2025-02-05 13:25:06 +00:00
import { type MediaEventContent } from "matrix-js-sdk/src/types";
import { Button } from "@vector-im/compound-web";
import { DownloadIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
2021-10-22 17:23:32 -05:00
2017-05-25 11:39:08 +01:00
import { _t } from "../../../languageHandler";
import Modal from "../../../Modal";
import AccessibleButton from "../elements/AccessibleButton";
2021-06-29 13:11:58 +01:00
import { mediaFromContent } from "../../../customisations/Media";
2021-03-09 12:54:20 -07:00
import ErrorDialog from "../dialogs/ErrorDialog";
import { downloadLabelForFile, presentableTextForFile } from "../../../utils/FileUtils";
2025-02-05 13:25:06 +00:00
import { type IBodyProps } from "./IBodyProps";
2021-07-29 15:36:50 -06:00
import { FileDownloader } from "../../../utils/FileDownloader";
2021-07-29 15:49:23 -06:00
import TextWithTooltip from "../elements/TextWithTooltip";
import RoomContext, { TimelineRenderingType } from "../../../contexts/RoomContext";
2023-02-13 11:39:16 +00:00
export let DOWNLOAD_ICON_URL: string; // cached copy of the download.svg asset for the sandboxed iframe later on
async function cacheDownloadIcon(): Promise<void> {
if (DOWNLOAD_ICON_URL) return; // cached already
2024-10-16 16:43:07 +01:00
// eslint-disable-next-line @typescript-eslint/no-require-imports
const svg = await fetch(require("@vector-im/compound-design-tokens/icons/download.svg").default).then((r) =>
r.text(),
);
DOWNLOAD_ICON_URL = "data:image/svg+xml;base64," + window.btoa(svg);
}
// Cache the asset immediately
// noinspection JSIgnoredPromiseFromCall
cacheDownloadIcon();
// User supplied content can contain scripts, we have to be careful that
// we don't accidentally run those script within the same origin as the
// client. Otherwise those scripts written by remote users can read
// the access token and end-to-end keys that are in local storage.
//
// For attachments downloaded directly from the homeserver we can use
// Content-Security-Policy headers to disable script execution.
//
// But attachments with end-to-end encryption are more difficult to handle.
// We need to decrypt the attachment on the client and then display it.
// To display the attachment we need to turn the decrypted bytes into a URL.
//
// There are two ways to turn bytes into URLs, data URL and blob URLs.
// Data URLs aren't suitable for downloading a file because Chrome has a
// 2MB limit on the size of URLs that can be viewed in the browser or
// downloaded. This limit does not seem to apply when the url is used as
// the source attribute of an image tag.
//
2018-02-15 20:20:19 +00:00
// Blob URLs are generated using window.URL.createObjectURL and unfortunately
// for our purposes they inherit the origin of the page that created them.
// This means that any scripts that run when the URL is viewed will be able
// to access local storage.
//
// The easiest solution is to host the code that generates the blob URL on
// a different domain to the client.
// Another possibility is to generate the blob URL within a sandboxed iframe.
// The downside of using a second domain is that it complicates hosting,
// the downside of using a sandboxed iframe is that the browers are overly
// restrictive in what you are allowed to do with the generated URL.
/**
* Get the current CSS style for a DOMElement.
* @param {HTMLElement} element The element to get the current style of.
* @return {string} The CSS style encoded as a string.
*/
export function computedStyle(element: HTMLElement | null): string {
if (!element) {
return "";
}
const style = window.getComputedStyle(element, null);
let cssText = style.cssText;
// noinspection EqualityComparisonWithCoercionJS
if (cssText == "") {
// Firefox doesn't implement ".cssText" for computed styles.
// https://bugzilla.mozilla.org/show_bug.cgi?id=137687
2022-11-07 13:45:34 +00:00
for (const rule of style) {
cssText += rule + ":";
cssText += style.getPropertyValue(rule) + ";";
}
}
return cssText;
}
2021-07-16 10:57:14 -06:00
interface IProps extends IBodyProps {
/* whether or not to show the default placeholder for the file. Defaults to true. */
showGenericPlaceholder?: boolean;
}
2021-03-04 20:07:48 -07:00
interface IState {
decryptedBlob?: Blob;
}
export default class MFileBody extends React.Component<IProps, IState> {
public static contextType = RoomContext;
2024-12-02 09:39:36 +00:00
declare public context: React.ContextType<typeof RoomContext>;
2024-08-01 13:01:05 +01:00
public state: IState = {};
private iframe = createRef<HTMLIFrameElement>();
private dummyLink = createRef<HTMLAnchorElement>();
private userDidClick = false;
private fileDownloader: FileDownloader = new FileDownloader(() => this.iframe.current);
2021-07-21 11:35:27 +05:30
private getContentUrl(): string | null {
2021-06-09 15:23:47 +05:30
if (this.props.forExport) return null;
const media = mediaFromContent(this.props.mxEvent.getContent());
return media.srcHttp;
2020-08-29 12:14:16 +01:00
}
private get content(): MediaEventContent {
return this.props.mxEvent.getContent<MediaEventContent>();
2021-07-29 15:36:50 -06:00
}
private get fileName(): string {
return this.props.mediaEventHelper?.fileName || _t("common|attachment");
2021-07-29 15:36:50 -06:00
}
private get linkText(): string {
return downloadLabelForFile(this.content, true);
2021-07-29 15:36:50 -06:00
}
private downloadFile(fileName: string, text: string): void {
if (!this.state.decryptedBlob) return;
2021-07-29 15:36:50 -06:00
this.fileDownloader.download({
blob: this.state.decryptedBlob,
name: fileName,
autoDownload: this.userDidClick,
opts: {
imgSrc: DOWNLOAD_ICON_URL,
imgStyle: null,
style: computedStyle(this.dummyLink.current),
textContent: text,
},
2021-07-29 15:36:50 -06:00
});
}
2016-11-04 14:00:26 +00:00
2021-07-29 15:36:50 -06:00
private decryptFile = async (): Promise<void> => {
if (this.state.decryptedBlob) {
return;
}
try {
this.userDidClick = true;
this.setState({
2023-07-07 13:37:26 +01:00
decryptedBlob: await this.props.mediaEventHelper!.sourceBlob.value,
2021-07-29 15:36:50 -06:00
});
} catch (err) {
2021-10-15 16:31:29 +02:00
logger.warn("Unable to decrypt attachment: ", err);
2022-06-14 17:51:51 +01:00
Modal.createDialog(ErrorDialog, {
title: _t("common|error"),
description: _t("timeline|m.file|error_decrypting"),
2021-07-29 15:36:50 -06:00
});
}
};
private onPlaceholderClick = async (): Promise<void> => {
2021-07-29 15:36:50 -06:00
const mediaHelper = this.props.mediaEventHelper;
if (mediaHelper?.media.isEncrypted) {
2021-07-29 15:36:50 -06:00
await this.decryptFile();
this.downloadFile(this.fileName, this.linkText);
2021-07-29 15:36:50 -06:00
} else {
// As a button we're missing the `download` attribute for styling reasons, so
// download with the file downloader.
this.fileDownloader.download({
2023-07-07 13:37:26 +01:00
blob: await mediaHelper!.sourceBlob.value,
2021-07-29 15:36:50 -06:00
name: this.fileName,
});
}
};
public render(): React.ReactNode {
const isEncrypted = this.props.mediaEventHelper?.media.isEncrypted;
const contentUrl = this.getContentUrl();
const contentFileSize = this.content.info ? this.content.info.size : null;
const fileType = this.content.info?.mimetype ?? "application/octet-stream";
// defaultProps breaks types on IBodyProps, so instead define the default here.
const showGenericPlaceholder = this.props.showGenericPlaceholder ?? true;
let showDownloadLink =
!showGenericPlaceholder ||
(this.context.timelineRenderingType !== TimelineRenderingType.Room &&
this.context.timelineRenderingType !== TimelineRenderingType.Search &&
this.context.timelineRenderingType !== TimelineRenderingType.Pinned);
2021-07-29 15:36:50 -06:00
let placeholder: React.ReactNode = null;
if (showGenericPlaceholder) {
2021-03-04 20:07:48 -07:00
placeholder = (
2021-07-29 15:36:50 -06:00
<AccessibleButton className="mx_MediaBody mx_MFileBody_info" onClick={this.onPlaceholderClick}>
2021-08-13 23:44:07 +05:30
<span className="mx_MFileBody_info_icon" />
<TextWithTooltip tooltip={presentableTextForFile(this.content, _t("common|attachment"), true)}>
2021-07-29 15:55:45 -06:00
<span className="mx_MFileBody_info_filename">
{presentableTextForFile(this.content, _t("common|attachment"), true, true)}
2021-07-29 15:55:45 -06:00
</span>
2021-07-29 15:49:23 -06:00
</TextWithTooltip>
2021-07-29 15:36:50 -06:00
</AccessibleButton>
2021-03-04 20:07:48 -07:00
);
showDownloadLink = false;
2021-03-04 20:07:48 -07:00
}
2021-06-09 15:23:47 +05:30
if (this.props.forExport) {
2021-06-29 12:54:44 +05:30
const content = this.props.mxEvent.getContent();
2021-08-14 00:14:57 +05:30
// During export, the content url will point to the MSC, which will later point to a local url
2021-05-31 23:50:55 +05:30
return (
<span className="mx_MFileBody">
2021-06-29 12:54:44 +05:30
<a href={content.file?.url || content.url}>{placeholder}</a>
2021-05-31 23:50:55 +05:30
</span>
);
2021-08-13 08:30:50 +05:30
}
if (this.context.timelineRenderingType === TimelineRenderingType.Thread) {
showDownloadLink = false;
}
2021-08-13 08:30:50 +05:30
if (isEncrypted) {
if (!this.state.decryptedBlob) {
// Need to decrypt the attachment
// Wait for the user to click on the link before downloading
// and decrypting the attachment.
2021-08-13 08:30:50 +05:30
// This button should actually Download because usercontent/ will try to click itself
// but it is not guaranteed between various browsers' settings.
2021-07-21 11:35:27 +05:30
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
<Button size="sm" kind="secondary" Icon={DownloadIcon} onClick={this.decryptFile}>
{this.linkText}
</Button>
2021-08-13 08:30:50 +05:30
</div>
)}
</span>
);
}
const url = "usercontent/"; // XXX: this path should probably be passed from the skin
2021-08-13 08:30:50 +05:30
// If the attachment is encrypted then put the link inside an iframe.
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
2022-01-03 18:51:58 +01:00
<div aria-hidden style={{ display: "none" }}>
2021-08-13 08:30:50 +05:30
{/*
* Add dummy copy of the button
* We'll use it to learn how the download button
* would have been styled if it was rendered inline.
2017-10-11 17:56:17 +01:00
*/}
2022-01-07 10:40:53 +01:00
{/* this violates multiple eslint rules
so ignore it completely */}
<Button size="sm" kind="secondary" Icon={DownloadIcon} as="a" ref={this.dummyLink} />
2021-08-13 08:30:50 +05:30
</div>
{/*
TODO: Move iframe (and dummy link) into FileDownloader.
We currently have it set up this way because of styles applied to the iframe
itself which cannot be easily handled/overridden by the FileDownloader. In
future, the download link may disappear entirely at which point it could also
be suitable to just remove this bit of code.
*/}
<iframe
aria-hidden
title={presentableTextForFile(this.content, _t("common|attachment"), true, true)}
src={url}
onLoad={() => this.downloadFile(this.fileName, this.linkText)}
ref={this.iframe}
sandbox="allow-scripts allow-downloads"
/>
2021-08-13 08:30:50 +05:30
</div>
)}
</span>
);
} else if (contentUrl) {
const downloadProps: Pick<
AllHTMLAttributes<HTMLAnchorElement>,
"target" | "rel" | "href" | "onClick" | "download"
> = {
2021-08-13 08:30:50 +05:30
target: "_blank",
rel: "noreferrer noopener",
2021-08-13 08:30:50 +05:30
// We set the href regardless of whether or not we intercept the download
// because we don't really want to convert the file to a blob eagerly, and
// still want "open in new tab" and "save link as" to work.
href: contentUrl,
};
2021-08-13 08:30:50 +05:30
// Blobs can only have up to 500mb, so if the file reports as being too large then
// we won't try and convert it. Likewise, if the file size is unknown then we'll assume
// it is too big. There is the risk of the reported file size and the actual file size
// being different, however the user shouldn't normally run into this problem.
const fileTooBig = typeof contentFileSize === "number" ? contentFileSize > 524288000 : true;
2021-07-21 11:35:27 +05:30
2021-08-13 08:30:50 +05:30
if (["application/pdf"].includes(fileType) && !fileTooBig) {
2021-07-21 11:35:27 +05:30
// We want to force a download on this type, so use an onClick handler.
2021-08-13 08:30:50 +05:30
downloadProps["onClick"] = (e) => {
logger.log(`Downloading ${fileType} as blob (unencrypted)`);
2021-07-21 11:35:27 +05:30
2021-08-13 08:30:50 +05:30
// Avoid letting the <a> do its thing
e.preventDefault();
e.stopPropagation();
2021-07-21 11:35:27 +05:30
2021-08-13 08:30:50 +05:30
// Start a fetch for the download
// Based upon https://stackoverflow.com/a/49500465
2023-07-07 13:37:26 +01:00
this.props.mediaEventHelper?.sourceBlob.value.then((blob) => {
2021-08-13 08:30:50 +05:30
const blobUrl = URL.createObjectURL(blob);
2021-07-21 11:35:27 +05:30
2021-08-13 08:30:50 +05:30
// We have to create an anchor to download the file
const tempAnchor = document.createElement("a");
tempAnchor.download = this.fileName;
tempAnchor.href = blobUrl;
document.body.appendChild(tempAnchor); // for firefox: https://stackoverflow.com/a/32226068
tempAnchor.click();
tempAnchor.remove();
});
};
2021-07-21 11:35:27 +05:30
} else {
2021-08-13 08:30:50 +05:30
// Else we are hoping the browser will do the right thing
downloadProps["download"] = this.fileName;
2016-09-11 02:14:27 +01:00
}
2021-08-13 08:30:50 +05:30
return (
<span className="mx_MFileBody">
{placeholder}
{showDownloadLink && (
<div className="mx_MFileBody_download">
<Button size="sm" kind="secondary" Icon={DownloadIcon} as="a" {...downloadProps}>
{this.linkText}
</Button>
2021-08-13 08:30:50 +05:30
</div>
)}
</span>
);
} else {
return (
<span className="mx_MFileBody">
{placeholder}
{_t("timeline|m.file|error_invalid")}
2021-08-13 08:30:50 +05:30
</span>
);
}
2020-08-29 12:14:16 +01:00
}
}