snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { clientCallbacks } from '@rocket.chat/ui-client';
import { Rooms } from '../../../stores';
import { getUser } from '../../user';
export const afterSendMessageCallback = async (message: IMessage, rid: string) => {
const user = getUser();
const room = Rooms.state.get(rid);
if (!room || !user) {
return;
}
const processedMessage = {
...message,
u: {
_id: user?._id,
username: user?.username,
name: user?.name || '',
},
};
await clientCallbacks.run('afterSaveMessage', processedMessage, { room, user });
};

View File

@@ -0,0 +1,35 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { MessageTypes } from '@rocket.chat/message-types';
import { dispatchToastMessage } from '../../toast';
import type { ChatAPI } from '../ChatAPI';
export const processMessageEditing = async (
chat: ChatAPI,
message: Pick<IMessage, '_id' | 't'> & Partial<Omit<IMessage, '_id' | 't'>>,
previewUrls?: string[],
): Promise<boolean> => {
const mid = chat.currentEditingMessage.getMID();
if (!mid) {
return false;
}
if (MessageTypes.isSystemMessage(message)) {
return false;
}
if (!message.msg && !message.attachments?.length && !message.content) {
return false;
}
try {
chat.composer?.clear();
await chat.data.updateMessage({ ...message, _id: mid }, previewUrls);
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
chat.currentEditingMessage.stop();
return true;
};

View File

@@ -0,0 +1,219 @@
import type { AtLeast, FileAttachmentProps, IE2EEMessage, IMessage, IUploadToConfirm } from '@rocket.chat/core-typings';
import { imperativeModal, GenericModal } from '@rocket.chat/ui-client';
import { t } from '../../../../app/utils/lib/i18n';
import { getFileExtension } from '../../../../lib/utils/getFileExtension';
import { sdk } from '../../SDKClient';
import { e2e } from '../../e2ee/rocketchat.e2e';
import type { E2ERoom } from '../../e2ee/rocketchat.e2e.room';
import { dispatchToastMessage } from '../../toast';
import type { ChatAPI, UploadsAPI } from '../ChatAPI';
import { isEncryptedUpload, type EncryptedUpload } from '../Upload';
const getHeightAndWidthFromDataUrl = (dataURL: string): Promise<{ height: number; width: number }> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
height: img.height,
width: img.width,
});
};
img.onerror = () => {
reject(new Error('Failed to load image for dimensions'));
};
img.src = dataURL;
});
};
const getAttachmentForFile = async (fileToUpload: EncryptedUpload): Promise<FileAttachmentProps> => {
const attachment: FileAttachmentProps = {
title: fileToUpload.file.name,
type: 'file',
title_link: fileToUpload.url,
title_link_download: true,
encryption: {
key: fileToUpload.encryptedFile.key,
iv: fileToUpload.encryptedFile.iv,
},
hashes: {
sha256: fileToUpload.encryptedFile.hash,
},
fileId: fileToUpload.id,
};
const fileType = fileToUpload.file.type.match(/^(image|audio|video)\/.+/)?.[1] as 'image' | 'audio' | 'video' | undefined;
if (!fileType) {
return {
...attachment,
size: fileToUpload.file.size,
format: getFileExtension(fileToUpload.file.name),
};
}
return {
...attachment,
[`${fileType}_url`]: fileToUpload.url,
[`${fileType}_type`]: fileToUpload.file.type,
[`${fileType}_size`]: fileToUpload.file.size,
...(fileType === 'image' && {
image_dimensions: await getHeightAndWidthFromDataUrl(window.URL.createObjectURL(fileToUpload.file)),
image_alt: fileToUpload.altText,
}),
};
};
const getEncryptedContent = async (filesToUpload: readonly EncryptedUpload[], e2eRoom: E2ERoom, msg: string) => {
const attachments: FileAttachmentProps[] = [];
const arrayOfFiles = await Promise.all(
filesToUpload.map(async (fileToUpload) => {
attachments.push(await getAttachmentForFile(fileToUpload));
const file = {
_id: fileToUpload.id,
name: fileToUpload.file.name,
type: fileToUpload.file.type,
size: fileToUpload.file.size,
format: getFileExtension(fileToUpload.file.name),
};
return file;
}),
);
return e2eRoom.encryptMessageContent({
attachments,
files: arrayOfFiles,
file: arrayOfFiles[0],
msg,
});
};
async function continueSendingMessage(store: UploadsAPI, message: IMessage) {
const { msg, rid, tmid } = message;
const e2eRoom = await e2e.getInstanceByRoomId(rid);
const shouldConvertSentMessages = await e2eRoom?.shouldConvertSentMessages({ msg });
const filesToUpload = store.get();
const confirmFilesQueue: (IUploadToConfirm & {
composedMessage: AtLeast<IMessage, 'msg' | 'tmid' | 't' | 'content'> & {
fileName?: string;
fileContent?: IE2EEMessage['content'];
description?: string;
};
})[] = [];
const validFiles = filesToUpload.filter((file) => !file.error);
for (const upload of validFiles) {
if (!upload.url || !upload.id) {
continue;
}
/**
* The first message will keep the composedMessage,
* subsequent messages will have a empty text
* */
const currentMsg = upload === validFiles[0] ? msg : '';
let content;
if (!e2eRoom || !isEncryptedUpload(upload)) {
confirmFilesQueue.push({
_id: upload.id,
name: upload.file.name,
composedMessage: { tmid, msg: currentMsg, fileName: upload.file.name, description: upload.altText || undefined },
});
continue;
}
const fileContent = await e2eRoom.encryptMessageContent(upload.metadataForEncryption);
if (shouldConvertSentMessages) {
content = await getEncryptedContent([upload], e2eRoom, currentMsg);
}
const composedMessage = {
tmid,
content,
t: 'e2e',
msg: '',
fileContent,
} as const;
confirmFilesQueue.push({ _id: upload.id, name: upload.file.name, content: fileContent, composedMessage });
}
try {
store.setProcessingUploads(true);
for (const fileToConfirm of confirmFilesQueue) {
await sdk.rest.post(`/v1/rooms.mediaConfirm/${rid}/${fileToConfirm._id}`, fileToConfirm.composedMessage);
store.removeUpload(fileToConfirm._id);
}
} catch (error: unknown) {
dispatchToastMessage({ type: 'error', message: error });
} finally {
store.setProcessingUploads(false);
}
return true;
}
export const processMessageUploads = async (chat: ChatAPI, message: IMessage): Promise<boolean> => {
const store = chat.composer?.uploads;
if (!store) {
return false;
}
const filesToUpload = store.get();
if (filesToUpload.length === 0) {
return false;
}
const failedUploads = filesToUpload.filter((upload) => upload.error);
if (!failedUploads.length) {
return continueSendingMessage(store, message);
}
const allUploadsFailed = failedUploads.length === filesToUpload.length;
return new Promise((resolve) => {
imperativeModal.open({
component: GenericModal,
props: {
variant: 'warning',
children: t('__count__files_failed_to_upload', {
count: failedUploads.length,
...(failedUploads.length === 1 && { name: failedUploads[0].file.name }),
}),
...(allUploadsFailed && {
title: t('Warning'),
confirmText: t('Ok'),
onConfirm: () => {
imperativeModal.close();
},
}),
...(!allUploadsFailed && {
title: t('Are_you_sure'),
confirmText: t('Send_anyway'),
cancelText: t('Cancel'),
onConfirm: () => {
imperativeModal.close();
failedUploads.forEach((upload) => store.removeUpload(upload.id));
resolve(continueSendingMessage(store, message));
},
onCancel: () => {
imperativeModal.close();
},
}),
onClose: () => {
imperativeModal.close();
},
},
});
});
};

