-
Notifications
You must be signed in to change notification settings - Fork 11.7k
/
Copy pathdata.ts
336 lines (259 loc) · 9.59 KB
/
data.ts
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import type { IEditedMessage, IMessage, IRoom, ISubscription } from '@rocket.chat/core-typings';
import { Random } from '@rocket.chat/random';
import moment from 'moment';
import { hasAtLeastOnePermission, hasPermission } from '../../../app/authorization/client';
import { Messages, ChatRoom, ChatSubscription } from '../../../app/models/client';
import { settings } from '../../../app/settings/client';
import { MessageTypes } from '../../../app/ui-utils/client';
import { sdk } from '../../../app/utils/client/lib/SDKClient';
import { prependReplies } from '../utils/prependReplies';
import type { DataAPI } from './ChatAPI';
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.findOne({ _id: mid, _hidden: { $ne: true } }, { reactive: false }) ?? sdk.call('getSingleMessage', mid);
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.findOne({ rid, tmid: tmid ?? { $exists: false }, _hidden: { $ne: true } }, { sort: { ts: -1 }, reactive: false });
const getLastMessage = async (): Promise<IMessage> => {
const message = await findLastMessage();
if (!message) {
throw new Error('Message not found');
}
return message;
};
const findLastOwnMessage = async (): Promise<IMessage | undefined> => {
const uid = Meteor.userId();
if (!uid) {
return undefined;
}
return Messages.findOne(
{ rid, 'tmid': tmid ?? { $exists: false }, 'u._id': uid, '_hidden': { $ne: true } },
{ sort: { ts: -1 }, reactive: false },
);
};
const getLastOwnMessage = async (): Promise<IMessage> => {
const message = await findLastOwnMessage();
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.get('Message_AllowEditing') as boolean | undefined) ?? false;
const editOwn = message?.u && message.u._id === Meteor.userId();
if (!canEditMessage && (!editAllowed || !editOwn)) {
return false;
}
const blockEditInMinutes = settings.get('Message_AllowEditing_BlockEditInMinutes') as number | undefined;
const bypassBlockTimeLimit = hasPermission('bypass-time-limit-edit-and-delete', message.rid);
const elapsedMinutes = moment().diff(message.ts, 'minutes');
if (!bypassBlockTimeLimit && elapsedMinutes && blockEditInMinutes && elapsedMinutes > blockEditInMinutes) {
return false;
}
return true;
};
const findPreviousOwnMessage = async (message: IMessage): Promise<IMessage | undefined> => {
const uid = Meteor.userId();
if (!uid) {
return undefined;
}
const msg = Messages.findOne(
{ rid, 'tmid': tmid ?? { $exists: false }, 'u._id': uid, '_hidden': { $ne: true }, 'ts': { $lt: message.ts } },
{ sort: { ts: -1 }, reactive: false },
);
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 = Meteor.userId();
if (!uid) {
return undefined;
}
const msg = Messages.findOne(
{ rid, 'tmid': tmid ?? { $exists: false }, 'u._id': uid, '_hidden': { $ne: true }, 'ts': { $gt: message.ts } },
{ sort: { ts: 1 }, reactive: false },
);
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> => {
Messages.upsert({ _id: message._id }, { $set: { ...message, rid, ...(tmid && { tmid }) } });
};
const updateMessage = async (message: IEditedMessage, previewUrls?: string[]): Promise<void> =>
sdk.call('updateMessage', message, previewUrls);
const canDeleteMessage = async (message: IMessage): Promise<boolean> => {
const uid = Meteor.userId();
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.get('Message_AllowDeleting') as boolean | undefined;
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 === Meteor.userId());
if (!deleteAllowed) {
return false;
}
const blockDeleteInMinutes = settings.get('Message_AllowDeleting_BlockDeleteInMinutes') as number | undefined;
const bypassBlockTimeLimit = hasPermission('bypass-time-limit-edit-and-delete', message.rid);
const elapsedMinutes = moment().diff(message.ts, 'minutes');
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> => ChatRoom.findOne({ _id: rid }, { reactive: false });
const getRoom = async (): Promise<IRoom> => {
const room = await findRoom();
if (!room) {
throw new Error('Room not found');
}
return room;
};
const isSubscribedToRoom = async (): Promise<boolean> => !!ChatSubscription.findOne({ rid }, { reactive: false });
const joinRoom = async (): Promise<void> => {
await sdk.call('joinRoom', rid);
};
const findDiscussionByID = async (drid: IRoom['_id']): Promise<IRoom | undefined> =>
ChatRoom.findOne({ _id: drid, prid: { $exists: true } }, { reactive: false });
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 ChatSubscription.findOne({ rid }, { reactive: false });
};
const getSubscription = createStrictGetter(findSubscription, 'Subscription not found');
const findSubscriptionFromMessage = async (message: IMessage): Promise<ISubscription | undefined> => {
return ChatSubscription.findOne({ rid: message.rid }, { reactive: false });
};
const getSubscriptionFromMessage = createStrictGetter(findSubscriptionFromMessage, 'Subscription not found');
return {
composeMessage,
findMessageByID,
getMessageByID,
findLastMessage,
getLastMessage,
findLastOwnMessage,
getLastOwnMessage,
findPreviousOwnMessage,
getPreviousOwnMessage,
findNextOwnMessage,
getNextOwnMessage,
pushEphemeralMessage,
canUpdateMessage,
updateMessage,
canDeleteMessage,
deleteMessage,
getDraft,
saveDraft,
discardDraft,
findRoom,
getRoom,
isSubscribedToRoom,
joinRoom,
findDiscussionByID,
getDiscussionByID,
findSubscription,
getSubscription,
findSubscriptionFromMessage,
getSubscriptionFromMessage,
};
};