-
Notifications
You must be signed in to change notification settings - Fork 72
/
channel.ts
1799 lines (1682 loc) · 51.4 KB
/
channel.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
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ChannelState } from './channel_state';
import { isValidEventType } from './events';
import { logChatPromiseExecution, normalizeQuerySort } from './utils';
import { StreamChat } from './client';
import {
APIResponse,
BanUserOptions,
ChannelAPIResponse,
ChannelData,
ChannelFilters,
ChannelMemberAPIResponse,
ChannelMemberResponse,
ChannelQueryOptions,
ChannelResponse,
DeleteChannelAPIResponse,
Event,
EventAPIResponse,
EventHandler,
EventTypes,
FormatMessageResponse,
GetMultipleMessagesAPIResponse,
GetReactionsAPIResponse,
GetRepliesAPIResponse,
InviteOptions,
LiteralStringForUnion,
MarkReadOptions,
Message,
MessageFilters,
MessageResponse,
MuteChannelAPIResponse,
PaginationOptions,
PartialUpdateChannel,
PartialUpdateChannelAPIResponse,
QueryMembersOptions,
Reaction,
ReactionAPIResponse,
SearchOptions,
SearchPayload,
SearchAPIResponse,
SendMessageAPIResponse,
TruncateChannelAPIResponse,
UnknownType,
UpdateChannelAPIResponse,
UserFilters,
UserResponse,
UserSort,
SearchMessageSortBase,
} from './types';
import { Role } from './permissions';
/**
* Channel - The Channel class manages it's own state.
*/
export class Channel<
AttachmentType extends UnknownType = UnknownType,
ChannelType extends UnknownType = UnknownType,
CommandType extends string = LiteralStringForUnion,
EventType extends UnknownType = UnknownType,
MessageType extends UnknownType = UnknownType,
ReactionType extends UnknownType = UnknownType,
UserType extends UnknownType = UnknownType
> {
_client: StreamChat<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>;
type: string;
id: string | undefined;
data:
| ChannelData<ChannelType>
| ChannelResponse<ChannelType, CommandType, UserType>
| undefined;
_data: ChannelData<ChannelType> | ChannelResponse<ChannelType, CommandType, UserType>;
cid: string;
listeners: {
[key: string]: (
| string
| EventHandler<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>
)[];
};
state: ChannelState<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>;
initialized: boolean;
lastKeyStroke?: Date;
lastTypingEvent: Date | null;
isTyping: boolean;
disconnected: boolean;
/**
* constructor - Create a channel
*
* @param {StreamChat<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>} client the chat client
* @param {string} type the type of channel
* @param {string} [id] the id of the chat
* @param {ChannelData<ChannelType>} data any additional custom params
*
* @return {Channel<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>} Returns a new uninitialized channel
*/
constructor(
client: StreamChat<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>,
type: string,
id: string | undefined,
data: ChannelData<ChannelType>,
) {
const validTypeRe = /^[\w_-]+$/;
const validIDRe = /^[\w!_-]+$/;
if (!validTypeRe.test(type)) {
throw new Error(`Invalid chat type ${type}, letters, numbers and "_-" are allowed`);
}
if (typeof id === 'string' && !validIDRe.test(id)) {
throw new Error(`Invalid chat id ${id}, letters, numbers and "!-_" are allowed`);
}
this._client = client;
this.type = type;
this.id = id;
// used by the frontend, gets updated:
this.data = data;
// this._data is used for the requests...
this._data = { ...data };
this.cid = `${type}:${id}`;
this.listeners = {};
// perhaps the state variable should be private
this.state = new ChannelState<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>(this);
this.initialized = false;
this.lastTypingEvent = null;
this.isTyping = false;
this.disconnected = false;
}
/**
* getClient - Get the chat client for this channel. If client.disconnect() was called, this function will error
*
* @return {StreamChat<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>}
*/
getClient(): StreamChat<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
> {
if (this.disconnected === true) {
throw Error(`You can't use a channel after client.disconnect() was called`);
}
return this._client;
}
/**
* getConfig - Get the configs for this channel type
*
* @return {Record<string, unknown>}
*/
getConfig() {
const client = this.getClient();
return client.configs[this.type];
}
/**
* sendMessage - Send a message to this channel
*
* @param {Message<AttachmentType, MessageType, UserType>} message The Message object
* @param {{ skip_push?: boolean }} [options] Option object, {skip_push: true} to skip sending push notifications
*
* @return {Promise<SendMessageAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The Server Response
*/
async sendMessage(
message: Message<AttachmentType, MessageType, UserType>,
options?: { skip_push?: boolean },
) {
const sendMessageResponse = await this.getClient().post<
SendMessageAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL() + '/message', {
message,
...options,
});
// Reset unreadCount to 0.
this.state.unreadCount = 0;
return sendMessageResponse;
}
sendFile(
uri: string | NodeJS.ReadableStream | Buffer | File,
name?: string,
contentType?: string,
user?: UserResponse<UserType>,
) {
return this.getClient().sendFile(
`${this._channelURL()}/file`,
uri,
name,
contentType,
user,
);
}
sendImage(
uri: string | NodeJS.ReadableStream | File,
name?: string,
contentType?: string,
user?: UserResponse<UserType>,
) {
return this.getClient().sendFile(
`${this._channelURL()}/image`,
uri,
name,
contentType,
user,
);
}
deleteFile(url: string) {
return this.getClient().delete<APIResponse>(`${this._channelURL()}/file`, { url });
}
deleteImage(url: string) {
return this.getClient().delete<APIResponse>(`${this._channelURL()}/image`, { url });
}
/**
* sendEvent - Send an event on this channel
*
* @param {Event<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>} event for example {type: 'message.read'}
*
* @return {Promise<EventAPIResponse<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>>} The Server Response
*/
async sendEvent(
event: Event<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>,
) {
this._checkInitialized();
return await this.getClient().post<
EventAPIResponse<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL() + '/event', {
event,
});
}
/**
* search - Query messages
*
* @param {MessageFilters<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType> | string} query search query or object MongoDB style filters
* @param {{client_id?: string; connection_id?: string; query?: string; message_filter_conditions?: MessageFilters<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>}} options Option object, {user_id: 'tommaso'}
*
* @return {Promise<SearchAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} search messages response
*/
async search(
query:
| MessageFilters<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
| string,
options: SearchOptions<MessageType> & {
client_id?: string;
connection_id?: string;
message_filter_conditions?: MessageFilters<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>;
query?: string;
} = {},
) {
if (options.offset && (options.sort || options.next)) {
throw Error(`Cannot specify offset with sort or next parameters`);
}
// Return a list of channels
const payload: SearchPayload<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
> = {
filter_conditions: { cid: this.cid } as ChannelFilters<
ChannelType,
CommandType,
UserType
>,
...options,
sort: options.sort
? normalizeQuerySort<SearchMessageSortBase<MessageType>>(options.sort)
: undefined,
};
if (typeof query === 'string') {
payload.query = query;
} else if (typeof query === 'object') {
payload.message_filter_conditions = query;
} else {
throw Error(`Invalid type ${typeof query} for query parameter`);
}
// Make sure we wait for the connect promise if there is a pending one
await this.getClient().wsPromise;
return await this.getClient().get<
SearchAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this.getClient().baseURL + '/search', {
payload,
});
}
/**
* queryMembers - Query Members
*
* @param {UserFilters<UserType>} filterConditions object MongoDB style filters
* @param {UserSort<UserType>} [sort] Sort options, for instance [{created_at: -1}].
* When using multiple fields, make sure you use array of objects to guarantee field order, for instance [{last_active: -1}, {created_at: 1}]
* @param {{ limit?: number; offset?: number }} [options] Option object, {limit: 10, offset:10}
*
* @return {Promise<ChannelMemberAPIResponse<UserType>>} Query Members response
*/
async queryMembers(
filterConditions: UserFilters<UserType>,
sort: UserSort<UserType> = [],
options: QueryMembersOptions = {},
) {
let id: string | undefined;
const type = this.type;
let members: string[] | ChannelMemberResponse<UserType>[] | undefined;
if (this.id) {
id = this.id;
} else if (this.data?.members && Array.isArray(this.data.members)) {
members = this.data.members;
}
// Return a list of members
return await this.getClient().get<ChannelMemberAPIResponse<UserType>>(
this.getClient().baseURL + '/members',
{
payload: {
type,
id,
members,
sort: normalizeQuerySort(sort),
filter_conditions: filterConditions,
...options,
},
},
);
}
/**
* sendReaction - Send a reaction about a message
*
* @param {string} messageID the message id
* @param {Reaction<ReactionType, UserType>} reaction the reaction object for instance {type: 'love'}
* @param {{ enforce_unique?: boolean, skip_push?: boolean }} [options] Option object, {enforce_unique: true, skip_push: true} to override any existing reaction or skip sending push notifications
*
* @return {Promise<ReactionAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The Server Response
*/
async sendReaction(
messageID: string,
reaction: Reaction<ReactionType, UserType>,
options?: { enforce_unique?: boolean; skip_push?: boolean },
) {
if (!messageID) {
throw Error(`Message id is missing`);
}
if (!reaction || Object.keys(reaction).length === 0) {
throw Error(`Reaction object is missing`);
}
return await this.getClient().post<
ReactionAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this.getClient().baseURL + `/messages/${messageID}/reaction`, {
reaction,
...options,
});
}
/**
* deleteReaction - Delete a reaction by user and type
*
* @param {string} messageID the id of the message from which te remove the reaction
* @param {string} reactionType the type of reaction that should be removed
* @param {string} [user_id] the id of the user (used only for server side request) default null
*
* @return {Promise<ReactionAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The Server Response
*/
deleteReaction(messageID: string, reactionType: string, user_id?: string) {
this._checkInitialized();
if (!reactionType || !messageID) {
throw Error(
'Deleting a reaction requires specifying both the message and reaction type',
);
}
const url =
this.getClient().baseURL + `/messages/${messageID}/reaction/${reactionType}`;
//provided when server side request
if (user_id) {
return this.getClient().delete<
ReactionAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(url, { user_id });
}
return this.getClient().delete<
ReactionAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(url, {});
}
/**
* update - Edit the channel's custom properties
*
* @param {ChannelData<ChannelType>} channelData The object to update the custom properties of this channel with
* @param {Message<AttachmentType, MessageType, UserType>} [updateMessage] Optional message object for channel members notification
* @param {{ skip_push?: boolean }} [options] Option object, {skip_push: true} to skip sending push notifications
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async update(
channelData:
| Partial<ChannelData<ChannelType>>
| Partial<ChannelResponse<ChannelType, CommandType, UserType>> = {},
updateMessage?: Message<AttachmentType, MessageType, UserType>,
options?: { skip_push?: boolean },
) {
// Strip out reserved names that will result in API errors.
const reserved = [
'config',
'cid',
'created_by',
'id',
'member_count',
'type',
'created_at',
'updated_at',
'last_message_at',
'own_capabilities',
];
reserved.forEach((key) => {
delete channelData[key];
});
return await this._update({
message: updateMessage,
data: channelData,
...options,
});
}
/**
* updatePartial - partial update channel properties
*
* @param {PartialUpdateChannel<ChannelType>} partial update request
*
* @return {Promise<PartialUpdateChannelAPIResponse<ChannelType,CommandType, UserType>>}
*/
async updatePartial(update: PartialUpdateChannel<ChannelType>) {
return await this.getClient().patch<
PartialUpdateChannelAPIResponse<ChannelType, CommandType, UserType>
>(this._channelURL(), update);
}
/**
* enableSlowMode - enable slow mode
*
* @param {number} coolDownInterval the cooldown interval in seconds
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async enableSlowMode(coolDownInterval: number) {
const data = await this.getClient().post<
UpdateChannelAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL(), {
cooldown: coolDownInterval,
});
this.data = data.channel;
return data;
}
/**
* disableSlowMode - disable slow mode
*
* @return {Promise<UpdateChannelAPIResponse<ChannelType, AttachmentType, MessageType, ReactionType, UserType>>} The server response
*/
async disableSlowMode() {
const data = await this.getClient().post<
UpdateChannelAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL(), {
cooldown: 0,
});
this.data = data.channel;
return data;
}
/**
* delete - Delete the channel. Messages are permanently removed.
*
* @return {Promise<DeleteChannelAPIResponse<ChannelType, CommandType, UserType>>} The server response
*/
async delete() {
return await this.getClient().delete<
DeleteChannelAPIResponse<ChannelType, CommandType, UserType>
>(this._channelURL(), {});
}
/**
* truncate - Removes all messages from the channel
*
* @return {Promise<TruncateChannelAPIResponse<ChannelType, CommandType, UserType>>} The server response
*/
async truncate() {
return await this.getClient().post<
TruncateChannelAPIResponse<ChannelType, CommandType, UserType>
>(this._channelURL() + '/truncate', {});
}
/**
* acceptInvite - accept invitation to the channel
*
* @param {InviteOptions<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>} [options] The object to update the custom properties of this channel with
*
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async acceptInvite(
options: InviteOptions<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
> = {},
) {
return await this._update({
accept_invite: true,
...options,
});
}
/**
* rejectInvite - reject invitation to the channel
*
* @param {InviteOptions<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>} [options] The object to update the custom properties of this channel with
*
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async rejectInvite(
options: InviteOptions<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
> = {},
) {
return await this._update({
reject_invite: true,
...options,
});
}
/**
* addMembers - add members to the channel
*
* @param {{user_id: string, channel_role?: Role}[]} members An array of members to add to the channel
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async addMembers(
members: string[] | { user_id: string; channel_role?: Role }[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
add_members: members,
message,
});
}
/**
* addModerators - add moderators to the channel
*
* @param {string[]} members An array of member identifiers
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async addModerators(
members: string[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
add_moderators: members,
message,
});
}
/**
* assignRoles - sets member roles in a channel
*
* @param {{channel_role: Role, user_id: string}[]} roles List of role assignments
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async assignRoles(
roles: { channel_role: Role; user_id: string }[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
assign_roles: roles,
message,
});
}
/**
* inviteMembers - invite members to the channel
*
* @param {{user_id: string, channel_role?: Role}[]} members An array of members to invite to the channel
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async inviteMembers(
members: { user_id: string; channel_role?: Role }[] | string[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
invites: members,
message,
});
}
/**
* removeMembers - remove members from channel
*
* @param {string[]} members An array of member identifiers
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async removeMembers(
members: string[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
remove_members: members,
message,
});
}
/**
* demoteModerators - remove moderator role from channel members
*
* @param {string[]} members An array of member identifiers
* @param {Message<AttachmentType, MessageType, UserType>} [message] Optional message object for channel members notification
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async demoteModerators(
members: string[],
message?: Message<AttachmentType, MessageType, UserType>,
) {
return await this._update({
demote_moderators: members,
message,
});
}
/**
* _update - executes channel update request
* @param payload Object Update Channel payload
* @return {Promise<UpdateChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
* TODO: introduce new type instead of Object in the next major update
*/
async _update(payload: Object) {
const data = await this.getClient().post<
UpdateChannelAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL(), payload);
this.data = data.channel;
return data;
}
/**
* mute - mutes the current channel
* @param {{ user_id?: string, expiration?: string }} opts expiration in minutes or user_id
* @return {Promise<MuteChannelAPIResponse<ChannelType, CommandType, UserType>>} The server response
*
* example with expiration:
* await channel.mute({expiration: moment.duration(2, 'weeks')});
*
* example server side:
* await channel.mute({user_id: userId});
*
*/
async mute(opts: { expiration?: number; user_id?: string } = {}) {
return await this.getClient().post<
MuteChannelAPIResponse<ChannelType, CommandType, UserType>
>(this.getClient().baseURL + '/moderation/mute/channel', {
channel_cid: this.cid,
...opts,
});
}
/**
* unmute - mutes the current channel
* @param {{ user_id?: string}} opts user_id
* @return {Promise<APIResponse>} The server response
*
* example server side:
* await channel.unmute({user_id: userId});
*/
async unmute(opts: { user_id?: string } = {}) {
return await this.getClient().post<APIResponse>(
this.getClient().baseURL + '/moderation/unmute/channel',
{
channel_cid: this.cid,
...opts,
},
);
}
/**
* muteStatus - returns the mute status for the current channel
* @return {{ muted: boolean; createdAt: Date | null; expiresAt: Date | null }} { muted: true | false, createdAt: Date | null, expiresAt: Date | null}
*/
muteStatus(): {
createdAt: Date | null;
expiresAt: Date | null;
muted: boolean;
} {
this._checkInitialized();
return this.getClient()._muteStatus(this.cid);
}
sendAction(messageID: string, formData: Record<string, string>) {
this._checkInitialized();
if (!messageID) {
throw Error(`Message id is missing`);
}
return this.getClient().post<
SendMessageAPIResponse<
AttachmentType,
ChannelType,
CommandType,
MessageType,
ReactionType,
UserType
>
>(this.getClient().baseURL + `/messages/${messageID}/action`, {
message_id: messageID,
form_data: formData,
id: this.id,
type: this.type,
});
}
/**
* keystroke - First of the typing.start and typing.stop events based on the users keystrokes.
* Call this on every keystroke
* @see {@link https://getstream.io/chat/docs/typing_indicators/?language=js|Docs}
* @param {string} [parent_id] set this field to `message.id` to indicate that typing event is happening in a thread
*/
async keystroke(parent_id?: string) {
if (!this.getConfig()?.typing_events) {
return;
}
const now = new Date();
const diff = this.lastTypingEvent && now.getTime() - this.lastTypingEvent.getTime();
this.lastKeyStroke = now;
this.isTyping = true;
// send a typing.start every 2 seconds
if (diff === null || diff > 2000) {
this.lastTypingEvent = new Date();
await this.sendEvent({
type: 'typing.start',
parent_id,
} as Event<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>);
}
}
/**
* stopTyping - Sets last typing to null and sends the typing.stop event
* @see {@link https://getstream.io/chat/docs/typing_indicators/?language=js|Docs}
* @param {string} [parent_id] set this field to `message.id` to indicate that typing event is happening in a thread
*/
async stopTyping(parent_id?: string) {
if (!this.getConfig()?.typing_events) {
return;
}
this.lastTypingEvent = null;
this.isTyping = false;
await this.sendEvent({
type: 'typing.stop',
parent_id,
} as Event<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>);
}
/**
* lastMessage - return the last message, takes into account that last few messages might not be perfectly sorted
*
* @return {ReturnType<ChannelState<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType>['formatMessage']> | undefined} Description
*/
lastMessage() {
// get last 5 messages, sort, return the latest
// get a slice of the last 5
let min = this.state.messages.length - 5;
if (min < 0) {
min = 0;
}
const max = this.state.messages.length + 1;
const messageSlice = this.state.messages.slice(min, max);
// sort by pk desc
messageSlice.sort((a, b) => b.created_at.getTime() - a.created_at.getTime());
return messageSlice[0];
}
/**
* markRead - Send the mark read event for this user, only works if the `read_events` setting is enabled
*
* @param {MarkReadOptions<UserType>} data
* @return {Promise<EventAPIResponse<AttachmentType, ChannelType, CommandType, EventType, MessageType, ReactionType, UserType> | null>} Description
*/
async markRead(data: MarkReadOptions<UserType> = {}) {
this._checkInitialized();
if (!this.getConfig()?.read_events) {
return Promise.resolve(null);
}
return await this.getClient().post<
EventAPIResponse<
AttachmentType,
ChannelType,
CommandType,
EventType,
MessageType,
ReactionType,
UserType
>
>(this._channelURL() + '/read', {
...data,
});
}
/**
* clean - Cleans the channel state and fires stop typing if needed
*/
clean() {
if (this.lastKeyStroke) {
const now = new Date();
const diff = now.getTime() - this.lastKeyStroke.getTime();
if (diff > 1000 && this.isTyping) {
logChatPromiseExecution(this.stopTyping(), 'stop typing event');
}
}
this.state.clean();
}
/**
* watch - Loads the initial channel state and watches for changes
*
* @param {ChannelQueryOptions<ChannelType, CommandType, UserType>} options additional options for the query endpoint
*
* @return {Promise<ChannelAPIResponse<AttachmentType, ChannelType, CommandType, MessageType, ReactionType, UserType>>} The server response
*/
async watch(options?: ChannelQueryOptions<ChannelType, CommandType, UserType>) {
const defaultOptions = {
state: true,
watch: true,
presence: false,
};
// Make sure we wait for the connect promise if there is a pending one
await this.getClient().wsPromise;
if (!this.getClient()._hasConnectionID()) {
defaultOptions.watch = false;
}
const combined = { ...defaultOptions, ...options };
const state = await this.query(combined);
this.initialized = true;
this.data = state.channel;
this._client.logger(
'info',
`channel:watch() - started watching channel ${this.cid}`,
{
tags: ['channel'],
channel: this,
},
);