View File

@@ -0,0 +1,110 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { Rooms, Subscriptions, Messages } from '../../../stores';
import { sdk } from '../../SDKClient';
import { emoji } from '../../emoji';
import { roomCoordinator } from '../../rooms/roomCoordinator';
import { dispatchToastMessage } from '../../toast';
import { getUser, getUserId } from '../../user';
import type { ChatAPI } from '../ChatAPI';
const runOptimisticSetReaction = (reaction: string, messageId: IMessage['_id']): void => {
if (!getUserId()) {
return;
}
const user = getUser();
if (!user?.username) {
return;
}
const message: IMessage | undefined = Messages.state.get(messageId);
if (!message) {
return;
}
const room = Rooms.state.get(message.rid);
if (!room) {
return;
}
if (message.private) {
return;
}
if (!emoji.list[reaction]) {
return;
}
if (roomCoordinator.readOnly(room, user)) {
return;
}
if (!Subscriptions.state.find(({ rid }) => rid === message.rid)) {
return;
}
const { username } = user;
Messages.state.update(
(record) => record._id === messageId,
(record) => {
const currentReactions = record.reactions ?? {};
const hasReacted = currentReactions[reaction]?.usernames.includes(username) ?? false;
const reactions: NonNullable<IMessage['reactions']> = {};
for (const [name, value] of Object.entries(currentReactions)) {
if (name !== reaction) {
reactions[name] = value;
continue;
}
const usernames = hasReacted ? value.usernames.filter((u) => u !== username) : [...value.usernames, username];
if (usernames.length > 0) {
reactions[name] = { ...value, usernames };
}
}
if (!currentReactions[reaction]) {
reactions[reaction] = { usernames: [username] };
}
if (Object.keys(reactions).length === 0) {
const { reactions: _, ...rest } = record;
return rest;
}
return { ...record, reactions };
},
);
};
export const processSetReaction = async (chat: ChatAPI, { msg }: Pick<IMessage, 'msg'>): Promise<boolean> => {
const match = msg.trim().match(/^\+(:.*?:)$/m);
if (!match) {
return false;
}
const [, reaction] = match;
if (!emoji.list[reaction]) {
return false;
}
const lastMessage = await chat.data.findLastMessage();
if (!lastMessage) {
return false;
}
chat.composer?.clear();
runOptimisticSetReaction(reaction, lastMessage._id);
try {
await sdk.rest.post('/v1/chat.react', { emoji: reaction, messageId: lastMessage._id });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
throw error;
}
return true;
};

