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
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:
186
apps/meteor/client/lib/chats/ChatAPI.ts
Normal file
186
apps/meteor/client/lib/chats/ChatAPI.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import type { IMessage, IRoom, ISubscription, IE2EEMessage, IUpload } from '@rocket.chat/core-typings';
|
||||
import type { IActionManager } from '@rocket.chat/ui-contexts';
|
||||
import type { RefObject } from 'react';
|
||||
|
||||
import type { Upload, EncryptedFile } from './Upload';
|
||||
import type { ReadStateManager } from './readStateManager';
|
||||
import type { FormattingButton } from '../messageBoxFormatting';
|
||||
|
||||
type Subscribable<T> = {
|
||||
get(): T;
|
||||
subscribe(callback: () => void): () => void;
|
||||
};
|
||||
|
||||
export type ComposerAPI = {
|
||||
release(): void;
|
||||
readonly text: string;
|
||||
readonly selection: { readonly start: number; readonly end: number };
|
||||
setText(
|
||||
text: string,
|
||||
options?: {
|
||||
selection?:
|
||||
| { readonly start?: number; readonly end?: number }
|
||||
| ((previous: { readonly start: number; readonly end: number }) => { readonly start?: number; readonly end?: number });
|
||||
},
|
||||
): void;
|
||||
wrapSelection(pattern: string): {
|
||||
selectionStart: number;
|
||||
selectionEnd: number;
|
||||
value: string;
|
||||
};
|
||||
insertText(text: string): void;
|
||||
insertNewLine(): void;
|
||||
clear(): void;
|
||||
focus(): void;
|
||||
blur(): void;
|
||||
|
||||
getCursorPosition(): number | undefined;
|
||||
|
||||
substring(start: number, end?: number): string;
|
||||
|
||||
replaceText(
|
||||
text: string,
|
||||
selection: {
|
||||
start: number;
|
||||
end: number;
|
||||
},
|
||||
): void;
|
||||
|
||||
setCursorToEnd(): void;
|
||||
setCursorToStart(): void;
|
||||
replyWith(text: string): Promise<void>;
|
||||
quoteMessage(message: IMessage): Promise<void>;
|
||||
dismissQuotedMessage(mid: IMessage['_id']): Promise<void>;
|
||||
dismissAllQuotedMessages(): Promise<void>;
|
||||
readonly quotedMessages: Subscribable<IMessage[]>;
|
||||
|
||||
setEditingMode(editing: boolean): void;
|
||||
readonly editing: Subscribable<boolean>;
|
||||
|
||||
setRecordingMode(recording: boolean): void;
|
||||
readonly recording: Subscribable<boolean>;
|
||||
|
||||
setRecordingVideo(recording: boolean): void;
|
||||
readonly recordingVideo: Subscribable<boolean>;
|
||||
|
||||
setIsMicrophoneDenied(isMicrophoneDenied: boolean): void;
|
||||
readonly isMicrophoneDenied: Subscribable<boolean>;
|
||||
|
||||
readonly formatters: Subscribable<FormattingButton[]>;
|
||||
|
||||
readonly composerRef: RefObject<HTMLElement | null>;
|
||||
|
||||
readonly uploads: UploadsAPI;
|
||||
};
|
||||
|
||||
export type DataAPI = {
|
||||
composeMessage(
|
||||
text: string,
|
||||
options: { sendToChannel?: boolean; quotedMessages: IMessage[]; originalMessage?: IMessage | null },
|
||||
): Promise<IMessage>;
|
||||
findMessageByID(mid: IMessage['_id']): Promise<IMessage | null>;
|
||||
getMessageByID(mid: IMessage['_id']): Promise<IMessage>;
|
||||
findLastMessage(): Promise<IMessage | undefined>;
|
||||
getLastMessage(): Promise<IMessage>;
|
||||
findPreviousOwnMessage(message?: IMessage): Promise<IMessage | undefined>;
|
||||
getPreviousOwnMessage(message: IMessage): Promise<IMessage>;
|
||||
findNextOwnMessage(message: IMessage): Promise<IMessage | undefined>;
|
||||
getNextOwnMessage(message: IMessage): Promise<IMessage>;
|
||||
pushEphemeralMessage(message: Omit<IMessage, 'rid' | 'tmid'>): Promise<void>;
|
||||
canUpdateMessage(message: IMessage): Promise<boolean>;
|
||||
updateMessage(message: Pick<IMessage, '_id' | 't'> & Partial<Omit<IMessage, '_id' | 't'>>, previewUrls?: string[]): Promise<void>;
|
||||
canDeleteMessage(message: IMessage): Promise<boolean>;
|
||||
deleteMessage(msgIdOrMsg: IMessage | IMessage['_id']): Promise<void>;
|
||||
getDraft(mid: IMessage['_id'] | undefined): Promise<string | undefined>;
|
||||
discardDraft(mid: IMessage['_id'] | undefined): Promise<void>;
|
||||
saveDraft(mid: IMessage['_id'] | undefined, text: string): Promise<void>;
|
||||
findRoom(): Promise<IRoom | undefined>;
|
||||
getRoom(): Promise<IRoom>;
|
||||
isSubscribedToRoom(): Promise<boolean>;
|
||||
joinRoom(): Promise<void>;
|
||||
findDiscussionByID(drid: IRoom['_id']): Promise<IRoom | undefined>;
|
||||
getDiscussionByID(drid: IRoom['_id']): Promise<IRoom>;
|
||||
findSubscription(): Promise<ISubscription | undefined>;
|
||||
getSubscription(): Promise<ISubscription>;
|
||||
findSubscriptionFromMessage(message: IMessage): Promise<ISubscription | undefined>;
|
||||
getSubscriptionFromMessage(message: IMessage): Promise<ISubscription>;
|
||||
};
|
||||
|
||||
export type EncryptedFileUploadContent = {
|
||||
rawFile: File;
|
||||
fileContent: { raw: Partial<IUpload>; encrypted?: IE2EEMessage['content'] };
|
||||
encryptedFile: EncryptedFile;
|
||||
};
|
||||
|
||||
export type UploadsAPI = {
|
||||
get(): readonly Upload[];
|
||||
subscribe(callback: () => void): () => void;
|
||||
wipeFailedOnes(): void;
|
||||
clear(): void;
|
||||
getProcessingUploads(): boolean;
|
||||
setProcessingUploads(processing: boolean): void;
|
||||
cancel(id: Upload['id']): void;
|
||||
removeUpload(id: Upload['id']): void;
|
||||
editUploadFileName: (id: Upload['id'], fileName: string) => void;
|
||||
editUploadAltText: (id: Upload['id'], altText: string) => void;
|
||||
send(file: File, encrypted?: never): Promise<void>;
|
||||
send(file: File, encrypted: EncryptedFileUploadContent): Promise<void>;
|
||||
};
|
||||
|
||||
export type ChatAPI = {
|
||||
readonly uid: string | undefined;
|
||||
readonly composer?: ComposerAPI;
|
||||
readonly setComposerAPI: (composer?: ComposerAPI) => void;
|
||||
readonly data: DataAPI;
|
||||
readonly readStateManager: ReadStateManager;
|
||||
readonly messageEditing: {
|
||||
toPreviousMessage(): Promise<void>;
|
||||
toNextMessage(): Promise<void>;
|
||||
editMessage(message: IMessage, options?: { cursorAtStart?: boolean }): Promise<void>;
|
||||
};
|
||||
|
||||
readonly currentEditingMessage: {
|
||||
setMID(mid: IMessage['_id']): void;
|
||||
getMID(): string | undefined;
|
||||
reset(): Promise<boolean>;
|
||||
stop(): Promise<void>;
|
||||
cancel(): Promise<void>;
|
||||
};
|
||||
|
||||
readonly emojiPicker: {
|
||||
open(el: Element, cb: (emoji: string) => void): void;
|
||||
close(): void;
|
||||
};
|
||||
|
||||
readonly action: {
|
||||
start(action: 'typing'): void;
|
||||
stop(action: 'typing' | 'recording' | 'uploading' | 'playing'): void;
|
||||
performContinuously(action: 'recording' | 'uploading' | 'playing'): void;
|
||||
};
|
||||
|
||||
ActionManager: IActionManager;
|
||||
|
||||
readonly flows: {
|
||||
readonly uploadFiles: ({ files, resetFileInput }: { files: readonly File[]; resetFileInput?: () => void }) => Promise<void>;
|
||||
readonly sendMessage: ({
|
||||
text,
|
||||
tshow,
|
||||
}: {
|
||||
text: string;
|
||||
tshow?: boolean;
|
||||
previewUrls?: string[];
|
||||
isSlashCommandAllowed?: boolean;
|
||||
tmid?: IMessage['tmid'];
|
||||
}) => Promise<boolean>;
|
||||
readonly processSlashCommand: (message: IMessage, userId: string | null) => Promise<boolean>;
|
||||
readonly processTooLongMessage: (message: IMessage) => Promise<boolean>;
|
||||
readonly processMessageEditing: (
|
||||
message: Pick<IMessage, '_id' | 't'> & Partial<Omit<IMessage, '_id' | 't'>>,
|
||||
previewUrls?: string[],
|
||||
) => Promise<boolean>;
|
||||
readonly processMessageUploads: (message: IMessage) => Promise<boolean>;
|
||||
readonly processSetReaction: (message: Pick<IMessage, 'msg'>) => Promise<boolean>;
|
||||
readonly requestMessageDeletion: (message: IMessage) => Promise<void>;
|
||||
readonly replyBroadcast: (message: IMessage) => Promise<void>;
|
||||
};
|
||||
};
|
||||
28
apps/meteor/client/lib/chats/Upload.ts
Normal file
28
apps/meteor/client/lib/chats/Upload.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { IUpload } from '@rocket.chat/core-typings';
|
||||
|
||||
export type NonEncryptedUpload = {
|
||||
readonly id: string;
|
||||
readonly file: File;
|
||||
readonly url?: string;
|
||||
readonly percentage: number;
|
||||
readonly error?: Error;
|
||||
readonly altText?: string;
|
||||
};
|
||||
|
||||
export type EncryptedUpload = NonEncryptedUpload & {
|
||||
readonly encryptedFile: EncryptedFile;
|
||||
readonly metadataForEncryption: Partial<IUpload>;
|
||||
};
|
||||
|
||||
export type Upload = EncryptedUpload | NonEncryptedUpload;
|
||||
|
||||
export type EncryptedFile = {
|
||||
readonly file: File;
|
||||
readonly key: JsonWebKey;
|
||||
readonly iv: string;
|
||||
readonly type: File['type'];
|
||||
readonly hash: string;
|
||||
};
|
||||
|
||||
export const isEncryptedUpload = (upload: Upload): upload is EncryptedUpload =>
|
||||
'encryptedFile' in upload && upload.encryptedFile !== undefined;
|
||||
349
apps/meteor/client/lib/chats/data.ts
Normal file
349
apps/meteor/client/lib/chats/data.ts
Normal file
@@ -0,0 +1,349 @@
|
||||
import { isEncryptedMessageContent, type IEditedMessage, type IMessage, type IRoom, type ISubscription } from '@rocket.chat/core-typings';
|
||||
import { MessageTypes } from '@rocket.chat/message-types';
|
||||
import { Random } from '@rocket.chat/random';
|
||||
import { differenceInMinutes } from 'date-fns';
|
||||
|
||||
import type { DataAPI } from './ChatAPI';
|
||||
import { Messages, Rooms, Subscriptions } from '../../stores';
|
||||
import { sdk } from '../SDKClient';
|
||||
import { hasAtLeastOnePermission, hasPermission } from '../authorization';
|
||||
import { settings } from '../settings';
|
||||
import { getUserId } from '../user';
|
||||
import { mapMessageFromApi } from '../utils/mapMessageFromApi';
|
||||
import { prependReplies } from '../utils/prependReplies';
|
||||
import { upsertThreadMessageInCache } from '../utils/threadMessageUtils';
|
||||
|
||||
export const createDataAPI = ({ rid, tmid }: { rid: IRoom['_id']; tmid: IMessage['_id'] | undefined }): DataAPI => {
|
||||
const composeMessage = async (
|
||||
text: string,
|
||||
{ sendToChannel, quotedMessages, originalMessage }: { sendToChannel?: boolean; quotedMessages: IMessage[]; originalMessage?: IMessage },
|
||||
): Promise<IMessage> => {
|
||||
const msg = await prependReplies(text, quotedMessages);
|
||||
|
||||
const effectiveRID = originalMessage?.rid ?? rid;
|
||||
const effectiveTMID = originalMessage ? originalMessage.tmid : tmid;
|
||||
|
||||
return {
|
||||
_id: originalMessage?._id ?? Random.id(),
|
||||
rid: effectiveRID,
|
||||
...(effectiveTMID && {
|
||||
tmid: effectiveTMID,
|
||||
...(sendToChannel && { tshow: sendToChannel }),
|
||||
}),
|
||||
msg,
|
||||
} as IMessage;
|
||||
};
|
||||
|
||||
const findMessageByID = async (mid: IMessage['_id']): Promise<IMessage | null> =>
|
||||
Messages.state.find((record) => record._id === mid && record._hidden !== true) ??
|
||||
sdk.rest.get('/v1/chat.getMessage', { msgId: mid }).then((response) => mapMessageFromApi(response.message));
|
||||
|
||||
const getMessageByID = async (mid: IMessage['_id']): Promise<IMessage> => {
|
||||
const message = await findMessageByID(mid);
|
||||
|
||||
if (!message) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
return message;
|
||||
};
|
||||
|
||||
const findLastMessage = async (): Promise<IMessage | undefined> =>
|
||||
Messages.state.findFirst(
|
||||
(record) => record.rid === rid && (tmid ? record.tmid === tmid : !record.tmid) && record._hidden !== true,
|
||||
(a, b) => b.ts.getTime() - a.ts.getTime(),
|
||||
);
|
||||
|
||||
const getLastMessage = async (): Promise<IMessage> => {
|
||||
const message = await findLastMessage();
|
||||
|
||||
if (!message) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
return message;
|
||||
};
|
||||
|
||||
const canUpdateMessage = async (message: IMessage): Promise<boolean> => {
|
||||
if (MessageTypes.isSystemMessage(message)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const canEditMessage = hasAtLeastOnePermission('edit-message', message.rid);
|
||||
const editAllowed = settings.peek('Message_AllowEditing') ?? false;
|
||||
const editOwn = message?.u && message.u._id === getUserId();
|
||||
|
||||
if (!canEditMessage && (!editAllowed || !editOwn)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const blockEditInMinutes = settings.peek('Message_AllowEditing_BlockEditInMinutes');
|
||||
const bypassBlockTimeLimit = hasPermission('bypass-time-limit-edit-and-delete', message.rid);
|
||||
|
||||
const elapsedMinutes = differenceInMinutes(new Date(), message.ts);
|
||||
if (!bypassBlockTimeLimit && elapsedMinutes && blockEditInMinutes && elapsedMinutes > blockEditInMinutes) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const findPreviousOwnMessage = async (message?: IMessage): Promise<IMessage | undefined> => {
|
||||
const uid = getUserId();
|
||||
|
||||
if (!uid) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const msg = Messages.state.findFirst(
|
||||
(record) =>
|
||||
record.rid === rid &&
|
||||
(tmid ? record.tmid === tmid : !record.tmid) &&
|
||||
record.u._id === uid &&
|
||||
record._hidden !== true &&
|
||||
record.ts.getTime() < (message?.ts.getTime() ?? Date.now()),
|
||||
(a, b) => b.ts.getTime() - a.ts.getTime(),
|
||||
);
|
||||
|
||||
if (!msg) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (await canUpdateMessage(msg)) {
|
||||
return msg;
|
||||
}
|
||||
|
||||
return findPreviousOwnMessage(msg);
|
||||
};
|
||||
|
||||
const getPreviousOwnMessage = async (message: IMessage): Promise<IMessage> => {
|
||||
const previousMessage = await findPreviousOwnMessage(message);
|
||||
|
||||
if (!previousMessage) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
return previousMessage;
|
||||
};
|
||||
|
||||
const findNextOwnMessage = async (message: IMessage): Promise<IMessage | undefined> => {
|
||||
const uid = getUserId();
|
||||
|
||||
if (!uid) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const msg = Messages.state.findFirst(
|
||||
(record) =>
|
||||
record.rid === rid &&
|
||||
(tmid ? record.tmid === tmid : !record.tmid) &&
|
||||
record.u._id === uid &&
|
||||
record._hidden !== true &&
|
||||
record.ts.getTime() > message.ts.getTime(),
|
||||
(a, b) => a.ts.getTime() - b.ts.getTime(),
|
||||
);
|
||||
|
||||
if (!msg) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (await canUpdateMessage(msg)) {
|
||||
return msg;
|
||||
}
|
||||
|
||||
return findNextOwnMessage(msg);
|
||||
};
|
||||
|
||||
const getNextOwnMessage = async (message: IMessage): Promise<IMessage> => {
|
||||
const nextMessage = await findNextOwnMessage(message);
|
||||
|
||||
if (!nextMessage) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
return nextMessage;
|
||||
};
|
||||
|
||||
const pushEphemeralMessage = async (message: Omit<IMessage, 'rid' | 'tmid'>): Promise<void> => {
|
||||
const fullMessage = { ...message, rid, ...(tmid && { tmid }) };
|
||||
Messages.state.store(fullMessage);
|
||||
|
||||
if (tmid) {
|
||||
upsertThreadMessageInCache(fullMessage, rid, tmid);
|
||||
}
|
||||
};
|
||||
|
||||
const updateMessage = async (message: IEditedMessage, previewUrls?: string[]): Promise<void> => {
|
||||
const params = isEncryptedMessageContent(message)
|
||||
? {
|
||||
msgId: message._id,
|
||||
roomId: message.rid,
|
||||
content: message.content,
|
||||
e2eMentions: message.e2eMentions,
|
||||
}
|
||||
: {
|
||||
previewUrls,
|
||||
msgId: message._id,
|
||||
roomId: message.rid,
|
||||
customFields: message.customFields,
|
||||
text: message.msg,
|
||||
};
|
||||
|
||||
await sdk.rest.post('/v1/chat.update', params);
|
||||
};
|
||||
|
||||
const canDeleteMessage = async (message: IMessage): Promise<boolean> => {
|
||||
const uid = getUserId();
|
||||
|
||||
if (!uid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (MessageTypes.isSystemMessage(message)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const forceDeleteAllowed = hasPermission('force-delete-message', message.rid);
|
||||
if (forceDeleteAllowed) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const deletionEnabled = settings.peek('Message_AllowDeleting');
|
||||
if (!deletionEnabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const deleteAnyAllowed = hasPermission('delete-message', rid);
|
||||
const deleteOwnAllowed = hasPermission('delete-own-message');
|
||||
const deleteAllowed = deleteAnyAllowed || (deleteOwnAllowed && message?.u && message.u._id === getUserId());
|
||||
|
||||
if (!deleteAllowed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const blockDeleteInMinutes = settings.peek('Message_AllowDeleting_BlockDeleteInMinutes');
|
||||
const bypassBlockTimeLimit = hasPermission('bypass-time-limit-edit-and-delete', message.rid);
|
||||
const elapsedMinutes = differenceInMinutes(new Date(), message.ts);
|
||||
const onTimeForDelete = bypassBlockTimeLimit || !blockDeleteInMinutes || !elapsedMinutes || elapsedMinutes <= blockDeleteInMinutes;
|
||||
|
||||
return deleteAllowed && onTimeForDelete;
|
||||
};
|
||||
|
||||
const deleteMessage = async (msgIdOrMsg: IMessage | IMessage['_id']): Promise<void> => {
|
||||
let msgId: string;
|
||||
let roomId: string;
|
||||
if (typeof msgIdOrMsg === 'string') {
|
||||
msgId = msgIdOrMsg;
|
||||
const msg = await findMessageByID(msgId);
|
||||
if (!msg) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
roomId = msg.rid;
|
||||
} else {
|
||||
msgId = msgIdOrMsg._id;
|
||||
roomId = msgIdOrMsg.rid;
|
||||
}
|
||||
|
||||
await sdk.rest.post('/v1/chat.delete', { msgId, roomId });
|
||||
};
|
||||
|
||||
const drafts = new Map<IMessage['_id'] | undefined, string>();
|
||||
|
||||
const getDraft = async (mid: IMessage['_id'] | undefined): Promise<string | undefined> => drafts.get(mid);
|
||||
|
||||
const discardDraft = async (mid: IMessage['_id'] | undefined): Promise<void> => {
|
||||
drafts.delete(mid);
|
||||
};
|
||||
|
||||
const saveDraft = async (mid: IMessage['_id'] | undefined, draft: string): Promise<void> => {
|
||||
drafts.set(mid, draft);
|
||||
};
|
||||
|
||||
const findRoom = async (): Promise<IRoom | undefined> => Rooms.state.get(rid);
|
||||
|
||||
const getRoom = async (): Promise<IRoom> => {
|
||||
const room = await findRoom();
|
||||
|
||||
if (!room) {
|
||||
throw new Error('Room not found');
|
||||
}
|
||||
|
||||
return room;
|
||||
};
|
||||
|
||||
const isSubscribedToRoom = async (): Promise<boolean> => !!Subscriptions.state.find((record) => record.rid === rid);
|
||||
|
||||
const joinRoom = async (): Promise<void> => {
|
||||
await sdk.rest.post('/v1/rooms.join', { roomId: rid });
|
||||
};
|
||||
|
||||
const findDiscussionByID = async (drid: IRoom['_id']): Promise<IRoom | undefined> =>
|
||||
Rooms.state.find((record) => Boolean(record._id === drid && record.prid));
|
||||
|
||||
const getDiscussionByID = async (drid: IRoom['_id']): Promise<IRoom> => {
|
||||
const discussion = await findDiscussionByID(drid);
|
||||
|
||||
if (!discussion) {
|
||||
throw new Error('Discussion not found');
|
||||
}
|
||||
|
||||
return discussion;
|
||||
};
|
||||
|
||||
const createStrictGetter = <TFind extends (...args: any[]) => Promise<any>>(
|
||||
find: TFind,
|
||||
errorMessage: string,
|
||||
): ((...args: Parameters<TFind>) => Promise<Exclude<Awaited<ReturnType<TFind>>, undefined>>) => {
|
||||
return async (...args) => {
|
||||
const result = await find(...args);
|
||||
|
||||
if (!result) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
const findSubscription = async (): Promise<ISubscription | undefined> => {
|
||||
return Subscriptions.state.find((record) => record.rid === rid);
|
||||
};
|
||||
|
||||
const getSubscription = createStrictGetter(findSubscription, 'Subscription not found');
|
||||
|
||||
const findSubscriptionFromMessage = async (message: IMessage): Promise<ISubscription | undefined> => {
|
||||
return Subscriptions.state.find((record) => record.rid === message.rid);
|
||||
};
|
||||
|
||||
const getSubscriptionFromMessage = createStrictGetter(findSubscriptionFromMessage, 'Subscription not found');
|
||||
|
||||
return {
|
||||
composeMessage,
|
||||
findMessageByID,
|
||||
getMessageByID,
|
||||
findLastMessage,
|
||||
getLastMessage,
|
||||
findPreviousOwnMessage,
|
||||
getPreviousOwnMessage,
|
||||
findNextOwnMessage,
|
||||
getNextOwnMessage,
|
||||
pushEphemeralMessage,
|
||||
canUpdateMessage,
|
||||
updateMessage,
|
||||
canDeleteMessage,
|
||||
deleteMessage,
|
||||
getDraft,
|
||||
saveDraft,
|
||||
discardDraft,
|
||||
findRoom,
|
||||
getRoom,
|
||||
isSubscribedToRoom,
|
||||
joinRoom,
|
||||
findDiscussionByID,
|
||||
getDiscussionByID,
|
||||
findSubscription,
|
||||
getSubscription,
|
||||
findSubscriptionFromMessage,
|
||||
getSubscriptionFromMessage,
|
||||
};
|
||||
};
|
||||
@@ -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 });
|
||||
};
|
||||
35
apps/meteor/client/lib/chats/flows/processMessageEditing.ts
Normal file
35
apps/meteor/client/lib/chats/flows/processMessageEditing.ts
Normal 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;
|
||||
};
|
||||
219
apps/meteor/client/lib/chats/flows/processMessageUploads.ts
Normal file
219
apps/meteor/client/lib/chats/flows/processMessageUploads.ts
Normal 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();
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
110
apps/meteor/client/lib/chats/flows/processSetReaction.ts
Normal file
110
apps/meteor/client/lib/chats/flows/processSetReaction.ts
Normal 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;
|
||||
};
|
||||
117
apps/meteor/client/lib/chats/flows/processSlashCommand.ts
Normal file
117
apps/meteor/client/lib/chats/flows/processSlashCommand.ts
Normal 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;
|
||||
};
|
||||
61
apps/meteor/client/lib/chats/flows/processTooLongMessage.ts
Normal file
61
apps/meteor/client/lib/chats/flows/processTooLongMessage.ts
Normal 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;
|
||||
};
|
||||
59
apps/meteor/client/lib/chats/flows/replyBroadcast.spec.ts
Normal file
59
apps/meteor/client/lib/chats/flows/replyBroadcast.spec.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
17
apps/meteor/client/lib/chats/flows/replyBroadcast.ts
Normal file
17
apps/meteor/client/lib/chats/flows/replyBroadcast.ts
Normal 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,
|
||||
},
|
||||
);
|
||||
};
|
||||
43
apps/meteor/client/lib/chats/flows/requestMessageDeletion.ts
Normal file
43
apps/meteor/client/lib/chats/flows/requestMessageDeletion.ts
Normal 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,
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
195
apps/meteor/client/lib/chats/flows/sendMessage.ts
Normal file
195
apps/meteor/client/lib/chats/flows/sendMessage.ts
Normal 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;
|
||||
};
|
||||
86
apps/meteor/client/lib/chats/flows/uploadFiles.ts
Normal file
86
apps/meteor/client/lib/chats/flows/uploadFiles.ts
Normal 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();
|
||||
}
|
||||
};
|
||||
159
apps/meteor/client/lib/chats/readStateManager.ts
Normal file
159
apps/meteor/client/lib/chats/readStateManager.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import type { IMessage, IRoom, ISubscription } from '@rocket.chat/core-typings';
|
||||
import { Emitter } from '@rocket.chat/emitter';
|
||||
|
||||
import { withDebouncing } from '../../../lib/utils/highOrderFunctions';
|
||||
import { Messages } from '../../stores';
|
||||
import { LegacyRoomManager } from '../LegacyRoomManager';
|
||||
import { RoomHistoryManager } from '../RoomHistoryManager';
|
||||
import { sdk } from '../SDKClient';
|
||||
import { getUserId } from '../user';
|
||||
|
||||
export class ReadStateManager extends Emitter {
|
||||
private rid: IRoom['_id'];
|
||||
|
||||
private firstUnreadRecordId?: IMessage['_id'];
|
||||
|
||||
private subscription?: ISubscription;
|
||||
|
||||
public constructor(rid: IRoom['_id']) {
|
||||
super();
|
||||
this.rid = rid;
|
||||
}
|
||||
|
||||
public getRid() {
|
||||
return this.rid;
|
||||
}
|
||||
|
||||
public onUnreadStateChange = (callback: () => void): (() => void) => {
|
||||
return this.on('unread-state-change', callback);
|
||||
};
|
||||
|
||||
public getFirstUnreadRecordId = () => {
|
||||
return this.firstUnreadRecordId;
|
||||
};
|
||||
|
||||
public subscribeToMessages() {
|
||||
return RoomHistoryManager.on('loaded-messages', () => this.updateFirstUnreadRecordId());
|
||||
}
|
||||
|
||||
public updateSubscription(subscription?: ISubscription) {
|
||||
if (!subscription) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstUpdate = !this.subscription;
|
||||
|
||||
this.subscription = subscription;
|
||||
LegacyRoomManager.setPropertyByRid(this.rid, 'unreadSince', this.subscription.ls);
|
||||
|
||||
const { unread, alert } = this.subscription;
|
||||
if (!unread && !alert) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (firstUpdate) {
|
||||
this.updateFirstUnreadRecordId();
|
||||
return;
|
||||
}
|
||||
|
||||
if (document.hasFocus() && this.firstUnreadRecordId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.updateFirstUnreadRecordId();
|
||||
}
|
||||
|
||||
private updateFirstUnreadRecordId() {
|
||||
if (!this.subscription?.ls) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstUnreadRecord = Messages.state.findFirst(
|
||||
(record) =>
|
||||
record.rid === this.subscription?.rid &&
|
||||
record.ts.getTime() > (this.subscription.ls?.getTime() ?? 0) &&
|
||||
record.u._id !== getUserId() &&
|
||||
(!record.tmid || record.tshow === true),
|
||||
(a, b) => a.ts.getTime() - b.ts.getTime(),
|
||||
);
|
||||
|
||||
this.setFirstUnreadRecordId(firstUnreadRecord?._id);
|
||||
}
|
||||
|
||||
private setFirstUnreadRecordId(firstUnreadRecordId: string | undefined) {
|
||||
this.firstUnreadRecordId = firstUnreadRecordId;
|
||||
this.emit('unread-state-change', this.firstUnreadRecordId);
|
||||
}
|
||||
|
||||
public clearUnreadMark() {
|
||||
this.setFirstUnreadRecordId(undefined);
|
||||
}
|
||||
|
||||
public handleWindowEvents = (): (() => void) => {
|
||||
const handleWindowFocus = () => {
|
||||
this.attemptMarkAsRead();
|
||||
};
|
||||
|
||||
const handleWindowKeyUp = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
this.markAsRead();
|
||||
this.updateFirstUnreadRecordId();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleWindowFocus);
|
||||
window.addEventListener('keyup', handleWindowKeyUp);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('focus', handleWindowFocus);
|
||||
window.removeEventListener('keyup', handleWindowKeyUp);
|
||||
};
|
||||
};
|
||||
|
||||
private isUnreadMarkVisible: () => boolean = () => false;
|
||||
|
||||
public setIsUnreadMarkVisibleCallback(callback: () => boolean) {
|
||||
this.isUnreadMarkVisible = callback;
|
||||
}
|
||||
|
||||
// This will only mark as read if the unread mark is visible
|
||||
public attemptMarkAsRead() {
|
||||
const { alert, unread } = this.subscription || {};
|
||||
if (!alert && unread === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!document.hasFocus()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.firstUnreadRecordId && this.isUnreadMarkVisible() === false) {
|
||||
return;
|
||||
}
|
||||
// if there are unloaded unread messages, don't mark as read
|
||||
if (RoomHistoryManager.getRoom(this.rid).unreadNotLoaded > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.markAsRead();
|
||||
}
|
||||
|
||||
public debouncedMarkAsRead = withDebouncing({ wait: 1000 })(() => {
|
||||
try {
|
||||
return this.markAsRead();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
|
||||
// this will always mark as read.
|
||||
public async markAsRead() {
|
||||
if (!this.rid || !this.subscription?.rid) {
|
||||
return;
|
||||
}
|
||||
|
||||
return sdk.rest.post('/v1/subscriptions.read', { rid: this.rid }).then(() => {
|
||||
RoomHistoryManager.updateRoom(this.rid, { unreadNotLoaded: 0 });
|
||||
});
|
||||
}
|
||||
}
|
||||
219
apps/meteor/client/lib/chats/uploads.ts
Normal file
219
apps/meteor/client/lib/chats/uploads.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import type { IMessage, IRoom } from '@rocket.chat/core-typings';
|
||||
import { Emitter } from '@rocket.chat/emitter';
|
||||
import { Random } from '@rocket.chat/random';
|
||||
import fileSize from 'filesize';
|
||||
|
||||
import { getErrorMessage } from '../errorHandling';
|
||||
import type { UploadsAPI, EncryptedFileUploadContent } from './ChatAPI';
|
||||
import { isEncryptedUpload, type Upload } from './Upload';
|
||||
import { i18n } from '../../../app/utils/lib/i18n';
|
||||
import { sdk } from '../SDKClient';
|
||||
import { USER_ACTIVITIES, UserAction } from '../UserAction';
|
||||
import { settings } from '../settings';
|
||||
import { fileUploadIsValidContentType } from '../utils/restrictions';
|
||||
|
||||
class UploadsStore extends Emitter<{ update: void; [x: `cancelling-${Upload['id']}`]: void }> implements UploadsAPI {
|
||||
private rid: string;
|
||||
|
||||
private tmid?: string;
|
||||
|
||||
constructor({ rid, tmid }: { rid: IRoom['_id']; tmid?: IMessage['_id'] }) {
|
||||
super();
|
||||
this.rid = rid;
|
||||
this.tmid = tmid;
|
||||
}
|
||||
|
||||
private uploads: readonly Upload[] = [];
|
||||
|
||||
private processingUploads: boolean = false;
|
||||
|
||||
set = (uploads: Upload[]): void => {
|
||||
this.uploads = uploads;
|
||||
this.emit('update');
|
||||
};
|
||||
|
||||
get = (): readonly Upload[] => this.uploads;
|
||||
|
||||
subscribe = (callback: () => void): (() => void) => this.on('update', callback);
|
||||
|
||||
setProcessingUploads = (processing: boolean): void => {
|
||||
this.processingUploads = processing;
|
||||
this.emit('update');
|
||||
};
|
||||
|
||||
getProcessingUploads = (): boolean => this.processingUploads;
|
||||
|
||||
cancel = (id: Upload['id']): void => {
|
||||
this.emit(`cancelling-${id}`);
|
||||
};
|
||||
|
||||
wipeFailedOnes = (): void => {
|
||||
this.set(this.uploads.filter((upload) => !upload.error));
|
||||
};
|
||||
|
||||
private updateUpload(id: Upload['id'], patch: Partial<Upload>): void {
|
||||
this.set(this.uploads.map((upload) => (upload.id !== id ? upload : { ...upload, ...patch })));
|
||||
}
|
||||
|
||||
removeUpload = (id: Upload['id']): void => {
|
||||
this.set(this.uploads.filter((upload) => upload.id !== id));
|
||||
|
||||
if (this.uploads.length === 0) {
|
||||
UserAction.stop(this.rid, USER_ACTIVITIES.USER_UPLOADING, { tmid: this.tmid });
|
||||
}
|
||||
};
|
||||
|
||||
editUploadAltText = (uploadId: Upload['id'], altText: string) => {
|
||||
this.set(
|
||||
this.uploads.map((upload) => {
|
||||
if (upload.id !== uploadId) {
|
||||
return upload;
|
||||
}
|
||||
|
||||
return {
|
||||
...upload,
|
||||
altText,
|
||||
...(isEncryptedUpload(upload) && {
|
||||
metadataForEncryption: { ...upload.metadataForEncryption, altText },
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
editUploadFileName = (uploadId: Upload['id'], fileName: Upload['file']['name']) => {
|
||||
try {
|
||||
this.set(
|
||||
this.uploads.map((upload) => {
|
||||
if (upload.id !== uploadId) {
|
||||
return upload;
|
||||
}
|
||||
|
||||
return {
|
||||
...upload,
|
||||
file: new File([upload.file], fileName, upload.file),
|
||||
...(isEncryptedUpload(upload) && {
|
||||
metadataForEncryption: { ...upload.metadataForEncryption, name: fileName },
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
this.set(
|
||||
this.uploads.map((upload) => {
|
||||
if (upload.id !== uploadId) {
|
||||
return upload;
|
||||
}
|
||||
|
||||
return {
|
||||
...upload,
|
||||
percentage: 0,
|
||||
error: new Error(i18n.t('FileUpload_Update_Failed')),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
clear = () => {
|
||||
this.set([]);
|
||||
UserAction.stop(this.rid, USER_ACTIVITIES.USER_UPLOADING, { tmid: this.tmid });
|
||||
};
|
||||
|
||||
async send(file: File, encrypted?: EncryptedFileUploadContent): Promise<void> {
|
||||
const maxFileSize = settings.peek('FileUpload_MaxFileSize');
|
||||
const invalidContentType = !fileUploadIsValidContentType(encrypted ? encrypted.rawFile.type : file.type);
|
||||
const id = Random.id();
|
||||
|
||||
this.set([
|
||||
...this.uploads,
|
||||
{
|
||||
id,
|
||||
file: encrypted ? encrypted.rawFile : file,
|
||||
percentage: 0,
|
||||
...(encrypted && {
|
||||
encryptedFile: encrypted.encryptedFile,
|
||||
metadataForEncryption: encrypted.fileContent.raw,
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
if (file.size === 0) {
|
||||
return reject(new Error(i18n.t('FileUpload_File_Empty')));
|
||||
}
|
||||
|
||||
// -1 maxFileSize means there is no limit
|
||||
if (maxFileSize > -1 && (file.size || 0) > maxFileSize) {
|
||||
return reject(new Error(i18n.t('File_exceeds_allowed_size_of_bytes', { size: fileSize(maxFileSize) })));
|
||||
}
|
||||
|
||||
if (invalidContentType) {
|
||||
return reject(new Error(i18n.t('FileUpload_MediaType_NotAccepted__type__', { type: file.type })));
|
||||
}
|
||||
|
||||
const xhr = sdk.rest.upload(
|
||||
`/v1/rooms.media/${this.rid}`,
|
||||
{
|
||||
file,
|
||||
...(encrypted && {
|
||||
content: JSON.stringify(encrypted.fileContent.encrypted),
|
||||
}),
|
||||
},
|
||||
{
|
||||
load: (event) => {
|
||||
resolve(event);
|
||||
},
|
||||
progress: (event) => {
|
||||
if (!event.lengthComputable) {
|
||||
return;
|
||||
}
|
||||
const progress = (event.loaded / event.total) * 100;
|
||||
this.updateUpload(id, { percentage: Math.min(Math.round(progress), 99) || 0 });
|
||||
},
|
||||
error: (event) => {
|
||||
this.updateUpload(id, { percentage: 0, error: new Error(xhr.responseText) });
|
||||
reject(event);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
xhr.onload = () => {
|
||||
try {
|
||||
if (xhr.readyState !== xhr.DONE) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (xhr.status === 400) {
|
||||
const error = JSON.parse(xhr.responseText);
|
||||
this.updateUpload(id, { percentage: 0, error: new Error(error.error) });
|
||||
return;
|
||||
}
|
||||
|
||||
if (xhr.status === 200) {
|
||||
const result = JSON.parse(xhr.responseText);
|
||||
this.updateUpload(id, { id: result.file._id, url: result.file.url, percentage: 100 });
|
||||
return;
|
||||
}
|
||||
|
||||
this.updateUpload(id, { percentage: 0, error: new Error(i18n.t('FileUpload_Error')) });
|
||||
} catch (error) {
|
||||
this.updateUpload(id, { percentage: 0, error: new Error(getErrorMessage(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
this.once(`cancelling-${id}`, () => {
|
||||
xhr.abort();
|
||||
this.removeUpload(id);
|
||||
reject(new Error(i18n.t('FileUpload_Canceled')));
|
||||
});
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
this.updateUpload(id, { percentage: 0, error: new Error(getErrorMessage(error)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const createUploadsAPI = ({ rid, tmid }: { rid: IRoom['_id']; tmid?: IMessage['_id'] }): UploadsAPI =>
|
||||
new UploadsStore({ rid, tmid });
|
||||
Reference in New Issue
Block a user