Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: multiple file sharing in one message #2

Draft
wants to merge 174 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
174 commits
Select commit Hold shift + click to select a range
4ee6d2f
POC
rodrigok Apr 25, 2024
a1c0569
Initial service worker implementation
rodrigok Apr 26, 2024
640ed9e
Start changing the upload to two calls
rodrigok Apr 27, 2024
59d99a6
Start using content property in place of e2e
rodrigok Apr 28, 2024
d84ce58
Readd e2e property
rodrigok Apr 28, 2024
e6a4330
Client side attachment generation
rodrigok Apr 28, 2024
677f0ef
Cleanup
rodrigok Apr 28, 2024
7c7eb29
Encrypt content
rodrigok Apr 28, 2024
a9add79
Fix file description
rodrigok Apr 28, 2024
69f815e
Small improvements
rodrigok Apr 28, 2024
ebbe64f
Cleanup
rodrigok Apr 28, 2024
b43f57b
Cleanup
rodrigok Apr 28, 2024
ec06eb3
Improve TS
rodrigok Apr 28, 2024
f70d2e1
Change content data structure
rodrigok Apr 30, 2024
445c528
Move attachment key info to inside encryption property
rodrigok Apr 30, 2024
6daab1a
Set encrypted file name as a hash sha-256 of the name
rodrigok Apr 30, 2024
d14a0e0
Merge remote-tracking branch 'origin/develop' into feat/encrypted-files
rodrigok Apr 30, 2024
fd5fcd2
Fix lint and TS
rodrigok Apr 30, 2024
2e1f78a
Fix regression
rodrigok Apr 30, 2024
d307519
Merge branch 'develop' into feat/encrypted-files
rodrigok May 9, 2024
1e25638
Mark uploads as temporary and confirm on send message
rodrigok May 9, 2024
574169f
Fix API test
rodrigok May 9, 2024
7154756
Implement cronjob
rodrigok May 10, 2024
222cbf3
Merge branch 'develop' into feat/encrypted-files
rodrigok May 10, 2024
aff80f3
Skip UI attachment test for now
rodrigok May 10, 2024
de5f0f2
Do not generate attachment on backend for e2ee messages
rodrigok May 10, 2024
939940d
Download through serviceworker
ggazzo May 14, 2024
7fb9618
Merge remote-tracking branch 'origin/develop' into feat/encrypted-files
rodrigok May 14, 2024
26e2eb8
👀
ggazzo May 15, 2024
3234c56
Merge branch 'develop' into feat/encrypted-files
MarcosSpessatto May 25, 2024
d894d30
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 10, 2024
aacf63d
testing with e2e
abhipatel0211 Jun 12, 2024
ee3fe8a
Move encryption of msg to inside content
rodrigok Jun 12, 2024
956316e
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 12, 2024
13566ab
Merge remote-tracking branch 'upstream/feat/encrypted-files' into fea…
abhipatel0211 Jun 13, 2024
611f91e
Merge branch 'RocketChat:develop' into feat/encrypted-file
abhipatel0211 Jun 13, 2024
48a97f7
Fix placeholder message for threads
rodrigok Jun 13, 2024
446b1a7
Unskip test
rodrigok Jun 13, 2024
35363b6
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 13, 2024
c258b21
Fix ts
rodrigok Jun 13, 2024
989c61c
Fix tests
rodrigok Jun 13, 2024
0a3cb4d
Merge remote-tracking branch 'upstream/feat/encrypted-files' into fea…
abhipatel0211 Jun 14, 2024
403ced3
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 14, 2024
ae670ff
Merge branch 'RocketChat:develop' into feat/encrypted-file
abhipatel0211 Jun 14, 2024
de94f83
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 14, 2024
9da9640
Add test for old e2ee msg format
rodrigok Jun 14, 2024
8c7310f
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 18, 2024
5228bdb
Add tests for new upload API
rodrigok Jun 18, 2024
9e83634
Save encrypted content info to the file upload
rodrigok Jun 19, 2024
8f81edd
Add dimensions to image attachments
rodrigok Jun 19, 2024
b9ff006
Fix TS
rodrigok Jun 19, 2024
9a39914
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 19, 2024
20962c4
Fix tests
rodrigok Jun 19, 2024
74cfee1
Fix image preview
rodrigok Jun 19, 2024
6508ebe
Prevent keys to be set on top of existent keys
rodrigok Jun 19, 2024
1a1788e
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 19, 2024
64a27cb
Fix API tests
rodrigok Jun 19, 2024
b5e1ba5
Fix e2ee change password
rodrigok Jun 19, 2024
f108fd4
Fix TS
rodrigok Jun 19, 2024
ae76481
Fix API tests
rodrigok Jun 19, 2024
18d0e87
Decrypt room's last message correctly
rodrigok Jun 19, 2024
e984ad2
Merge remote-tracking branch 'origin/develop' into feat/encrypted-files
rodrigok Jun 19, 2024
c251e17
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 19, 2024
a96fa61
Try to fix tests
rodrigok Jun 19, 2024
3f480b0
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 19, 2024
fa2456a
Fix tests
rodrigok Jun 20, 2024
365cef8
Fix preview of encrypted files
rodrigok Jun 20, 2024
bd90357
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 20, 2024
81dad69
Fix download button
rodrigok Jun 20, 2024
8402305
Fix download from files list
rodrigok Jun 20, 2024
503218e
Merge branch 'develop' into feat/encrypted-files
rodrigok Jun 20, 2024
09e3bb7
Force cors on SW
rodrigok Jun 20, 2024
f6162af
Merge remote-tracking branch 'upstream/feat/encrypted-files' into fea…
abhipatel0211 Jun 21, 2024
b739659
feat: multiple file sharing feature with encryption
abhipatel0211 Jun 29, 2024
a1f7848
Merge remote-tracking branch 'upstream/develop' into e2e_multiple_mer…
abhipatel0211 Jun 29, 2024
74ed1f2
fix: file name issue
abhipatel0211 Jun 29, 2024
cbb41bb
Merge branch 'develop' into feat/multiple_files_in_one_msg
rodrigok Jul 5, 2024
c93da30
multiple files shared one at a time
abhipatel0211 Jul 7, 2024
cfc177c
Change message API to handle file upload
abhipatel0211 Jul 16, 2024
2e344a1
fix: Ensure correct preview of multiple images in shared in single me…
abhipatel0211 Jul 17, 2024
7f0b615
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Jul 18, 2024
671fd31
solved merge conflict
abhipatel0211 Jul 18, 2024
8379c94
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Jul 25, 2024
9a97c3d
fix: type error of fileContent and remove extra code
abhipatel0211 Jul 25, 2024
62fbc56
added support for single file upload
abhipatel0211 Jul 31, 2024
f88cd26
UI update added cross button on hover and added the functionality of …
abhipatel0211 Jul 31, 2024
f39042b
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 6, 2024
5a9f646
merge develop
abhipatel0211 Aug 6, 2024
771314e
feat: Added a file upload preview inside the messageBox
abhipatel0211 Aug 7, 2024
755c08b
Fix issue in uploads.ts causing duplicate messages on send
abhipatel0211 Aug 7, 2024
f2bd552
Cleanup: Remove unnecessary code
abhipatel0211 Aug 7, 2024
39ff2a3
removed unused space
abhipatel0211 Aug 7, 2024
23eb009
fix: lint errors
abhipatel0211 Aug 8, 2024
e786f70
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 8, 2024
f4b60d5
fix: lint and TS errors
abhipatel0211 Aug 8, 2024
1c0ddde
fix: ensure file handling as array to resolve type errors in uploads
abhipatel0211 Aug 8, 2024
f5213b0
fix: lint error and TS errors
abhipatel0211 Aug 8, 2024
6f398b4
fix: lint and TS errors
abhipatel0211 Aug 8, 2024
cdc0ff5
removed unused code
abhipatel0211 Aug 8, 2024
a1faa22
fix: reorder imports to fix ESLint errors and removed unused changes
abhipatel0211 Aug 8, 2024
326a197
fix: changed the variable name with camelCase and removed unwanted ch…
abhipatel0211 Aug 8, 2024
c078083
fix: changed variable names to cameCase
abhipatel0211 Aug 8, 2024
0e4d827
fix: added toast message while uploading file
abhipatel0211 Aug 9, 2024
60a80f9
Added the files to upload in the sendMessage in the executeSendMessage
abhipatel0211 Aug 10, 2024
7ac5841
fix: Revert back as using message API
abhipatel0211 Aug 10, 2024
9f74219
Removed unused import
abhipatel0211 Aug 10, 2024
9afeee6
Remove unwanted code
abhipatel0211 Aug 10, 2024
97f743b
Added defineProperty for all the files selected
abhipatel0211 Aug 12, 2024
68f45dc
Added different function for files and encrypted files sharing
abhipatel0211 Aug 13, 2024
d7b92cc
changed uploadFiles.ts and FileUploadModal.tsx to handle single file …
abhipatel0211 Aug 13, 2024
21005c0
Merge branch 'develop' into feat/multiple_files_in_one_msg
rodrigok Aug 13, 2024
a0f6c83
Added the type check for the filesToUpload and also removed the refer…
abhipatel0211 Aug 14, 2024
de319d8
Added isUploading and removed the unnecessary changes
abhipatel0211 Aug 14, 2024
3ad5e63
Added a folder of FilePreview near the messageBox and also changed th…
abhipatel0211 Aug 15, 2024
72bc00d
feat: Enable file attachments after typing a message
abhipatel0211 Aug 16, 2024
fbd30c9
Merge remote-tracking branch 'upstream/develop' into dev_feat/multipl…
abhipatel0211 Aug 16, 2024
fe2b428
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 16, 2024
b3db9fc
added title to the generic and image preview
abhipatel0211 Aug 16, 2024
3aa8c3d
fix: issue while sharing the message after file shared
abhipatel0211 Aug 17, 2024
2eb9b64
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 18, 2024
11aac8e
passed uploadIdsToConfirm to the sendMessage in executeSendMessage
abhipatel0211 Aug 18, 2024
9ff1b9f
Added newe function parseMultipleFilesIntoMessageAttachments
abhipatel0211 Aug 18, 2024
2370b14
added ui changes and also added the transition
abhipatel0211 Aug 19, 2024
47b592e
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 19, 2024
9722194
shifted confirm files at last after save message and attached multipl…
abhipatel0211 Aug 21, 2024
84bfcae
fix: image thumbnail display and remove extra msgData parameter
abhipatel0211 Aug 22, 2024
335e886
removed console logs
abhipatel0211 Aug 22, 2024
a5598f7
added a function for parse and also solved eslint error of reshuffling
abhipatel0211 Aug 22, 2024
7ea18d7
fix: solved lint errors messageBox and uploadfiles
abhipatel0211 Aug 23, 2024
822e2c5
fix: lint and TS errors
abhipatel0211 Aug 23, 2024
d1b6922
fix: lint error and converted description to msg
abhipatel0211 Aug 23, 2024
b13bdd2
fix: added description for TS error
abhipatel0211 Aug 23, 2024
a8cff84
Merge branch 'develop' into feat/multiple_files_in_one_msg
rodrigok Aug 23, 2024
0fe3aee
Changed the location of parsing file into attachments and also added …
abhipatel0211 Aug 24, 2024
7347447
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Aug 24, 2024
65c7be7
fix: maintain file upload order to ensure consistent fileId, fileUrl …
abhipatel0211 Aug 31, 2024
c4fb104
Added different function for file upload
abhipatel0211 Aug 31, 2024
12abfc5
removed unnecessary changes
abhipatel0211 Sep 2, 2024
ed463c0
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Sep 2, 2024
8c91c8c
added file which upload the file and return back the file IDs and fil…
abhipatel0211 Sep 3, 2024
7e5081b
fix: added condition so it will remove extra space
abhipatel0211 Sep 5, 2024
e45e376
feat: Add drag-and-drop file upload to message box
abhipatel0211 Sep 8, 2024
d21dd7f
fix: added encryption of message also
abhipatel0211 Sep 11, 2024
8508954
fix: Issue inside the thread messages
abhipatel0211 Sep 20, 2024
ea689a2
fix: multiple dispatch messages
abhipatel0211 Sep 20, 2024
ce5b7dd
Merge branch 'feat/multiple_files_in_one_msg' into dev_feat/multiple_…
abhipatel0211 Sep 21, 2024
7a2324a
Merge remote-tracking branch 'upstream/develop' into dev_feat/multipl…
abhipatel0211 Sep 21, 2024
acdf3c1
removed onFileDrop as using setFilesToUpload
abhipatel0211 Sep 21, 2024
ca89baf
Merge branch 'develop' into dev_feat/multiple_files_in_one_msg
abhipatel0211 Sep 24, 2024
1ccc5f8
Merge branch 'develop' into feat/multiple_files_in_one_msg
abhipatel0211 Sep 24, 2024
724856b
Merge branch 'feat/multiple_files_in_one_msg' into dev_feat/multiple_…
abhipatel0211 Sep 27, 2024
f1ea0da
testing test
abhipatel0211 Oct 2, 2024
1d92433
Merge remote-tracking branch 'upstream/develop' into dev_feat/multipl…
abhipatel0211 Oct 2, 2024
8ce9034
return to old test
abhipatel0211 Oct 2, 2024
4437083
Merge remote-tracking branch 'upstream/develop' into dev_feat/multipl…
abhipatel0211 Oct 3, 2024
5f22315
fix: remove selected files when in edit mode
abhipatel0211 Oct 5, 2024
19df253
fix: diabled file sharing while editing
abhipatel0211 Oct 6, 2024
9d12bf6
Merge branch 'feat/multiple_files_in_one_msg' into dev_feat/multiple_…
abhipatel0211 Oct 6, 2024
71135f1
Merge remote-tracking branch 'upstream/develop' into feat/multiple_fi…
abhipatel0211 Oct 7, 2024
bbdd7a5
Merge branch 'develop' into feat/multiple_files_in_one_msg
abhipatel0211 Oct 9, 2024
ec6a12f
fix:TS_error_resolved
abhipatel0211 Oct 9, 2024
beb5723
Merge remote-tracking branch 'upstream/develop' into dev_feat/multipl…
abhipatel0211 Oct 11, 2024
d9a7452
Merge branch 'develop' into dev_feat/multiple_files_in_one_msg
abhipatel0211 Oct 15, 2024
176d676
Merge branch 'dev_feat/multiple_files_in_one_msg' into feat/multiple_…
abhipatel0211 Oct 15, 2024
056bfed
fix: Trans error
abhipatel0211 Oct 15, 2024
5dbdfc6
Merge branch 'develop' into dev_feat/multiple_files_in_one_msg
abhipatel0211 Oct 26, 2024
d68c421
Merge branch 'develop' into test_feat/multiple_files
abhipatel0211 Oct 26, 2024
11e6002
Merge branch 'develop' into feat/multiple_files_in_one_msg
abhipatel0211 Oct 26, 2024
d7e71b9
Merge branch 'develop' into dev_feat/multiple_files_in_one_msg
abhipatel0211 Oct 26, 2024
65e39c5
Merge branch 'develop' into test_feat/multiple_files
abhipatel0211 Oct 26, 2024
9fba829
Restore deleted subscriptions.ts file
abhipatel0211 Oct 26, 2024
945a224
Merge branch 'test_feat/multiple_files' into dev_feat/multiple_files_…
abhipatel0211 Oct 26, 2024
c060422
Merge branch 'dev_feat/multiple_files_in_one_msg' into feat/multiple_…
abhipatel0211 Oct 26, 2024
3cc6b17
Merge branch 'develop' into feat/multiple_files_in_one_msg
abhipatel0211 Nov 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions apps/meteor/app/file-upload/server/methods/sendFileMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
AtLeast,
FilesAndAttachments,
IMessage,
FileProp,
} from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms, Uploads, Users } from '@rocket.chat/models';
Expand All @@ -29,6 +30,38 @@ function validateFileRequiredFields(file: Partial<IUpload>): asserts file is AtL
});
}