View File

@@ -0,0 +1,117 @@
import type { IMessage, SlashCommand } from '@rocket.chat/core-typings';
import { Random } from '@rocket.chat/random';
import { escapeHTML } from '@rocket.chat/tools';
import { t } from '../../../../app/utils/lib/i18n';
import { sdk } from '../../SDKClient';
import { hasAtLeastOnePermission } from '../../authorization';
import { settings } from '../../settings';
import { slashCommands } from '../../slashCommand';
import type { ChatAPI } from '../ChatAPI';
const parse = (msg: string): { command: string; params: string } | { command: SlashCommand; params: string } | undefined => {
const match = msg.match(/^\/([^\s]+)(.*)/);
if (!match) {
return undefined;
}
const [, cmd, params] = match;
const command = slashCommands.commands[cmd];
if (!command) {
return { command: cmd, params };
}
return { command, params };
};
const warnUnrecognizedSlashCommand = async (chat: ChatAPI, message: string): Promise<void> => {
console.error(message);
await chat.data.pushEphemeralMessage({
_id: Random.id(),
ts: new Date(),
msg: message,
u: {
_id: 'rocket.cat',
username: 'rocket.cat',
name: 'Rocket.Cat',
},
private: true,
_updatedAt: new Date(),
});
};
export const processSlashCommand = async (chat: ChatAPI, message: IMessage): Promise<boolean> => {
const match = parse(message.msg);
if (!match) {
return false;
}
const { command, params } = match;
if (typeof command === 'string') {
if (!settings.peek('Message_AllowUnrecognizedSlashCommand')) {
chat.composer?.clear();
await warnUnrecognizedSlashCommand(chat, t('No_such_command', { command: escapeHTML(command) }));
return true;
}
return false;
}
const { permission, clientOnly, callback: handleOnClient, result: handleResult, appId, command: commandName } = command;
if (permission && !hasAtLeastOnePermission(permission, message.rid)) {
chat.composer?.clear();
await warnUnrecognizedSlashCommand(chat, t('You_do_not_have_permission_to_execute_this_command', { command: escapeHTML(commandName) }));
return true;
}
if (clientOnly && chat.uid) {
chat.composer?.clear();
handleOnClient?.({ command: commandName, message, params, userId: chat.uid });
return true;
}
void sdk.rest.post('/v1/statistics.telemetry', {
params: [{ eventName: 'slashCommandsStats', timestamp: Date.now(), command: commandName }],
});
const triggerId = chat.ActionManager.generateTriggerId(appId);
const data = {
cmd: commandName,
params,
msg: message,
userId: chat.uid,
} as const;
try {
if (appId) {
chat.ActionManager.notifyBusy();
}
chat.composer?.clear();
const { result } = await sdk.rest.post('/v1/commands.run', {
command: commandName,
params,
roomId: message.rid,
...(message.tmid && { tmid: message.tmid }),
...(triggerId && { triggerId }),
});
handleResult?.(undefined, result, data);
} catch (error: unknown) {
await warnUnrecognizedSlashCommand(chat, t('Something_went_wrong_while_executing_command', { command: commandName }));
handleResult?.(error, undefined, data);
}
if (appId) {
chat.ActionManager.notifyIdle();
}
return true;
};

