2015-07-08 13:34:26 +00:00
|
|
|
/*
|
2024-09-09 13:57:16 +00:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2020-05-24 14:47:52 +00:00
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
2024-09-09 13:57:16 +00:00
|
|
|
Copyright 2019 New Vector Ltd
|
|
|
|
Copyright 2015, 2016 OpenMarket Ltd
|
2015-07-08 13:34:26 +00:00
|
|
|
|
2024-09-09 13:57:16 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
|
|
|
Please see LICENSE files in the repository root for full details.
|
2015-07-08 13:34:26 +00:00
|
|
|
*/
|
|
|
|
|
2023-05-09 09:52:07 +00:00
|
|
|
import {
|
2023-08-09 07:18:41 +00:00
|
|
|
MatrixClient,
|
2023-08-08 10:12:12 +00:00
|
|
|
MsgType,
|
2023-05-09 09:52:07 +00:00
|
|
|
HTTPError,
|
|
|
|
IEventRelation,
|
|
|
|
ISendEventResponse,
|
|
|
|
MatrixEvent,
|
|
|
|
UploadOpts,
|
|
|
|
UploadProgress,
|
2023-08-14 08:58:55 +00:00
|
|
|
THREAD_RELATION_TYPE,
|
2023-05-09 09:52:07 +00:00
|
|
|
} from "matrix-js-sdk/src/matrix";
|
2024-03-11 09:30:00 +00:00
|
|
|
import {
|
|
|
|
ImageInfo,
|
|
|
|
AudioInfo,
|
|
|
|
VideoInfo,
|
|
|
|
EncryptedFile,
|
|
|
|
MediaEventContent,
|
|
|
|
MediaEventInfo,
|
|
|
|
} from "matrix-js-sdk/src/types";
|
2023-08-08 10:12:12 +00:00
|
|
|
import encrypt from "matrix-encrypt-attachment";
|
|
|
|
import extractPngChunks from "png-chunks-extract";
|
|
|
|
import { logger } from "matrix-js-sdk/src/logger";
|
2022-10-12 17:59:07 +00:00
|
|
|
import { removeElement } from "matrix-js-sdk/src/utils";
|
2021-05-21 13:52:27 +00:00
|
|
|
|
2022-12-12 11:24:14 +00:00
|
|
|
import dis from "./dispatcher/dispatcher";
|
|
|
|
import { _t } from "./languageHandler";
|
|
|
|
import Modal from "./Modal";
|
2020-06-01 16:05:53 +00:00
|
|
|
import Spinner from "./components/views/elements/Spinner";
|
2020-06-03 01:07:46 +00:00
|
|
|
import { Action } from "./dispatcher/actions";
|
2021-03-05 20:20:50 +00:00
|
|
|
import {
|
|
|
|
UploadCanceledPayload,
|
|
|
|
UploadErrorPayload,
|
|
|
|
UploadFinishedPayload,
|
|
|
|
UploadProgressPayload,
|
|
|
|
UploadStartedPayload,
|
|
|
|
} from "./dispatcher/payloads/UploadPayload";
|
2022-10-12 17:59:07 +00:00
|
|
|
import { RoomUpload } from "./models/RoomUpload";
|
2021-09-08 17:26:54 +00:00
|
|
|
import SettingsStore from "./settings/SettingsStore";
|
|
|
|
import { decorateStartSendingTime, sendRoundTripMetric } from "./sendTimePerformanceMetrics";
|
2022-01-26 09:04:19 +00:00
|
|
|
import { TimelineRenderingType } from "./contexts/RoomContext";
|
2022-03-21 12:03:59 +00:00
|
|
|
import { addReplyToMessageContent } from "./utils/Reply";
|
2022-03-02 23:33:40 +00:00
|
|
|
import ErrorDialog from "./components/views/dialogs/ErrorDialog";
|
|
|
|
import UploadFailureDialog from "./components/views/dialogs/UploadFailureDialog";
|
|
|
|
import UploadConfirmDialog from "./components/views/dialogs/UploadConfirmDialog";
|
2022-03-24 21:13:11 +00:00
|
|
|
import { createThumbnail } from "./utils/image-media";
|
2023-03-23 11:47:40 +00:00
|
|
|
import { attachMentions, attachRelation } from "./components/views/rooms/SendMessageComposer";
|
2022-07-13 05:56:36 +00:00
|
|
|
import { doMaybeLocalRoomAction } from "./utils/local-room";
|
2022-10-19 12:07:03 +00:00
|
|
|
import { SdkContextClass } from "./contexts/SDKContext";
|
2016-11-15 11:22:39 +00:00
|
|
|
|
2019-01-14 17:10:20 +00:00
|
|
|
// scraped out of a macOS hidpi (5660ppm) screenshot png
|
|
|
|
// 5669 px (x-axis) , 5669 px (y-axis) , per metre
|
|
|
|
const PHYS_HIDPI = [0x00, 0x00, 0x16, 0x25, 0x00, 0x00, 0x16, 0x25, 0x01];
|
2016-11-15 11:22:39 +00:00
|
|
|
|
2019-04-08 18:07:17 +00:00
|
|
|
export class UploadCanceledError extends Error {}
|
2016-11-15 11:22:39 +00:00
|
|
|
|
2020-05-24 14:47:52 +00:00
|
|
|
interface IMediaConfig {
|
|
|
|
"m.upload.size"?: number;
|
|
|
|
}
|
|
|
|
|
2016-11-15 11:22:39 +00:00
|
|
|
/**
|
|
|
|
* Load a file into a newly created image element.
|
|
|
|
*
|
2019-04-01 15:42:41 +00:00
|
|
|
* @param {File} imageFile The file to load in an image element.
|
2016-11-15 11:22:39 +00:00
|
|
|
* @return {Promise} A promise that resolves with the html image element.
|
|
|
|
*/
|
2023-01-12 13:25:14 +00:00
|
|
|
async function loadImageElement(imageFile: File): Promise<{
|
|
|
|
width: number;
|
|
|
|
height: number;
|
|
|
|
img: HTMLImageElement;
|
|
|
|
}> {
|
2015-07-08 13:34:26 +00:00
|
|
|
// Load the file into an html element
|
2022-10-12 17:59:07 +00:00
|
|
|
const img = new Image();
|
2017-10-19 16:16:52 +00:00
|
|
|
const objectUrl = URL.createObjectURL(imageFile);
|
2019-04-09 10:32:44 +00:00
|
|
|
const imgPromise = new Promise((resolve, reject) => {
|
2023-01-12 13:25:14 +00:00
|
|
|
img.onload = function (): void {
|
2019-04-09 10:32:44 +00:00
|
|
|
URL.revokeObjectURL(objectUrl);
|
|
|
|
resolve(img);
|
|
|
|
};
|
2023-01-12 13:25:14 +00:00
|
|
|
img.onerror = function (e): void {
|
2019-04-09 10:32:44 +00:00
|
|
|
reject(e);
|
|
|
|
};
|
|
|
|
});
|
2017-10-19 16:16:52 +00:00
|
|
|
img.src = objectUrl;
|
2015-07-08 13:34:26 +00:00
|
|
|
|
2019-01-14 17:10:20 +00:00
|
|
|
// check for hi-dpi PNGs and fudge display resolution as needed.
|
|
|
|
// this is mainly needed for macOS screencaps
|
2023-02-16 17:21:44 +00:00
|
|
|
let parsePromise = Promise.resolve(false);
|
2019-01-14 17:10:20 +00:00
|
|
|
if (imageFile.type === "image/png") {
|
|
|
|
// in practice macOS happens to order the chunks so they fall in
|
|
|
|
// the first 0x1000 bytes (thanks to a massive ICC header).
|
|
|
|
// Thus we could slice the file down to only sniff the first 0x1000
|
2019-04-09 10:18:06 +00:00
|
|
|
// bytes (but this makes extractPngChunks choke on the corrupt file)
|
2019-01-14 17:10:20 +00:00
|
|
|
const headers = imageFile; //.slice(0, 0x1000);
|
2023-03-07 15:48:23 +00:00
|
|
|
parsePromise = readFileAsArrayBuffer(headers)
|
|
|
|
.then((arrayBuffer) => {
|
|
|
|
const buffer = new Uint8Array(arrayBuffer);
|
|
|
|
const chunks = extractPngChunks(buffer);
|
|
|
|
for (const chunk of chunks) {
|
|
|
|
if (chunk.name === "pHYs") {
|
|
|
|
if (chunk.data.byteLength !== PHYS_HIDPI.length) return false;
|
|
|
|
return chunk.data.every((val, i) => val === PHYS_HIDPI[i]);
|
|
|
|
}
|
2019-01-14 17:10:20 +00:00
|
|
|
}
|
2023-03-07 15:48:23 +00:00
|
|
|
return false;
|
|
|
|
})
|
|
|
|
.catch((e) => {
|
|
|
|
console.error("Failed to parse PNG", e);
|
|
|
|
return false;
|
|
|
|
});
|
2019-01-14 17:10:20 +00:00
|
|
|
}
|
|
|
|
|
2019-04-09 10:32:44 +00:00
|
|
|
const [hidpi] = await Promise.all([parsePromise, imgPromise]);
|
2022-12-12 11:24:14 +00:00
|
|
|
const width = hidpi ? img.width >> 1 : img.width;
|
|
|
|
const height = hidpi ? img.height >> 1 : img.height;
|
2021-06-29 12:11:58 +00:00
|
|
|
return { width, height, img };
|
2015-07-08 13:34:26 +00:00
|
|
|
}
|
|
|
|
|
2021-08-05 12:04:20 +00:00
|
|
|
// Minimum size for image files before we generate a thumbnail for them.
|
|
|
|
const IMAGE_SIZE_THRESHOLD_THUMBNAIL = 1 << 15; // 32KB
|
|
|
|
// Minimum size improvement for image thumbnails, if both are not met then don't bother uploading thumbnail.
|
|
|
|
const IMAGE_THUMBNAIL_MIN_REDUCTION_SIZE = 1 << 16; // 1MB
|
|
|
|
const IMAGE_THUMBNAIL_MIN_REDUCTION_PERCENT = 0.1; // 10%
|
|
|
|
// We don't apply these thresholds to video thumbnails as a poster image is always useful
|
|
|
|
// and videos tend to be much larger.
|
|
|
|
|
2022-05-24 08:05:29 +00:00
|
|
|
// Image mime types for which to always include a thumbnail for even if it is larger than the input for wider support.
|
|
|
|
const ALWAYS_INCLUDE_THUMBNAIL = ["image/avif", "image/webp"];
|
|
|
|
|
2016-11-15 11:22:39 +00:00
|
|
|
/**
|
|
|
|
* Read the metadata for an image file and create and upload a thumbnail of the image.
|
|
|
|
*
|
|
|
|
* @param {MatrixClient} matrixClient A matrixClient to upload the thumbnail with.
|
|
|
|
* @param {String} roomId The ID of the room the image will be uploaded in.
|
2019-04-01 15:42:41 +00:00
|
|
|
* @param {File} imageFile The image to read and thumbnail.
|
2016-11-15 11:22:39 +00:00
|
|
|
* @return {Promise} A promise that resolves with the attachment info.
|
|
|
|
*/
|
2023-07-17 12:07:58 +00:00
|
|
|
async function infoForImageFile(matrixClient: MatrixClient, roomId: string, imageFile: File): Promise<ImageInfo> {
|
2017-10-11 16:56:17 +00:00
|
|
|
let thumbnailType = "image/png";
|
2020-05-24 14:47:52 +00:00
|
|
|
if (imageFile.type === "image/jpeg") {
|
2016-11-15 11:22:39 +00:00
|
|
|
thumbnailType = "image/jpeg";
|
|
|
|
}
|
|
|
|
|
2021-08-05 12:04:20 +00:00
|
|
|
const imageElement = await loadImageElement(imageFile);
|
|
|
|
|
|
|
|
const result = await createThumbnail(imageElement.img, imageElement.width, imageElement.height, thumbnailType);
|
|
|
|
const imageInfo = result.info;
|
|
|
|
|
2022-03-29 06:03:41 +00:00
|
|
|
// For lesser supported image types, always include the thumbnail even if it is larger
|
2022-05-24 08:05:29 +00:00
|
|
|
if (!ALWAYS_INCLUDE_THUMBNAIL.includes(imageFile.type)) {
|
2022-03-29 06:03:41 +00:00
|
|
|
// we do all sizing checks here because we still rely on thumbnail generation for making a blurhash from.
|
2023-03-07 13:19:18 +00:00
|
|
|
const sizeDifference = imageFile.size - imageInfo.thumbnail_info!.size;
|
2022-03-29 06:03:41 +00:00
|
|
|
if (
|
|
|
|
// image is small enough already
|
|
|
|
imageFile.size <= IMAGE_SIZE_THRESHOLD_THUMBNAIL ||
|
|
|
|
// thumbnail is not sufficiently smaller than original
|
|
|
|
(sizeDifference <= IMAGE_THUMBNAIL_MIN_REDUCTION_SIZE &&
|
2022-12-12 11:24:14 +00:00
|
|
|
sizeDifference <= imageFile.size * IMAGE_THUMBNAIL_MIN_REDUCTION_PERCENT)
|
2022-03-29 06:03:41 +00:00
|
|
|
) {
|
|
|
|
delete imageInfo["thumbnail_info"];
|
|
|
|
return imageInfo;
|
|
|
|
}
|
2021-08-05 12:04:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const uploadResult = await uploadFile(matrixClient, roomId, result.thumbnail);
|
|
|
|
|
|
|
|
imageInfo["thumbnail_url"] = uploadResult.url;
|
|
|
|
imageInfo["thumbnail_file"] = uploadResult.file;
|
|
|
|
return imageInfo;
|
2016-11-15 11:22:39 +00:00
|
|
|
}
|
|
|
|
|
2023-07-17 12:07:58 +00:00
|
|
|
/**
|
|
|
|
* Load a file into a newly created audio element and load the metadata
|
|
|
|
*
|
|
|
|
* @param {File} audioFile The file to load in an audio element.
|
|
|
|
* @return {Promise} A promise that resolves with the audio element.
|
|
|
|
*/
|
|
|
|
function loadAudioElement(audioFile: File): Promise<HTMLAudioElement> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
// Load the file into a html element
|
|
|
|
const audio = document.createElement("audio");
|
|
|
|
audio.preload = "metadata";
|
|
|
|
audio.muted = true;
|
|
|
|
|
|
|
|
const reader = new FileReader();
|
|
|
|
|
|
|
|
reader.onload = function (ev): void {
|
|
|
|
audio.onloadedmetadata = async function (): Promise<void> {
|
|
|
|
resolve(audio);
|
|
|
|
};
|
|
|
|
audio.onerror = function (e): void {
|
|
|
|
reject(e);
|
|
|
|
};
|
|
|
|
|
|
|
|
audio.src = ev.target?.result as string;
|
|
|
|
};
|
|
|
|
reader.onerror = function (e): void {
|
|
|
|
reject(e);
|
|
|
|
};
|
|
|
|
reader.readAsDataURL(audioFile);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read the metadata for an audio file.
|
|
|
|
*
|
|
|
|
* @param {File} audioFile The audio to read.
|
|
|
|
* @return {Promise} A promise that resolves with the attachment info.
|
|
|
|
*/
|
|
|
|
async function infoForAudioFile(audioFile: File): Promise<AudioInfo> {
|
|
|
|
const audio = await loadAudioElement(audioFile);
|
|
|
|
return { duration: Math.ceil(audio.duration * 1000) };
|
|
|
|
}
|
|
|
|
|
2016-11-15 11:22:39 +00:00
|
|
|
/**
|
2021-05-21 20:04:36 +00:00
|
|
|
* Load a file into a newly created video element and pull some strings
|
|
|
|
* in an attempt to guarantee the first frame will be showing.
|
2016-11-15 11:22:39 +00:00
|
|
|
*
|
2023-07-17 12:07:58 +00:00
|
|
|
* @param {File} videoFile The file to load in a video element.
|
|
|
|
* @return {Promise} A promise that resolves with the video element.
|
2016-11-15 11:22:39 +00:00
|
|
|
*/
|
2022-05-24 08:05:29 +00:00
|
|
|
function loadVideoElement(videoFile: File): Promise<HTMLVideoElement> {
|
2019-11-12 11:40:38 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2023-07-17 12:07:58 +00:00
|
|
|
// Load the file into a html element
|
2019-11-12 11:40:38 +00:00
|
|
|
const video = document.createElement("video");
|
2021-05-21 20:04:36 +00:00
|
|
|
video.preload = "metadata";
|
|
|
|
video.playsInline = true;
|
|
|
|
video.muted = true;
|
2019-11-12 11:40:38 +00:00
|
|
|
|
|
|
|
const reader = new FileReader();
|
|
|
|
|
2023-01-12 13:25:14 +00:00
|
|
|
reader.onload = function (ev): void {
|
2019-11-12 11:40:38 +00:00
|
|
|
// Wait until we have enough data to thumbnail the first frame.
|
2023-01-12 13:25:14 +00:00
|
|
|
video.onloadeddata = async function (): Promise<void> {
|
2019-11-12 11:40:38 +00:00
|
|
|
resolve(video);
|
2021-05-21 20:04:36 +00:00
|
|
|
video.pause();
|
2019-11-12 11:40:38 +00:00
|
|
|
};
|
2023-01-12 13:25:14 +00:00
|
|
|
video.onerror = function (e): void {
|
2019-11-12 11:40:38 +00:00
|
|
|
reject(e);
|
|
|
|
};
|
2021-05-21 20:04:36 +00:00
|
|
|
|
2023-02-16 17:21:44 +00:00
|
|
|
let dataUrl = ev.target?.result as string;
|
2022-03-22 12:23:25 +00:00
|
|
|
// Chrome chokes on quicktime but likes mp4, and `file.type` is
|
|
|
|
// read only, so do this horrible hack to unbreak quicktime
|
2023-02-16 17:21:44 +00:00
|
|
|
if (dataUrl?.startsWith("data:video/quicktime;")) {
|
2022-03-22 12:23:25 +00:00
|
|
|
dataUrl = dataUrl.replace("data:video/quicktime;", "data:video/mp4;");
|
|
|
|
}
|
|
|
|
|
|
|
|
video.src = dataUrl;
|
2021-05-21 20:04:36 +00:00
|
|
|
video.load();
|
|
|
|
video.play();
|
2016-07-19 15:05:15 +00:00
|
|
|
};
|
2023-01-12 13:25:14 +00:00
|
|
|
reader.onerror = function (e): void {
|
2019-11-12 11:40:38 +00:00
|
|
|
reject(e);
|
2016-07-19 15:05:15 +00:00
|
|
|
};
|
2019-11-12 11:40:38 +00:00
|
|
|
reader.readAsDataURL(videoFile);
|
|
|
|
});
|
2016-07-19 15:05:15 +00:00
|
|
|
}
|
|
|
|
|
2016-11-15 11:22:39 +00:00
|
|
|
/**
|
|
|
|
* Read the metadata for a video file and create and upload a thumbnail of the video.
|
|
|
|
*
|
|
|
|
* @param {MatrixClient} matrixClient A matrixClient to upload the thumbnail with.
|
|
|
|
* @param {String} roomId The ID of the room the video will be uploaded to.
|
2019-04-01 15:42:41 +00:00
|
|
|
* @param {File} videoFile The video to read and thumbnail.
|
2016-11-15 11:22:39 +00:00
|
|
|
* @return {Promise} A promise that resolves with the attachment info.
|
|
|
|
*/
|
2023-07-17 12:07:58 +00:00
|
|
|
function infoForVideoFile(matrixClient: MatrixClient, roomId: string, videoFile: File): Promise<VideoInfo> {
|
2016-11-15 11:22:39 +00:00
|
|
|
const thumbnailType = "image/jpeg";
|
|
|
|
|
2023-07-17 12:07:58 +00:00
|
|
|
const videoInfo: VideoInfo = {};
|
2022-12-12 11:24:14 +00:00
|
|
|
return loadVideoElement(videoFile)
|
|
|
|
.then((video) => {
|
2023-07-17 12:07:58 +00:00
|
|
|
videoInfo.duration = Math.ceil(video.duration * 1000);
|
2022-12-12 11:24:14 +00:00
|
|
|
return createThumbnail(video, video.videoWidth, video.videoHeight, thumbnailType);
|
|
|
|
})
|
|
|
|
.then((result) => {
|
2023-07-17 12:07:58 +00:00
|
|
|
Object.assign(videoInfo, result.info);
|
2022-12-12 11:24:14 +00:00
|
|
|
return uploadFile(matrixClient, roomId, result.thumbnail);
|
|
|
|
})
|
|
|
|
.then((result) => {
|
|
|
|
videoInfo.thumbnail_url = result.url;
|
|
|
|
videoInfo.thumbnail_file = result.file;
|
|
|
|
return videoInfo;
|
|
|
|
});
|
2016-11-15 11:22:39 +00:00
|
|
|
}
|
|
|
|
|
2016-11-08 11:42:20 +00:00
|
|
|
/**
|
|
|
|
* Read the file as an ArrayBuffer.
|
2019-04-01 15:42:41 +00:00
|
|
|
* @param {File} file The file to read
|
2016-11-08 11:42:20 +00:00
|
|
|
* @return {Promise} A promise that resolves with an ArrayBuffer when the file
|
|
|
|
* is read.
|
|
|
|
*/
|
2020-05-24 14:47:52 +00:00
|
|
|
function readFileAsArrayBuffer(file: File | Blob): Promise<ArrayBuffer> {
|
2019-11-12 11:40:38 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const reader = new FileReader();
|
2023-01-12 13:25:14 +00:00
|
|
|
reader.onload = function (e): void {
|
2023-02-16 17:21:44 +00:00
|
|
|
resolve(e.target?.result as ArrayBuffer);
|
2019-11-12 11:40:38 +00:00
|
|
|
};
|
2023-01-12 13:25:14 +00:00
|
|
|
reader.onerror = function (e): void {
|
2019-11-12 11:40:38 +00:00
|
|
|
reject(e);
|
|
|
|
};
|
|
|
|
reader.readAsArrayBuffer(file);
|
|
|
|
});
|
2016-11-08 11:42:20 +00:00
|
|
|
}
|
|
|
|
|
2016-11-15 11:22:39 +00:00
|
|
|
/**
|
|
|
|
* Upload the file to the content repository.
|
|
|
|
* If the room is encrypted then encrypt the file before uploading.
|
|
|
|
*
|
|
|
|
* @param {MatrixClient} matrixClient The matrix client to upload the file with.
|
|
|
|
* @param {String} roomId The ID of the room being uploaded to.
|
|
|
|
* @param {File} file The file to upload.
|
2017-07-14 16:01:03 +00:00
|
|
|
* @param {Function?} progressHandler optional callback to be called when a chunk of
|
|
|
|
* data is uploaded.
|
2022-10-12 17:59:07 +00:00
|
|
|
* @param {AbortController?} controller optional abortController to use for this upload.
|
2016-11-15 11:22:39 +00:00
|
|
|
* @return {Promise} A promise that resolves with an object.
|
|
|
|
* 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.
|
|
|
|
*/
|
2022-10-12 17:59:07 +00:00
|
|
|
export async function uploadFile(
|
2021-06-02 04:21:04 +00:00
|
|
|
matrixClient: MatrixClient,
|
|
|
|
roomId: string,
|
|
|
|
file: File | Blob,
|
2022-10-12 17:59:07 +00:00
|
|
|
progressHandler?: UploadOpts["progressHandler"],
|
|
|
|
controller?: AbortController,
|
2023-07-17 12:07:58 +00:00
|
|
|
): Promise<{ url?: string; file?: EncryptedFile }> {
|
2022-10-12 17:59:07 +00:00
|
|
|
const abortController = controller ?? new AbortController();
|
|
|
|
|
|
|
|
// If the room is encrypted then encrypt the file before uploading it.
|
2024-10-18 14:44:56 +00:00
|
|
|
if (await matrixClient.getCrypto()?.isEncryptionEnabledInRoom(roomId)) {
|
2016-11-15 11:22:39 +00:00
|
|
|
// First read the file into memory.
|
2022-10-12 17:59:07 +00:00
|
|
|
const data = await readFileAsArrayBuffer(file);
|
|
|
|
if (abortController.signal.aborted) throw new UploadCanceledError();
|
2021-10-28 08:40:38 +00:00
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
// Then encrypt the file.
|
|
|
|
const encryptResult = await encrypt.encryptAttachment(data);
|
|
|
|
if (abortController.signal.aborted) throw new UploadCanceledError();
|
|
|
|
|
|
|
|
// Pass the encrypted data as a Blob to the uploader.
|
|
|
|
const blob = new Blob([encryptResult.data]);
|
|
|
|
|
|
|
|
const { content_uri: url } = await matrixClient.uploadContent(blob, {
|
|
|
|
progressHandler,
|
|
|
|
abortController,
|
|
|
|
includeFilename: false,
|
2022-12-30 08:34:38 +00:00
|
|
|
type: "application/octet-stream",
|
2022-10-12 17:59:07 +00:00
|
|
|
});
|
|
|
|
if (abortController.signal.aborted) throw new UploadCanceledError();
|
|
|
|
|
|
|
|
// If the attachment is encrypted then bundle the URL along with the information
|
|
|
|
// needed to decrypt the attachment and add it under a file key.
|
|
|
|
return {
|
|
|
|
file: {
|
|
|
|
...encryptResult.info,
|
|
|
|
url,
|
2023-07-17 12:07:58 +00:00
|
|
|
} as EncryptedFile,
|
2019-04-08 16:53:39 +00:00
|
|
|
};
|
2016-11-15 11:22:39 +00:00
|
|
|
} else {
|
2022-10-12 17:59:07 +00:00
|
|
|
const { content_uri: url } = await matrixClient.uploadContent(file, { progressHandler, abortController });
|
|
|
|
if (abortController.signal.aborted) throw new UploadCanceledError();
|
|
|
|
// If the attachment isn't encrypted then include the URL directly.
|
|
|
|
return { url };
|
2016-11-15 11:22:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-01 15:42:41 +00:00
|
|
|
export default class ContentMessages {
|
2022-10-12 17:59:07 +00:00
|
|
|
private inprogress: RoomUpload[] = [];
|
2023-02-16 17:21:44 +00:00
|
|
|
private mediaConfig: IMediaConfig | null = null;
|
2019-04-01 15:42:41 +00:00
|
|
|
|
2022-01-26 09:04:19 +00:00
|
|
|
public sendStickerContentToRoom(
|
2021-12-03 08:22:13 +00:00
|
|
|
url: string,
|
|
|
|
roomId: string,
|
|
|
|
threadId: string | null,
|
2024-03-25 12:21:02 +00:00
|
|
|
info: ImageInfo,
|
2021-12-03 08:22:13 +00:00
|
|
|
text: string,
|
|
|
|
matrixClient: MatrixClient,
|
2022-01-26 09:04:19 +00:00
|
|
|
): Promise<ISendEventResponse> {
|
2022-07-13 05:56:36 +00:00
|
|
|
return doMaybeLocalRoomAction(
|
|
|
|
roomId,
|
|
|
|
(actualRoomId: string) => matrixClient.sendStickerMessage(actualRoomId, threadId, url, info, text),
|
|
|
|
matrixClient,
|
|
|
|
).catch((e) => {
|
2021-10-15 14:31:29 +00:00
|
|
|
logger.warn(`Failed to send content with URL ${url} to room ${roomId}`, e);
|
2018-03-29 15:24:03 +00:00
|
|
|
throw e;
|
2018-03-29 15:23:20 +00:00
|
|
|
});
|
2018-01-04 09:53:26 +00:00
|
|
|
}
|
|
|
|
|
2022-01-26 09:04:19 +00:00
|
|
|
public getUploadLimit(): number | null {
|
2024-10-16 16:38:22 +00:00
|
|
|
return this.mediaConfig?.["m.upload.size"] ?? null;
|
2019-04-01 15:42:41 +00:00
|
|
|
}
|
|
|
|
|
2022-01-26 09:04:19 +00:00
|
|
|
public async sendContentListToRoom(
|
2021-11-03 08:43:24 +00:00
|
|
|
files: File[],
|
|
|
|
roomId: string,
|
2022-02-22 11:14:56 +00:00
|
|
|
relation: IEventRelation | undefined,
|
2021-11-03 08:43:24 +00:00
|
|
|
matrixClient: MatrixClient,
|
2022-01-26 09:04:19 +00:00
|
|
|
context = TimelineRenderingType.Room,
|
|
|
|
): Promise<void> {
|
2019-04-01 15:42:41 +00:00
|
|
|
if (matrixClient.isGuest()) {
|
2022-12-12 11:24:14 +00:00
|
|
|
dis.dispatch({ action: "require_registration" });
|
2019-04-01 15:42:41 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-19 12:07:03 +00:00
|
|
|
const replyToEvent = SdkContextClass.instance.roomViewStore.getQuotingEvent();
|
2022-12-12 11:24:14 +00:00
|
|
|
if (!this.mediaConfig) {
|
|
|
|
// hot-path optimization to not flash a spinner if we don't need to
|
2023-02-03 15:27:47 +00:00
|
|
|
const modal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
|
2023-03-16 12:24:22 +00:00
|
|
|
await Promise.race([this.ensureMediaConfigFetched(matrixClient), modal.finished]);
|
|
|
|
if (!this.mediaConfig) {
|
|
|
|
// User cancelled by clicking away on the spinner
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
modal.close();
|
|
|
|
}
|
2020-06-01 14:00:55 +00:00
|
|
|
}
|
2019-04-01 15:42:41 +00:00
|
|
|
|
2023-02-16 17:21:44 +00:00
|
|
|
const tooBigFiles: File[] = [];
|
|
|
|
const okFiles: File[] = [];
|
2019-04-01 15:42:41 +00:00
|
|
|
|
2022-05-03 21:04:37 +00:00
|
|
|
for (const file of files) {
|
|
|
|
if (this.isFileSizeAcceptable(file)) {
|
|
|
|
okFiles.push(file);
|
2019-04-01 15:42:41 +00:00
|
|
|
} else {
|
2022-05-03 21:04:37 +00:00
|
|
|
tooBigFiles.push(file);
|
2019-04-01 15:42:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (tooBigFiles.length > 0) {
|
2023-02-28 10:31:48 +00:00
|
|
|
const { finished } = Modal.createDialog(UploadFailureDialog, {
|
2020-05-24 14:47:52 +00:00
|
|
|
badFiles: tooBigFiles,
|
|
|
|
totalFiles: files.length,
|
|
|
|
contentMessages: this,
|
2019-04-01 15:42:41 +00:00
|
|
|
});
|
2020-07-12 23:19:15 +00:00
|
|
|
const [shouldContinue] = await finished;
|
2019-04-01 15:42:41 +00:00
|
|
|
if (!shouldContinue) return;
|
|
|
|
}
|
|
|
|
|
2019-06-16 10:43:13 +00:00
|
|
|
let uploadAll = false;
|
2019-12-27 13:59:57 +00:00
|
|
|
// Promise to complete before sending next file into room, used for synchronisation of file-sending
|
|
|
|
// to match the order the files were specified in
|
2021-06-02 04:21:04 +00:00
|
|
|
let promBefore: Promise<any> = Promise.resolve();
|
2019-04-01 15:42:41 +00:00
|
|
|
for (let i = 0; i < okFiles.length; ++i) {
|
|
|
|
const file = okFiles[i];
|
2022-07-13 05:56:36 +00:00
|
|
|
const loopPromiseBefore = promBefore;
|
|
|
|
|
2019-06-16 10:43:13 +00:00
|
|
|
if (!uploadAll) {
|
2023-02-28 10:31:48 +00:00
|
|
|
const { finished } = Modal.createDialog(UploadConfirmDialog, {
|
2022-06-14 16:51:51 +00:00
|
|
|
file,
|
|
|
|
currentIndex: i,
|
|
|
|
totalFiles: okFiles.length,
|
|
|
|
});
|
2020-07-12 23:19:15 +00:00
|
|
|
const [shouldContinue, shouldUploadAll] = await finished;
|
2019-06-16 10:43:13 +00:00
|
|
|
if (!shouldContinue) break;
|
2020-05-24 14:47:52 +00:00
|
|
|
if (shouldUploadAll) {
|
|
|
|
uploadAll = true;
|
|
|
|
}
|
2019-06-16 10:43:13 +00:00
|
|
|
}
|
2021-11-24 08:40:15 +00:00
|
|
|
|
2023-05-23 15:24:12 +00:00
|
|
|
promBefore = doMaybeLocalRoomAction(
|
|
|
|
roomId,
|
|
|
|
(actualRoomId) =>
|
|
|
|
this.sendContentToRoom(
|
|
|
|
file,
|
|
|
|
actualRoomId,
|
|
|
|
relation,
|
|
|
|
matrixClient,
|
|
|
|
replyToEvent ?? undefined,
|
|
|
|
loopPromiseBefore,
|
|
|
|
),
|
|
|
|
matrixClient,
|
2022-07-13 05:56:36 +00:00
|
|
|
);
|
2022-03-21 12:03:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (replyToEvent) {
|
|
|
|
// Clear event being replied to
|
|
|
|
dis.dispatch({
|
|
|
|
action: "reply_to_event",
|
|
|
|
event: null,
|
|
|
|
context,
|
|
|
|
});
|
2020-05-24 15:00:57 +00:00
|
|
|
}
|
2022-01-26 09:04:19 +00:00
|
|
|
|
|
|
|
// Focus the correct composer
|
|
|
|
dis.dispatch({
|
|
|
|
action: Action.FocusSendMessageComposer,
|
|
|
|
context,
|
|
|
|
});
|
2020-05-24 15:00:57 +00:00
|
|
|
}
|
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
public getCurrentUploads(relation?: IEventRelation): RoomUpload[] {
|
2022-12-12 11:24:14 +00:00
|
|
|
return this.inprogress.filter((roomUpload) => {
|
2022-10-12 17:59:07 +00:00
|
|
|
const noRelation = !relation && !roomUpload.relation;
|
2022-12-12 11:24:14 +00:00
|
|
|
const matchingRelation =
|
|
|
|
relation &&
|
|
|
|
roomUpload.relation &&
|
|
|
|
relation.rel_type === roomUpload.relation.rel_type &&
|
|
|
|
relation.event_id === roomUpload.relation.event_id;
|
2021-11-03 08:43:24 +00:00
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
return (noRelation || matchingRelation) && !roomUpload.cancelled;
|
2021-11-03 08:43:24 +00:00
|
|
|
});
|
2020-05-24 15:00:57 +00:00
|
|
|
}
|
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
public cancelUpload(upload: RoomUpload): void {
|
|
|
|
upload.abort();
|
|
|
|
dis.dispatch<UploadCanceledPayload>({ action: Action.UploadCanceled, upload });
|
2019-04-01 15:42:41 +00:00
|
|
|
}
|
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
public async sendContentToRoom(
|
2021-11-03 08:43:24 +00:00
|
|
|
file: File,
|
|
|
|
roomId: string,
|
2022-02-22 11:14:56 +00:00
|
|
|
relation: IEventRelation | undefined,
|
2021-11-03 08:43:24 +00:00
|
|
|
matrixClient: MatrixClient,
|
2022-03-21 12:03:59 +00:00
|
|
|
replyToEvent: MatrixEvent | undefined,
|
2022-10-12 17:59:07 +00:00
|
|
|
promBefore?: Promise<any>,
|
2023-01-12 13:25:14 +00:00
|
|
|
): Promise<void> {
|
2023-08-23 09:25:33 +00:00
|
|
|
const fileName = file.name || _t("common|attachment");
|
2024-03-11 09:30:00 +00:00
|
|
|
const content: Omit<MediaEventContent, "info"> & { info: Partial<MediaEventInfo> } = {
|
2022-10-12 17:59:07 +00:00
|
|
|
body: fileName,
|
2015-12-02 18:16:16 +00:00
|
|
|
info: {
|
|
|
|
size: file.size,
|
2017-10-11 16:56:17 +00:00
|
|
|
},
|
2022-05-24 08:05:29 +00:00
|
|
|
msgtype: MsgType.File, // set more specifically later
|
2015-12-02 18:16:16 +00:00
|
|
|
};
|
|
|
|
|
2023-03-23 11:47:40 +00:00
|
|
|
// Attach mentions, which really only applies if there's a replyToEvent.
|
|
|
|
attachMentions(matrixClient.getSafeUserId(), content, null, replyToEvent);
|
2022-03-31 17:40:35 +00:00
|
|
|
attachRelation(content, relation);
|
2022-03-21 12:03:59 +00:00
|
|
|
if (replyToEvent) {
|
|
|
|
addReplyToMessageContent(content, replyToEvent, {
|
|
|
|
includeLegacyFallback: false,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-09-08 17:26:54 +00:00
|
|
|
if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
|
|
|
|
decorateStartSendingTime(content);
|
|
|
|
}
|
|
|
|
|
2015-12-02 18:16:16 +00:00
|
|
|
// if we have a mime type for the file, add it to the message metadata
|
|
|
|
if (file.type) {
|
|
|
|
content.info.mimetype = file.type;
|
|
|
|
}
|
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
const upload = new RoomUpload(roomId, fileName, relation, file.size);
|
|
|
|
this.inprogress.push(upload);
|
|
|
|
dis.dispatch<UploadStartedPayload>({ action: Action.UploadStarted, upload });
|
|
|
|
|
2023-01-12 13:25:14 +00:00
|
|
|
function onProgress(progress: UploadProgress): void {
|
2022-10-12 17:59:07 +00:00
|
|
|
upload.onProgress(progress);
|
|
|
|
dis.dispatch<UploadProgressPayload>({ action: Action.UploadProgress, upload });
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2022-12-12 11:24:14 +00:00
|
|
|
if (file.type.startsWith("image/")) {
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.Image;
|
2022-10-12 17:59:07 +00:00
|
|
|
try {
|
|
|
|
const imageInfo = await infoForImageFile(matrixClient, roomId, file);
|
2020-10-13 16:36:40 +00:00
|
|
|
Object.assign(content.info, imageInfo);
|
2022-10-12 17:59:07 +00:00
|
|
|
} catch (e) {
|
2023-05-09 09:52:07 +00:00
|
|
|
if (e instanceof HTTPError) {
|
|
|
|
// re-throw to main upload error handler
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
// Otherwise we failed to thumbnail, fall back to uploading an m.file
|
2021-10-15 14:30:53 +00:00
|
|
|
logger.error(e);
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.File;
|
2022-10-12 17:59:07 +00:00
|
|
|
}
|
2024-10-16 16:38:22 +00:00
|
|
|
} else if (file.type.startsWith("audio/")) {
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.Audio;
|
2023-07-17 12:07:58 +00:00
|
|
|
try {
|
|
|
|
const audioInfo = await infoForAudioFile(file);
|
|
|
|
Object.assign(content.info, audioInfo);
|
|
|
|
} catch (e) {
|
|
|
|
// Failed to process audio file, fall back to uploading an m.file
|
|
|
|
logger.error(e);
|
|
|
|
content.msgtype = MsgType.File;
|
|
|
|
}
|
2024-10-16 16:38:22 +00:00
|
|
|
} else if (file.type.startsWith("video/")) {
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.Video;
|
2022-10-12 17:59:07 +00:00
|
|
|
try {
|
|
|
|
const videoInfo = await infoForVideoFile(matrixClient, roomId, file);
|
2020-10-13 16:36:40 +00:00
|
|
|
Object.assign(content.info, videoInfo);
|
2022-10-12 17:59:07 +00:00
|
|
|
} catch (e) {
|
2022-05-24 08:05:29 +00:00
|
|
|
// Failed to thumbnail, fall back to uploading an m.file
|
|
|
|
logger.error(e);
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.File;
|
2022-10-12 17:59:07 +00:00
|
|
|
}
|
2019-11-12 11:40:38 +00:00
|
|
|
} else {
|
2021-10-28 08:40:38 +00:00
|
|
|
content.msgtype = MsgType.File;
|
2019-11-12 11:40:38 +00:00
|
|
|
}
|
2015-12-02 18:16:16 +00:00
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
if (upload.cancelled) throw new UploadCanceledError();
|
|
|
|
const result = await uploadFile(matrixClient, roomId, file, onProgress, upload.abortController);
|
|
|
|
content.file = result.file;
|
|
|
|
content.url = result.url;
|
2020-05-24 14:13:53 +00:00
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
if (upload.cancelled) throw new UploadCanceledError();
|
|
|
|
// Await previous message being sent into the room
|
|
|
|
if (promBefore) await promBefore;
|
2015-12-02 18:16:16 +00:00
|
|
|
|
2022-10-12 17:59:07 +00:00
|
|
|
if (upload.cancelled) throw new UploadCanceledError();
|
|
|
|
const threadId = relation?.rel_type === THREAD_RELATION_TYPE.name ? relation.event_id : null;
|
|
|
|
|
2024-03-25 12:48:48 +00:00
|
|
|
const response = await matrixClient.sendMessage(roomId, threadId ?? null, content as MediaEventContent);
|
2017-07-14 16:01:03 +00:00
|
|
|
|
2021-09-08 17:26:54 +00:00
|
|
|
if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
|
2022-10-12 17:59:07 +00:00
|
|
|
sendRoundTripMetric(matrixClient, roomId, response.event_id);
|
2021-09-08 17:26:54 +00:00
|
|
|
}
|
2022-10-12 17:59:07 +00:00
|
|
|
|
|
|
|
dis.dispatch<UploadFinishedPayload>({ action: Action.UploadFinished, upload });
|
2022-12-12 11:24:14 +00:00
|
|
|
dis.dispatch({ action: "message_sent" });
|
2022-10-12 17:59:07 +00:00
|
|
|
} catch (error) {
|
|
|
|
// 413: File was too big or upset the server in some way:
|
|
|
|
// clear the media size limit so we fetch it again next time we try to upload
|
2023-05-16 13:25:43 +00:00
|
|
|
if (error instanceof HTTPError && error.httpStatus === 413) {
|
2022-10-12 17:59:07 +00:00
|
|
|
this.mediaConfig = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!upload.cancelled) {
|
2023-09-22 15:39:40 +00:00
|
|
|
let desc = _t("upload_failed_generic", { fileName: upload.fileName });
|
2023-05-16 13:25:43 +00:00
|
|
|
if (error instanceof HTTPError && error.httpStatus === 413) {
|
2023-09-22 15:39:40 +00:00
|
|
|
desc = _t("upload_failed_size", {
|
2022-12-12 11:24:14 +00:00
|
|
|
fileName: upload.fileName,
|
|
|
|
});
|
2015-12-03 10:52:06 +00:00
|
|
|
}
|
2022-06-14 16:51:51 +00:00
|
|
|
Modal.createDialog(ErrorDialog, {
|
2023-09-22 15:39:40 +00:00
|
|
|
title: _t("upload_failed_title"),
|
2017-05-23 14:16:31 +00:00
|
|
|
description: desc,
|
2015-12-03 10:52:06 +00:00
|
|
|
});
|
2021-06-29 12:11:58 +00:00
|
|
|
dis.dispatch<UploadErrorPayload>({ action: Action.UploadFailed, upload, error });
|
2016-02-15 19:29:56 +00:00
|
|
|
}
|
2022-10-12 17:59:07 +00:00
|
|
|
} finally {
|
2022-12-12 11:24:14 +00:00
|
|
|
removeElement(this.inprogress, (e) => e.promise === upload.promise);
|
2022-10-12 17:59:07 +00:00
|
|
|
}
|
2015-07-08 13:34:26 +00:00
|
|
|
}
|
|
|
|
|
2023-01-12 13:25:14 +00:00
|
|
|
private isFileSizeAcceptable(file: File): boolean {
|
2024-10-16 16:38:22 +00:00
|
|
|
if (this.mediaConfig?.["m.upload.size"] !== undefined && file.size > this.mediaConfig["m.upload.size"]) {
|
2020-05-24 15:00:57 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
2015-12-02 18:16:16 +00:00
|
|
|
}
|
|
|
|
|
2022-05-24 08:05:29 +00:00
|
|
|
private ensureMediaConfigFetched(matrixClient: MatrixClient): Promise<void> {
|
2023-02-16 17:21:44 +00:00
|
|
|
if (this.mediaConfig !== null) return Promise.resolve();
|
2020-05-24 15:00:57 +00:00
|
|
|
|
2021-09-21 15:48:09 +00:00
|
|
|
logger.log("[Media Config] Fetching");
|
2022-12-12 11:24:14 +00:00
|
|
|
return matrixClient
|
|
|
|
.getMediaConfig()
|
|
|
|
.then((config) => {
|
|
|
|
logger.log("[Media Config] Fetched config:", config);
|
|
|
|
return config;
|
|
|
|
})
|
|
|
|
.catch(() => {
|
|
|
|
// Media repo can't or won't report limits, so provide an empty object (no limits).
|
|
|
|
logger.log("[Media Config] Could not fetch config, so not limiting uploads.");
|
|
|
|
return {};
|
|
|
|
})
|
|
|
|
.then((config) => {
|
|
|
|
this.mediaConfig = config;
|
|
|
|
});
|
2020-05-24 15:00:57 +00:00
|
|
|
}
|
|
|
|
|
2023-01-12 13:25:14 +00:00
|
|
|
public static sharedInstance(): ContentMessages {
|
2020-07-20 19:43:49 +00:00
|
|
|
if (window.mxContentMessages === undefined) {
|
|
|
|
window.mxContentMessages = new ContentMessages();
|
2015-12-02 18:16:16 +00:00
|
|
|
}
|
2020-07-20 19:43:49 +00:00
|
|
|
return window.mxContentMessages;
|
2015-12-02 18:16:16 +00:00
|
|
|
}
|
|
|
|
}
|