export const parseMultipleFilesIntoMessageAttachments = async (
filesToConfirm: Partial<IUpload>[],
roomId: string,
user: IUser,
): Promise<{ files: FileProp[]; attachments: MessageAttachment[] }> => {
const messageFiles: FileProp[] = [];
const messageAttachments: MessageAttachment[] = [];

const filesAndAttachments = await Promise.all(
filesToConfirm
.filter((files: Partial<IUpload>) => !!files)
.map(async (file) => {
try {
const { files, attachments } = await parseFileIntoMessageAttachments(file, roomId, user);
return { files, attachments };
} catch (error) {
console.error('Error processing file:', file, error);
return { files: [], attachments: [] };
}
}),
);

filesAndAttachments
.filter(({ files, attachments }) => files.length || attachments.length)
.forEach(({ files, attachments }) => {
messageFiles.push(...files);
messageAttachments.push(...attachments);
});

return { files: messageFiles, attachments: messageAttachments };
};

export const parseFileIntoMessageAttachments = async (
file: Partial<IUpload>,
roomId: string,
Expand Down
35 changes: 32 additions & 3 deletions apps/meteor/app/lib/server/functions/sendMessage.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Apps } from '@rocket.chat/apps';
import { api, Message } from '@rocket.chat/core-services';
import type { IMessage, IRoom } from '@rocket.chat/core-typings';
import { Messages } from '@rocket.chat/models';
import type { IMessage, IRoom, IUpload } from '@rocket.chat/core-typings';
import { Messages, Uploads } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';