View File

@@ -0,0 +1,61 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { GenericModal, imperativeModal } from '@rocket.chat/ui-client';
import { t } from '../../../../app/utils/lib/i18n';
import { settings } from '../../settings';
import { dispatchToastMessage } from '../../toast';
import { getUser } from '../../user';
import type { ChatAPI } from '../ChatAPI';
export const processTooLongMessage = async (chat: ChatAPI, { msg }: Pick<IMessage, 'msg'>): Promise<boolean> => {
const maxAllowedSize = settings.peek('Message_MaxAllowedSize');
if (msg.length <= maxAllowedSize) {
return false;
}
const fileUploadsEnabled = settings.peek('FileUpload_Enabled');
const convertLongMessagesToAttachment = settings.peek('Message_AllowConvertLongMessagesToAttachment');
if (chat.currentEditingMessage.getMID() || !fileUploadsEnabled || !convertLongMessagesToAttachment) {
dispatchToastMessage({ type: 'error', message: new Error(t('Message_too_long')) });
chat.composer?.setText(msg);
return true;
}
await new Promise<void>((resolve) => {
const onConfirm = async (): Promise<void> => {
const contentType = 'text/plain';
const messageBlob = new Blob([msg], { type: contentType });
const fileName = `${getUser()?.username ?? 'anonymous'} - ${new Date()}.txt`; // TODO: proper naming and formatting
const file = new File([messageBlob], fileName, {
type: contentType,
lastModified: Date.now(),
});
chat.composer?.clear();
imperativeModal.close();
await chat.flows.uploadFiles({ files: [file] });
resolve();
};
const onClose = (): void => {
imperativeModal.close();
resolve();
};
imperativeModal.open({
component: GenericModal,
props: {
title: t('Message_too_long'),
children: t('Send_it_as_attachment_instead_question'),
onConfirm,
onClose,
onCancel: onClose,
variant: 'warning',
},
});
});
return true;
};

View File

