-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathim.ts
More file actions
666 lines (562 loc) · 17.6 KB
/
im.ts
File metadata and controls
666 lines (562 loc) · 17.6 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
* Docs: https://github.com/RocketChat/developer-docs/blob/master/reference/api/rest-api/endpoints/team-collaboration-endpoints/im-endpoints
*/
import type { IMessage, IRoom, ISubscription, IUser } from '@rocket.chat/core-typings';
import { Subscriptions, Uploads, Messages, Rooms, Users } from '@rocket.chat/models';
import {
ajv,
validateUnauthorizedErrorResponse,
validateBadRequestErrorResponse,
isDmFileProps,
isDmMemberProps,
isDmMessagesProps,
isDmCreateProps,
isDmHistoryProps,
} from '@rocket.chat/rest-typings';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import type { FindOptions } from 'mongodb';
import { eraseRoom } from '../../../../server/lib/eraseRoom';
import { openRoom } from '../../../../server/lib/openRoom';
import { createDirectMessage } from '../../../../server/methods/createDirectMessage';
import { hideRoomMethod } from '../../../../server/methods/hideRoom';
import { canAccessRoomIdAsync } from '../../../authorization/server/functions/canAccessRoom';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { saveRoomSettings } from '../../../channel-settings/server/methods/saveRoomSettings';
import { getRoomByNameOrIdWithOptionToJoin } from '../../../lib/server/functions/getRoomByNameOrIdWithOptionToJoin';
import { getChannelHistory } from '../../../lib/server/methods/getChannelHistory';
import { settings } from '../../../settings/server';
import { normalizeMessagesForUser } from '../../../utils/server/lib/normalizeMessagesForUser';
import type { ExtractRoutesFromAPI } from '../ApiClass';
import { API } from '../api';
import type { TypedAction } from '../definition';
import { addUserToFileObj } from '../helpers/addUserToFileObj';
import { composeRoomWithLastMessage } from '../helpers/composeRoomWithLastMessage';
import { getPaginationItems } from '../helpers/getPaginationItems';
const findDirectMessageRoom = async (
keys: { roomId?: string; username?: string },
uid: string,
): Promise<{ room: IRoom; subscription: ISubscription | null }> => {
const nameOrId = 'roomId' in keys ? keys.roomId : keys.username;
if (typeof nameOrId !== 'string') {
throw new Meteor.Error('error-room-param-not-provided', 'Query param "roomId" or "username" is required');
}
const user = await Users.findOneById(uid, { projection: { username: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'findDirectMessageRoom',
});
}
const room = await getRoomByNameOrIdWithOptionToJoin({
user,
nameOrId,
type: 'd',
});
if (!room || room?.t !== 'd') {
throw new Meteor.Error('error-room-not-found', 'The required "roomId" param provided does not match any direct message');
}
const subscription = await Subscriptions.findOne({ 'rid': room._id, 'u._id': uid });
return {
room,
subscription,
};
};
API.v1.addRoute(
['dm.create', 'im.create'],
{
authRequired: true,
validateParams: isDmCreateProps,
},
{
async post() {
const users =
'username' in this.bodyParams
? [this.bodyParams.username]
: this.bodyParams.usernames.split(',').map((username: string) => username.trim());
const room = await createDirectMessage(users, this.userId, this.bodyParams.excludeSelf);
return API.v1.success({
room: { ...room, _id: room.rid },
});
},
},
);
type DmDeleteProps =
| {
roomId: string;
}
| {
username: string;
};
const isDmDeleteProps = ajv.compile<DmDeleteProps>({
oneOf: [
{
type: 'object',
properties: {
roomId: {
type: 'string',
},
},
required: ['roomId'],
additionalProperties: false,
},
{
type: 'object',
properties: {
username: {
type: 'string',
},
},
required: ['username'],
additionalProperties: false,
},
],
});
const dmDeleteEndpointsProps = {
authRequired: true,
body: isDmDeleteProps,
response: {
400: validateBadRequestErrorResponse,
401: validateUnauthorizedErrorResponse,
200: ajv.compile<void>({
type: 'object',
properties: {
success: {
type: 'boolean',
enum: [true],
},
},
required: ['success'],
additionalProperties: false,
}),
},
} as const;
const dmDeleteAction = <Path extends string>(_path: Path): TypedAction<typeof dmDeleteEndpointsProps, Path> =>
async function action() {
const { room } = await findDirectMessageRoom(this.bodyParams, this.userId);
const canAccess =
(await canAccessRoomIdAsync(room._id, this.userId)) || (await hasPermissionAsync(this.userId, 'view-room-administration'));
if (!canAccess) {
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}
await eraseRoom(room._id, this.user);
return API.v1.success();
};
const dmEndpoints = API.v1
.post('im.delete', dmDeleteEndpointsProps, dmDeleteAction('im.delete'))
.post('dm.delete', dmDeleteEndpointsProps, dmDeleteAction('dm.delete'));
API.v1.addRoute(
['dm.close', 'im.close'],
{ authRequired: true },
{
async post() {
const { roomId } = this.bodyParams;
if (!roomId) {
throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" is required');
}
let subscription;
const roomExists = !!(await Rooms.findOneById(roomId));
if (!roomExists) {
// even if the room doesn't exist, we should allow the user to close the subscription anyways
subscription = await Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId);
} else {
const canAccess = await canAccessRoomIdAsync(roomId, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const { subscription: subs } = await findDirectMessageRoom({ roomId }, this.userId);
subscription = subs;
}
if (!subscription) {
return API.v1.failure(`The user is not subscribed to the room`);
}
if (!subscription.open) {
return API.v1.failure(`The direct message room, is already closed to the sender`);
}
await hideRoomMethod(this.userId, roomId);
return API.v1.success();
},
},
);
// https://github.com/RocketChat/Rocket.Chat/pull/9679 as reference
API.v1.addRoute(
['dm.counters', 'im.counters'],
{ authRequired: true },
{
async get() {
const access = await hasPermissionAsync(this.userId, 'view-room-administration');
const { roomId, userId: ruserId } = this.queryParams;
if (!roomId) {
throw new Meteor.Error('error-room-param-not-provided', 'Query param "roomId" is required');
}
let user = this.userId;
let unreads = null;
let userMentions = null;
let unreadsFrom = null;
let joined = false;
let msgs = null;
let latest = null;
let members = null;
let lm = null;
if (ruserId) {
if (!access) {
return API.v1.forbidden();
}
user = ruserId;
}
const canAccess = await canAccessRoomIdAsync(roomId, user);
if (!canAccess) {
return API.v1.forbidden();
}
const { room, subscription } = await findDirectMessageRoom({ roomId }, user);
lm = room?.lm ? new Date(room.lm).toISOString() : new Date(room._updatedAt).toISOString(); // lm is the last message timestamp
if (subscription) {
unreads = subscription.unread ?? null;
if (subscription.ls && room.msgs) {
unreadsFrom = new Date(subscription.ls).toISOString(); // last read timestamp
}
userMentions = subscription.userMentions;
joined = true;
}
if (access || joined) {
msgs = room.msgs;
latest = lm;
members = await Users.countActiveUsersInDMRoom(room._id);
}
return API.v1.success({
joined,
members,
unreads,
unreadsFrom,
msgs,
latest,
userMentions,
});
},
},
);
API.v1.addRoute(
['dm.files', 'im.files'],
{
authRequired: true,
validateParams: isDmFileProps,
},
{
async get() {
const { typeGroup, name, roomId, username, onlyConfirmed } = this.queryParams;
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort, fields, query } = await this.parseJsonQuery();
const { room } = await findDirectMessageRoom(roomId ? { roomId } : { username }, this.userId);
const canAccess = await canAccessRoomIdAsync(room._id, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const filter = {
...query,
rid: room._id,
...(name ? { name: { $regex: name || '', $options: 'i' } } : {}),
...(typeGroup ? { typeGroup } : {}),
...(onlyConfirmed && { expiresAt: { $exists: false } }),
};
const { cursor, totalCount } = Uploads.findPaginatedWithoutThumbs(filter, {
sort: sort || { name: 1 },
skip: offset,
limit: count,
projection: fields,
});
const [files, total] = await Promise.all([cursor.toArray(), totalCount]);
return API.v1.success({
files: await addUserToFileObj(files),
count: files.length,
offset,
total,
});
},
},
);
API.v1.addRoute(
['dm.history', 'im.history'],
{ authRequired: true, validateParams: isDmHistoryProps },
{
async get() {
const { offset = 0, count = 20 } = await getPaginationItems(this.queryParams);
const { roomId, latest, oldest, inclusive, unreads, showThreadMessages } = this.queryParams;
if (!roomId) {
throw new Meteor.Error('error-room-param-not-provided', 'Query param "roomId" is required');
}
const { room } = await findDirectMessageRoom({ roomId }, this.userId);
const objectParams = {
rid: room._id,
fromUserId: this.userId,
latest: latest ? new Date(latest) : new Date(),
oldest: oldest ? new Date(oldest) : undefined,
inclusive: inclusive === 'true',
offset,
count,
unreads: unreads === 'true',
showThreadMessages: showThreadMessages === 'true',
};
const result = await getChannelHistory(objectParams);
if (!result) {
return API.v1.forbidden();
}
return API.v1.success(result);
},
},
);
API.v1.addRoute(
['dm.members', 'im.members'],
{
authRequired: true,
validateParams: isDmMemberProps,
},
{
async get() {
const { room } = await findDirectMessageRoom(this.queryParams, this.userId);
const canAccess = await canAccessRoomIdAsync(room._id, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort } = await this.parseJsonQuery();
check(
this.queryParams,
Match.ObjectIncluding({
status: Match.Maybe([String]),
filter: Match.Maybe(String),
}),
);
const { status, filter } = this.queryParams;
const extraQuery = {
_id: { $in: room.uids },
...(status && { status: { $in: status } }),
};
const options: FindOptions<IUser> = {
projection: {
_id: 1,
username: 1,
name: 1,
status: 1,
statusText: 1,
utcOffset: 1,
federated: 1,
freeSwitchExtension: 1,
},
skip: offset,
limit: count,
sort: {
_updatedAt: -1,
username: sort?.username ? sort.username : 1,
},
};
const searchFields = settings.get<string>('Accounts_SearchFields').trim().split(',');
const { cursor, totalCount } = Users.findPaginatedByActiveUsersExcept(filter, [], options, searchFields, [extraQuery]);
const [members, total] = await Promise.all([cursor.toArray(), totalCount]);
// find subscriptions of those users
const subs = await Subscriptions.findByRoomIdAndUserIds(
room._id,
members.map((member) => member._id),
{ projection: { u: 1, status: 1, ts: 1, roles: 1 } },
).toArray();
const membersWithSubscriptionInfo = members.map((member) => {
const sub = subs.find((sub) => sub.u._id === member._id);
const { u: _u, ...subscription } = sub || {};
return {
...member,
subscription,
};
});
return API.v1.success({
members: membersWithSubscriptionInfo,
count: members.length,
offset,
total,
});
},
},
);
API.v1.addRoute(
['dm.messages', 'im.messages'],
{
authRequired: true,
validateParams: isDmMessagesProps,
},
{
async get() {
const { roomId, username, mentionIds, starredIds, pinned } = this.queryParams;
const { room } = await findDirectMessageRoom({ ...(roomId ? { roomId } : { username }) }, this.userId);
const canAccess = await canAccessRoomIdAsync(room._id, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort, fields, query } = await this.parseJsonQuery();
const parseIds = (ids: string | undefined, field: string) =>
typeof ids === 'string' && ids ? { [field]: { $in: ids.split(',').map((id) => id.trim()) } } : {};
const ourQuery = {
rid: room._id,
...query,
...parseIds(mentionIds, 'mentions._id'),
...parseIds(starredIds, 'starred._id'),
...(pinned && pinned.toLowerCase() === 'true' ? { pinned: true } : {}),
_hidden: { $ne: true },
};
const sortObj = sort || { ts: -1 };
const { cursor, totalCount } = Messages.findPaginated(ourQuery, {
sort: sortObj,
skip: offset,
limit: count,
...(fields && { projection: fields }),
});
const [messages, total] = await Promise.all([cursor.toArray(), totalCount]);
return API.v1.success({
messages: await normalizeMessagesForUser(messages, this.userId),
count: messages.length,
offset,
total,
});
},
},
);
API.v1.addRoute(
['dm.messages.others', 'im.messages.others'],
{ authRequired: true, permissionsRequired: ['view-room-administration'] },
{
async get() {
if (settings.get('API_Enable_Direct_Message_History_EndPoint') !== true) {
throw new Meteor.Error('error-endpoint-disabled', 'This endpoint is disabled', {
route: '/api/v1/im.messages.others',
});
}
const { roomId } = this.queryParams;
if (!roomId) {
throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" is required');
}
const room = await Rooms.findOneById<Pick<IRoom, '_id' | 't'>>(roomId, { projection: { _id: 1, t: 1 } });
if (!room || room?.t !== 'd') {
throw new Meteor.Error('error-room-not-found', `No direct message room found by the id of: ${roomId}`);
}
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort, fields, query } = await this.parseJsonQuery();
const ourQuery = Object.assign({}, query, { rid: room._id });
const { cursor, totalCount } = Messages.findPaginated<IMessage>(ourQuery, {
sort: sort || { ts: -1 },
skip: offset,
limit: count,
projection: fields,
});
const [msgs, total] = await Promise.all([cursor.toArray(), totalCount]);
if (!msgs) {
throw new Meteor.Error('error-no-messages', 'No messages found');
}
return API.v1.success({
messages: await normalizeMessagesForUser(msgs, this.userId),
offset,
count: msgs.length,
total,
});
},
},
);
API.v1.addRoute(
['dm.list', 'im.list'],
{ authRequired: true },
{
async get() {
const { offset, count } = await getPaginationItems(this.queryParams);
const { sort = { name: 1 }, fields } = await this.parseJsonQuery();
// TODO: CACHE: Add Breaking notice since we removed the query param
const subscriptions = await Subscriptions.find({ 'u._id': this.userId, 't': 'd' }, { projection: { rid: 1 } })
.map((item) => item.rid)
.toArray();
const { cursor, totalCount } = Rooms.findPaginated(
{ t: 'd', _id: { $in: subscriptions } },
{
sort,
skip: offset,
limit: count,
projection: fields,
},
);
const [ims, total] = await Promise.all([cursor.toArray(), totalCount]);
return API.v1.success({
ims: await Promise.all(ims.map((room: IRoom) => composeRoomWithLastMessage(room, this.userId))),
offset,
count: ims.length,
total,
});
},
},
);
API.v1.addRoute(
['dm.list.everyone', 'im.list.everyone'],
{ authRequired: true, permissionsRequired: ['view-room-administration'] },
{
async get() {
const { offset, count }: { offset: number; count: number } = await getPaginationItems(this.queryParams);
const { sort, fields, query } = await this.parseJsonQuery();
const { cursor, totalCount } = Rooms.findPaginated(
{ ...query, t: 'd' },
{
sort: sort || { name: 1 },
skip: offset,
limit: count,
projection: fields,
},
);
const [rooms, total] = await Promise.all([cursor.toArray(), totalCount]);
return API.v1.success({
ims: await Promise.all(rooms.map((room: IRoom) => composeRoomWithLastMessage(room, this.userId))),
offset,
count: rooms.length,
total,
});
},
},
);
API.v1.addRoute(
['dm.open', 'im.open'],
{ authRequired: true },
{
async post() {
const { roomId } = this.bodyParams;
if (!roomId) {
throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" is required');
}
const canAccess = await canAccessRoomIdAsync(roomId, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const { room, subscription } = await findDirectMessageRoom({ roomId }, this.userId);
if (!subscription?.open) {
await openRoom(this.userId, room._id);
}
return API.v1.success();
},
},
);
API.v1.addRoute(
['dm.setTopic', 'im.setTopic'],
{ authRequired: true },
{
async post() {
const { roomId, topic } = this.bodyParams;
if (!roomId) {
throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" is required');
}
const canAccess = await canAccessRoomIdAsync(roomId, this.userId);
if (!canAccess) {
return API.v1.forbidden();
}
const { room } = await findDirectMessageRoom({ roomId }, this.userId);
await saveRoomSettings(this.userId, room._id, 'roomTopic', topic);
return API.v1.success({
topic,
});
},
},
);
export type DmEndpoints = ExtractRoutesFromAPI<typeof dmEndpoints>;
declare module '@rocket.chat/rest-typings' {
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface
interface Endpoints extends DmEndpoints {}
}