import { isRelativeURL } from '../../../../lib/utils/isRelativeURL';
import { isURL } from '../../../../lib/utils/isURL';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { FileUpload } from '../../../file-upload/server';
import { parseMultipleFilesIntoMessageAttachments } from '../../../file-upload/server/methods/sendFileMessage';
import { settings } from '../../../settings/server';
import { afterSaveMessage } from '../lib/afterSaveMessage';
import { notifyOnRoomChangedById, notifyOnMessageChange } from '../lib/notifyListener';
Expand Down Expand Up @@ -215,11 +216,35 @@ export function prepareMessageObject(
/**
* Validates and sends the message object.
*/
export const sendMessage = async function (user: any, message: any, room: any, upsert = false, previewUrls?: string[]) {
export const sendMessage = async function (
user: any,
message: any,
room: any,
upsert = false,
previewUrls?: string[],
uploadIdsToConfirm?: string[],
) {
if (!user || !message || !room._id) {
return false;
}

if (uploadIdsToConfirm !== undefined) {
const filesToConfirm: Partial<IUpload>[] = await Promise.all(
uploadIdsToConfirm.map(async (fileid) => {
const file = await Uploads.findOneById(fileid);
if (!file) {
throw new Meteor.Error('invalid-file');
}
return file;
}),
);
if (message?.t !== 'e2e') {
const { files, attachments } = await parseMultipleFilesIntoMessageAttachments(filesToConfirm, message.rid, user);
message.files = files;
message.attachments = attachments;
}
}

await validateMessage(message, room, user);
prepareMessageObject(message, room._id, user);

Expand Down Expand Up @@ -292,6 +317,10 @@ export const sendMessage = async function (user: any, message: any, room: any, u
// TODO: is there an opportunity to send returned data to notifyOnMessageChange?
await afterSaveMessage(message, room);

if (uploadIdsToConfirm !== undefined) {
await Promise.all(uploadIdsToConfirm.map((fileid) => Uploads.confirmTemporaryFile(fileid, user._id)));
}

void notifyOnMessageChange({ id: message._id });

void notifyOnRoomChangedById(message.rid);
Expand Down
15 changes: 10 additions & 5 deletions apps/meteor/app/lib/server/methods/sendMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ import { MessageTypes } from '../../../ui-utils/server';
import { sendMessage } from '../functions/sendMessage';
import { RateLimiter } from '../lib';

export async function executeSendMessage(uid: IUser['_id'], message: AtLeast<IMessage, 'rid'>, previewUrls?: string[]) {
export async function executeSendMessage(
uid: IUser['_id'],
message: AtLeast<IMessage, 'rid'>,
previewUrls?: string[],
uploadIdsToConfirm?: string[],
) {
if (message.tshow && !message.tmid) {
throw new Meteor.Error('invalid-params', 'tshow provided but missing tmid', {
method: 'sendMessage',
Expand Down Expand Up @@ -96,7 +101,7 @@ export async function executeSendMessage(uid: IUser['_id'], message: AtLeast<IMe
}

metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736
return await sendMessage(user, message, room, false, previewUrls);
return await sendMessage(user, message, room, false, previewUrls, uploadIdsToConfirm);
} catch (err: any) {
SystemLogger.error({ msg: 'Error sending message:', err });

Expand All @@ -117,12 +122,12 @@ export async function executeSendMessage(uid: IUser['_id'], message: AtLeast<IMe
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
sendMessage(message: AtLeast<IMessage, '_id' | 'rid' | 'msg'>, previewUrls?: string[]): any;
sendMessage(message: AtLeast<IMessage, '_id' | 'rid' | 'msg'>, previewUrls?: string[], uploadIdsToConfirm?: string[]): any;
}
}

Meteor.methods<ServerMethods>({
async sendMessage(message, previewUrls) {
async sendMessage(message, previewUrls, uploadIdsToConfirm) {
check(message, Object);

const uid = Meteor.userId();
Expand All @@ -137,7 +142,7 @@ Meteor.methods<ServerMethods>({
}

try {
return await applyAirGappedRestrictionsValidation(() => executeSendMessage(uid, message, previewUrls));
return await applyAirGappedRestrictionsValidation(() => executeSendMessage(uid, message, previewUrls, uploadIdsToConfirm));
} catch (error: any) {
if (['error-not-allowed', 'restricted-workspace'].includes(error.error || error.message)) {
throw new Meteor.Error(error.error || error.message, error.reason, {
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/client/lib/chats/ChatAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ export type UploadsAPI = {
wipeFailedOnes(): void;
cancel(id: Upload['id']): void;
send(
file: File,
file: File[] | File,
{ description, msg, t, e2e }: { description?: string; msg?: string; t?: IMessage['t']; e2e?: IMessage['e2e'] },
getContent?: (fileId: string, fileUrl: string) => Promise<IE2EEMessage['content']>,
fileContent?: { raw: Partial<IUpload>; encrypted: IE2EEMessage['content'] },
getContent?: (fileId: string[], fileUrl: string[]) => Promise<IE2EEMessage['content']>,
fileContent?: { raw: Partial<IUpload>; encrypted?: { algorithm: string; ciphertext: string } | undefined },
): Promise<void>;
};

Expand Down
6 changes: 4 additions & 2 deletions apps/meteor/client/lib/chats/flows/uploadFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const uploadFiles = async (chat: ChatAPI, files: readonly File[], resetFi
const uploadFile = (
file: File,
extraData?: Pick<IMessage, 't' | 'e2e'> & { description?: string },
getContent?: (fileId: string, fileUrl: string) => Promise<IE2EEMessage['content']>,
getContent?: (fileId: string[], fileUrl: string[]) => Promise<IE2EEMessage['content']>,
fileContent?: { raw: Partial<IUpload>; encrypted: IE2EEMessage['content'] },
) => {
chat.uploads.send(
Expand Down Expand Up @@ -99,8 +99,10 @@ export const uploadFiles = async (chat: ChatAPI, files: readonly File[], resetFi
const encryptedFile = await e2eRoom.encryptFile(file);

if (encryptedFile) {
const getContent = async (_id: string, fileUrl: string): Promise<IE2EEMessage['content']> => {
const getContent = async (filesId: string[], filesUrl: string[]): Promise<IE2EEMessage['content']> => {
const attachments = [];
const _id = filesId[0];
const fileUrl = filesUrl[0];

const attachment: FileAttachmentProps = {
title: file.name,
Expand Down
143 changes: 143 additions & 0 deletions apps/meteor/client/lib/chats/uploadFilesAndGetIdsandURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import type { IUpload } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import { Random } from '@rocket.chat/random';

import { UserAction, USER_ACTIVITIES } from '../../../app/ui/client/lib/UserAction';
import { sdk } from '../../../app/utils/client/lib/SDKClient';
import { getErrorMessage } from '../errorHandling';
import type { Upload } from './Upload';

let uploads: readonly Upload[] = [];

const emitter = new Emitter<{ update: void; [x: `cancelling-${Upload['id']}`]: void }>();

const updateUploads = (update: (uploads: readonly Upload[]) => readonly Upload[]): void => {
uploads = update(uploads);
emitter.emit('update');
};
export const uploadAndGetIds = async (
file: File,
{
rid,
tmid,
fileContent,
}: {
rid: string;
tmid?: string;
fileContent?: { raw: Partial<IUpload>; encrypted?: { algorithm: string; ciphertext: string } | undefined };
},
): Promise<{ fileId: string; fileUrl: string }> => {
const id = Random.id();

updateUploads((uploads) => [
...uploads,
{
id,
name: fileContent?.raw.name || file.name,
percentage: 0,
},
]);

try {
const result = await new Promise<{ fileId: string; fileUrl: string }>((resolve, reject) => {
const xhr = sdk.rest.upload(
`/v1/rooms.media/${rid}`,
{
file,
...(fileContent && {
content: JSON.stringify(fileContent.encrypted),
}),
},
{
load: (event) => {
console.log('from uploadfiles event', event);
},
progress: (event) => {
if (!event.lengthComputable) {
return;
}
const progress = (event.loaded / event.total) * 100;
if (progress === 100) {
return;
}

updateUploads((uploads) =>
uploads.map((upload) => {
if (upload.id !== id) {
return upload;
}

return {
...upload,
percentage: Math.round(progress) || 0,
};
}),
);
},
error: (event) => {
updateUploads((uploads) =>
uploads.map((upload) => {
if (upload.id !== id) {
return upload;
}

return {
...upload,
percentage: 0,
error: new Error(xhr.responseText),
};
}),
);
reject(event);
},
},
);

xhr.onload = () => {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);

resolve({
fileId: response.file._id,
fileUrl: response.file.url,
});
} else {
reject(new Error('File upload failed.'));
}
};

if (uploads.length) {
UserAction.performContinuously(rid, USER_ACTIVITIES.USER_UPLOADING, { tmid });
}

emitter.once(`cancelling-${id}`, () => {
xhr.abort();
updateUploads((uploads) => uploads.filter((upload) => upload.id !== id));
reject(new Error('Upload cancelled.'));
});
});

updateUploads((uploads) => uploads.filter((upload) => upload.id !== id));

return result;
} catch (error: unknown) {
updateUploads((uploads) =>
uploads.map((upload) => {
if (upload.id !== id) {
return upload;
}

return {
...upload,
percentage: 0,
error: new Error(getErrorMessage(error)),
};
}),
);
throw error;
} finally {
if (!uploads.length) {
UserAction.stop(rid, USER_ACTIVITIES.USER_UPLOADING, { tmid });
}
}
};
Loading
Loading