@@ -0,0 +1,59 @@
import { replyBroadcast } from './replyBroadcast';
import { createFakeMessage } from '../../../../tests/mocks/data';
import { router } from '../../../providers/RouterProvider';
import { roomCoordinator } from '../../rooms/roomCoordinator';
import type { ChatAPI } from '../ChatAPI';
jest.mock('../../rooms/roomCoordinator', () => ({
roomCoordinator: {
openRouteLink: jest.fn(),
},
}));
jest.mock('../../../providers/RouterProvider', () => ({
router: {
getSearchParameters: jest.fn(),
},
}));
const mockedOpenRouteLink = jest.mocked(roomCoordinator.openRouteLink);
const mockedGetSearchParameters = jest.mocked(router.getSearchParameters);
const messageAuthor = {
_id: 'author-user-id',
username: 'authoruser',
name: 'Author User',
};
const message = createFakeMessage({
_id: 'reply-message-id',
u: messageAuthor,
});
afterEach(() => {
jest.clearAllMocks();
});
describe('replyBroadcast', () => {
it('should not carry over the msg search parameter when opening a direct message', async () => {
mockedGetSearchParameters.mockReturnValue({
msg: 'stale-message-id',
layout: 'embedded',
});
await replyBroadcast({} as ChatAPI, message);
expect(mockedGetSearchParameters).toHaveBeenCalled();
expect(mockedOpenRouteLink).toHaveBeenCalledWith(
'd',
{ name: messageAuthor.username },
{
layout: 'embedded',
reply: 'reply-message-id',
},
);
const searchParams = mockedOpenRouteLink.mock.calls[0]?.[2];
expect(searchParams).not.toHaveProperty('msg');
});
});

View File

@@ -0,0 +1,17 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { router } from '../../../providers/RouterProvider';
import { roomCoordinator } from '../../rooms/roomCoordinator';
import type { ChatAPI } from '../ChatAPI';
export const replyBroadcast = async (_chat: ChatAPI, message: IMessage) => {
const { msg: _, ...searchParameters } = router.getSearchParameters();
roomCoordinator.openRouteLink(
'd',
{ name: message.u.username },
{
...searchParameters,
reply: message._id,
},
);
};

View File

@@ -0,0 +1,43 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { imperativeModal } from '@rocket.chat/ui-client';
import { t } from '../../../../app/utils/lib/i18n';
import DeleteMessageConfirmModal from '../../../views/room/modals/DeleteMessageConfirmModal';
import { dispatchToastMessage } from '../../toast';
import type { ChatAPI } from '../ChatAPI';
export const requestMessageDeletion = async (chat: ChatAPI, message: IMessage): Promise<void> => {
if (!(await chat.data.canDeleteMessage(message))) {
dispatchToastMessage({ type: 'error', message: t('Message_deleting_blocked') });
return;
}
const room = message.drid ? await chat.data.getDiscussionByID(message.drid) : undefined;
await new Promise<void>((resolve, reject) => {
const mid = chat.currentEditingMessage.getMID();
const onCloseModal = async (): Promise<void> => {
imperativeModal.close();
if (mid === message._id) {
chat.currentEditingMessage.stop();
}
chat.composer?.focus();
resolve();
};
imperativeModal.open({
component: DeleteMessageConfirmModal,
props: {
room,
chat,
resolve,
reject,
message,
onCancel: onCloseModal,
},
});
});
};

View File

