-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathsendFileMessage.ts
More file actions
267 lines (241 loc) · 7.23 KB
/
sendFileMessage.ts
File metadata and controls
267 lines (241 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import type {
MessageAttachment,
FileAttachmentProps,
IUser,
IUpload,
AtLeast,
FilesAndAttachments,
IMessage,
FileProp,
} from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Logger } from '@rocket.chat/logger';
import { Rooms, Uploads, Users } from '@rocket.chat/models';
import { wrapExceptions } from '@rocket.chat/tools';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { callbacks } from '../../../../lib/callbacks';
import { getFileExtension } from '../../../../lib/utils/getFileExtension';
import { omit } from '../../../../lib/utils/omit';
import { SystemLogger } from '../../../../server/lib/logger/system';
import { canAccessRoomAsync } from '../../../authorization/server/functions/canAccessRoom';
import { executeSendMessage } from '../../../lib/server/methods/sendMessage';
import { FileUpload } from '../lib/FileUpload';
function validateFileRequiredFields(file: Partial<IUpload>): asserts file is AtLeast<IUpload, '_id' | 'name' | 'type' | 'size'> {
const requiredFields = ['_id', 'name', 'type', 'size'];
for (const field of requiredFields) {
if (!Object.keys(file).includes(field)) {
throw new Meteor.Error('error-invalid-file', 'Invalid file');
}
}
}
const logger = new Logger('sendFileMessage');
export const parseMultipleFilesIntoMessageAttachments = async (
filesToConfirm: Partial<IUpload>[],
roomId: string,
user: IUser,
): Promise<{ files: FileProp[]; attachments: MessageAttachment[] }> => {
const results = await Promise.all(
filesToConfirm.map((file) =>
wrapExceptions(() => parseFileIntoMessageAttachments(file, roomId, user)).catch(async (error) => {
// Not an important error, it should not happen and if it happens wil affect the attachment preview in the message object only
logger.warn({ msg: 'Error processing file: ', file, error });
return { files: [], attachments: [] };
}),
),
);
return {
files: results.flatMap(({ files }) => files),
attachments: results.flatMap(({ attachments }) => attachments),
};
};
export const parseFileIntoMessageAttachments = async (
file: Partial<IUpload>,
roomId: string,
user: IUser,
): Promise<FilesAndAttachments> => {
validateFileRequiredFields(file);
await Uploads.updateFileComplete(file._id, user._id, omit(file, '_id'));
const fileUrl = FileUpload.getPath(`${file._id}/${encodeURI(file.name || '')}`);
const attachments: MessageAttachment[] = [];
const files = [
{
_id: file._id,
name: file.name || '',
type: file.type || 'file',
size: file.size || 0,
format: file.identify?.format || '',
},
];
if (/^image\/.+/.test(file.type as string)) {
const attachment: FileAttachmentProps = {
title: file.name,
type: 'file',
description: file?.description,
title_link: fileUrl,
title_link_download: true,
image_url: fileUrl,
image_type: file.type as string,
image_size: file.size,
};
if (file.identify?.size) {
attachment.image_dimensions = file.identify.size;
}
try {
attachment.image_preview = await FileUpload.resizeImagePreview(file);
const thumbResult = await FileUpload.createImageThumbnail(file);
if (thumbResult) {
const { data: thumbBuffer, width, height, thumbFileType, thumbFileName, originalFileId } = thumbResult;
const thumbnail = await FileUpload.uploadImageThumbnail(
{
thumbFileName,
thumbFileType,
originalFileId,
},
thumbBuffer,
roomId,
user._id,
);
const thumbUrl = FileUpload.getPath(`${thumbnail._id}/${encodeURI(file.name || '')}`);
attachment.image_url = thumbUrl;
attachment.image_type = thumbnail.type;
attachment.image_dimensions = {
width,
height,
};
files.push({
_id: thumbnail._id,
name: thumbnail.name || '',
type: thumbnail.type || 'file',
size: thumbnail.size || 0,
format: thumbnail.identify?.format || '',
});
}
} catch (e) {
SystemLogger.error(e);
}
attachments.push(attachment);
} else if (/^audio\/.+/.test(file.type as string)) {
const attachment: FileAttachmentProps = {
title: file.name,
type: 'file',
description: file.description,
title_link: fileUrl,
title_link_download: true,
audio_url: fileUrl,
audio_type: file.type as string,
audio_size: file.size,
};
attachments.push(attachment);
} else if (/^video\/.+/.test(file.type as string)) {
const attachment: FileAttachmentProps = {
title: file.name,
type: 'file',
description: file.description,
title_link: fileUrl,
title_link_download: true,
video_url: fileUrl,
video_type: file.type as string,
video_size: file.size as number,
};
attachments.push(attachment);
} else {
const attachment = {
title: file.name,
type: 'file',
format: getFileExtension(file.name),
description: file.description,
title_link: fileUrl,
title_link_download: true,
size: file.size as number,
};
attachments.push(attachment);
}
return { files, attachments };
};
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
sendFileMessage: (roomId: string, _store: string, file: Partial<IUpload>, msgData?: Record<string, any>) => boolean;
}
}
export const sendFileMessage = async (
userId: string,
{
roomId,
file,
msgData,
}: {
roomId: string;
file: Partial<IUpload>;
msgData?: Record<string, any>;
},
{
parseAttachmentsForE2EE,
}: {
parseAttachmentsForE2EE: boolean;
} = {
parseAttachmentsForE2EE: true,
},
): Promise<boolean> => {
const user = await Users.findOneById(userId, { projection: { services: 0 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'sendFileMessage',
} as any);
}
const room = await Rooms.findOneById(roomId);
if (!room) {
return false;
}
if (user?.type !== 'app' && !(await canAccessRoomAsync(room, user))) {
return false;
}
check(
msgData,
Match.Maybe({
avatar: Match.Optional(String),
emoji: Match.Optional(String),
alias: Match.Optional(String),
groupable: Match.Optional(Boolean),
msg: Match.Optional(String),
tmid: Match.Optional(String),
customFields: Match.Optional(String),
t: Match.Optional(String),
content: Match.Optional(
Match.ObjectIncluding({
algorithm: String,
ciphertext: String,
}),
),
}),
);
const data = {
rid: roomId,
ts: new Date(),
...(msgData as Partial<IMessage>),
...(msgData?.customFields && { customFields: JSON.parse(msgData.customFields) }),
msg: msgData?.msg ?? '',
groupable: msgData?.groupable ?? false,
};
if (parseAttachmentsForE2EE || msgData?.t !== 'e2e') {
const { files, attachments } = await parseFileIntoMessageAttachments(file, roomId, user);
data.file = files[0];
data.files = files;
data.attachments = attachments;
}
const msg = await executeSendMessage(userId, data);
callbacks.runAsync('afterFileUpload', { user, room, message: msg });
return msg;
};
Meteor.methods<ServerMethods>({
async sendFileMessage(roomId, _store, file, msgData = {}) {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'sendFileMessage',
} as any);
}
return sendFileMessage(userId, { roomId, file, msgData });
},
});