@@ -0,0 +1,195 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { t } from '../../../../app/utils/lib/i18n';
import { closeUnclosedCodeBlock } from '../../../../lib/utils/closeUnclosedCodeBlock';
import { Messages, Rooms } from '../../../stores';
import { onClientBeforeSendMessage } from '../../onClientBeforeSendMessage';
import { dispatchToastMessage } from '../../toast';
import type { ChatAPI } from '../ChatAPI';
import { afterSendMessageCallback } from './afterSendMessageCallback';
import { processMessageEditing } from './processMessageEditing';
import { processMessageUploads } from './processMessageUploads';
import { processSetReaction } from './processSetReaction';
import { processSlashCommand } from './processSlashCommand';
import { processTooLongMessage } from './processTooLongMessage';
import { trim } from '../../../../lib/utils/stringUtils';
import { sdk } from '../../SDKClient';
import { onClientMessageReceived } from '../../onClientMessageReceived';
import { settings } from '../../settings';
import { getUserId, getUser } from '../../user';
import { upsertThreadMessageInCache } from '../../utils/threadMessageUtils';
const runOptimisticSendMessage = async (message: Partial<IMessage> & { rid: IMessage['rid']; msg: IMessage['msg'] }): Promise<void> => {
const uid = getUserId();
if (!uid || trim(message.msg) === '') {
return;
}
const messageAlreadyExists = message._id && Messages.state.get(message._id);
if (messageAlreadyExists) {
dispatchToastMessage({ type: 'error', message: t('Message_Already_Sent') });
return;
}
const user = getUser();
if (!user?.username) {
return;
}
const room = Rooms.state.get(message.rid);
if (room?.federated) {
return;
}
const optimistic: IMessage = {
...(message as IMessage),
ts: new Date(),
u: {
_id: uid,
username: user.username,
name: user.name || '',
},
temp: true,
...(settings.peek('Message_Read_Receipt_Enabled') ? { unread: true } : {}),
};
const processed = await onClientMessageReceived(optimistic);
Messages.state.store(processed);
if (processed.tmid) {
upsertThreadMessageInCache(processed, processed.rid, processed.tmid);
}
};
const process = async (chat: ChatAPI, message: IMessage, previewUrls?: string[], isSlashCommandAllowed?: boolean): Promise<void> => {
const mid = chat.currentEditingMessage.getMID();
if (await processSetReaction(chat, message)) {
return;
}
if (await processTooLongMessage(chat, message)) {
return;
}
if (isSlashCommandAllowed && (await processSlashCommand(chat, message))) {
return;
}
if (await processMessageUploads(chat, message)) {
chat.composer?.clear();
return;
}
message = (await onClientBeforeSendMessage({ ...message, isEditing: !!mid })) as IMessage & { isEditing?: boolean };
// e2e should be a client property only
delete message.e2e;
delete (message as IMessage & { isEditing?: boolean }).isEditing;
if (await processMessageEditing(chat, message, previewUrls)) {
return;
}
chat.composer?.clear();
await runOptimisticSendMessage(message);
await sdk.rest.post('/v1/chat.sendMessage', { message, previewUrls });
// Clear the optimistic `temp` flag only if the messages stream hasn't already
// replaced the record. Overwriting with the server response can clobber stream
// updates that arrive first — e.g. read-receipt-driven `unread: false`, async
// URL/quote attachments, or E2EE decrypt — leading to stale UI state.
Messages.state.update(
(record) => record._id === message._id && record.temp === true,
({ temp: _, ...record }) => record,
);
};
export const sendMessage = async (
chat: ChatAPI,
{
text,
tshow,
previewUrls,
isSlashCommandAllowed,
}: { text: string; tshow?: boolean; previewUrls?: string[]; isSlashCommandAllowed?: boolean; tmid?: IMessage['tmid'] },
): Promise<boolean> => {
if (!(await chat.data.isSubscribedToRoom())) {
try {
await chat.data.joinRoom();
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
return false;
}
}
chat.readStateManager.clearUnreadMark();
const uploadsStore = chat.composer?.uploads;
text = text.trim();
text = closeUnclosedCodeBlock(text);
const mid = chat.currentEditingMessage.getMID();
const hasFiles = uploadsStore && uploadsStore.get().length > 0;
if (!text && !mid && !hasFiles) {
// Nothing to do
return false;
}
if (text || hasFiles) {
const message = await chat.data.composeMessage(text, {
sendToChannel: tshow,
quotedMessages: chat.composer?.quotedMessages.get() ?? [],
originalMessage: mid ? await chat.data.findMessageByID(mid) : null,
});
// When editing an encrypted message with files, preserve the original attachments/files
// This ensures they're included in the re-encryption process
if (mid) {
const originalMessage = await chat.data.findMessageByID(mid);
if (originalMessage?.t === 'e2e' && originalMessage.attachments && originalMessage.attachments.length > 0) {
message.attachments = originalMessage.attachments;
message.file = originalMessage.file;
}
}
try {
// Dismiss quoted messages optimistically — they are already baked into
// `message` by composeMessage above, so the composer preview must unmount
// regardless of whether the send request resolves. Keeping it coupled to a
// resolved request leaves the quote stuck in the composer when the REST call
// rejects even though the message was already broadcast over the stream.
chat.composer?.dismissAllQuotedMessages();
await process(chat, message, previewUrls, isSlashCommandAllowed);
await afterSendMessageCallback(message, message.rid);
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
return true;
}
if (mid) {
const originalMessage = await chat.data.findMessageByID(mid);
if (!originalMessage) {
dispatchToastMessage({ type: 'warning', message: t('Message_not_found') });
return false;
}
try {
if (await chat.flows.processMessageEditing({ ...originalMessage, msg: '' }, previewUrls)) {
chat.currentEditingMessage.stop();
return false;
}
await chat.currentEditingMessage.reset();
await chat.flows.requestMessageDeletion(originalMessage);
return false;
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
}
return false;
};

View File

@@ -0,0 +1,86 @@
import { t } from '../../../../app/utils/lib/i18n';
import { MAX_MULTIPLE_UPLOADED_FILES } from '../../../../lib/constants';
import { e2e } from '../../e2ee';
import { settings } from '../../settings';
import { dispatchToastMessage } from '../../toast';
import type { ChatAPI } from '../ChatAPI';
export const uploadFiles = async (
chat: ChatAPI,
{ files, resetFileInput }: { files: readonly File[]; resetFileInput?: () => void },
): Promise<void> => {
const uploadsStore = chat.composer?.uploads;
if (!uploadsStore) {
throw new Error('No uploads store found in composer');
}
const mergedFilesLength = files.length + uploadsStore.get().length;
if (mergedFilesLength > MAX_MULTIPLE_UPLOADED_FILES) {
return dispatchToastMessage({
type: 'error',
message: t('You_cant_upload_more_than__count__files', { count: MAX_MULTIPLE_UPLOADED_FILES }),
});
}
const room = await chat.data.getRoom();
if (room.encrypted && !settings.peek('E2E_Allow_Unencrypted_Messages') && !settings.peek('E2E_Enable_Encrypt_Files')) {
return dispatchToastMessage({
type: 'error',
message: t('You_cant_send_unencrypted_files_in_an_encrypted_room'),
});
}
const uploadFile = async (file: File) => {
Object.defineProperty(file, 'name', {
writable: true,
value: file.name,
});
const e2eRoom = await e2e.getInstanceByRoomId(room._id);
if (!e2eRoom || !settings.peek('E2E_Enable_Encrypt_Files')) {
await uploadsStore.send(file);
return;
}
const encryptedFile = await e2eRoom.encryptFile(file);
if (!e2eRoom.isReady() || !encryptedFile) {
dispatchToastMessage({
type: 'error',
message: t('Error_encrypting_file'),
});
return;
}
const fileContentData = {
type: file.type,
typeGroup: file.type.split('/')[0],
name: file.name,
encryption: {
key: encryptedFile.key,
iv: encryptedFile.iv,
},
hashes: {
sha256: encryptedFile.hash,
},
};
const fileContent = {
raw: fileContentData,
encrypted: await e2eRoom.encryptMessageContent(fileContentData),
};
await uploadsStore.send(encryptedFile.file, { rawFile: file, fileContent, encryptedFile });
};
resetFileInput?.();
chat?.action.performContinuously('uploading');
try {
await Promise.allSettled(files.map((file) => uploadFile(file)));
} finally {
chat.composer?.focus();
}
};