forked from stoatchat/javascript-client-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannel.ts
More file actions
846 lines (752 loc) · 21 KB
/
Copy pathChannel.ts
File metadata and controls
846 lines (752 loc) · 21 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
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
import { batch } from "solid-js";
import { ReactiveMap } from "@solid-primitives/map";
import type { ReactiveSet } from "@solid-primitives/set";
import type {
Channel as APIChannel,
Member as APIMember,
Message as APIMessage,
User as APIUser,
DataEditChannel,
DataMessageSearch,
DataMessageSend,
Invite,
Override,
} from "stoat-api";
import type { APIRoutes } from "stoat-api";
import { decodeTime, ulid } from "ulid";
import { ChannelCollection } from "../collections/index.js";
import { hydrate } from "../hydration/index.js";
import {
bitwiseAndEq,
calculatePermission,
} from "../permissions/calculator.js";
import { Permission } from "../permissions/definitions.js";
import type { ChannelWebhook } from "./ChannelWebhook.js";
import type { File } from "./File.js";
import type { Message } from "./Message.js";
import type { Server } from "./Server.js";
import type { ServerMember } from "./ServerMember.js";
import type { User } from "./User.js";
import { VoiceParticipant } from "./VoiceParticipant.js";
/**
* Channel Class
*/
export class Channel {
readonly #collection: ChannelCollection;
readonly id: string;
_typingTimers: Record<string, number> = {};
voiceParticipants = new ReactiveMap<string, VoiceParticipant>();
/**
* Construct Channel
* @param collection Collection
* @param id Channel Id
*/
constructor(collection: ChannelCollection, id: string) {
this.#collection = collection;
this.id = id;
}
/**
* Write to string as a channel mention
* @returns Formatted String
*/
toString(): string {
return `<#${this.id}>`;
}
/**
* Whether this object exists
*/
get $exists(): boolean {
return !!this.#collection.getUnderlyingObject(this.id).id;
}
/**
* Time when this server was created
*/
get createdAt(): Date {
return new Date(decodeTime(this.id));
}
/**
* Channel type
*/
get type(): APIChannel["channel_type"] {
return this.#collection.getUnderlyingObject(this.id).channelType;
}
/**
* Absolute pathname to this channel in the client
*/
get path(): string {
if (this.serverId) {
return `/server/${this.serverId}/channel/${this.id}`;
} else {
return `/channel/${this.id}`;
}
}
/**
* URL to this channel
*/
get url(): string {
return this.#collection.client.configuration?.app + this.path;
}
/**
* Channel name
*/
get name(): string {
return this.#collection.getUnderlyingObject(this.id).name;
}
/**
* Display name
*/
get displayName(): string | undefined {
return this.type === "SavedMessages"
? this.user?.username
: this.type === "DirectMessage"
? this.recipient?.username
: this.name;
}
/**
* Channel description
*/
get description(): string | undefined {
return this.#collection.getUnderlyingObject(this.id).description;
}
/**
* Channel icon
*/
get icon(): File | undefined {
return this.#collection.getUnderlyingObject(this.id).icon;
}
/**
* Whether the conversation is active
*/
get active(): boolean {
return this.#collection.getUnderlyingObject(this.id).active;
}
/**
* User ids of people currently typing in channel
*/
get typingIds(): ReactiveSet<string> {
return this.#collection.getUnderlyingObject(this.id).typingIds;
}
/**
* Users currently trying in channel
*/
get typing(): User[] {
return [...this.typingIds.values()].map(
(id) => this.#collection.client.users.get(id)!,
);
}
/**
* User ids of recipients of the group
*/
get recipientIds(): ReactiveSet<string> {
return this.#collection.getUnderlyingObject(this.id).recipientIds;
}
/**
* Recipients of the group
*/
get recipients(): User[] {
return [
...this.#collection.getUnderlyingObject(this.id).recipientIds.values(),
].map((id) => this.#collection.client.users.get(id)!);
}
/**
* Find recipient of this DM
*/
get recipient(): User | undefined {
return this.type === "DirectMessage"
? this.recipients?.find(
(user) => user?.id !== this.#collection.client.user!.id,
)
: undefined;
}
/**
* User ID
*/
get userId(): string {
return this.#collection.getUnderlyingObject(this.id).userId!;
}
/**
* User this channel belongs to
*/
get user(): User | undefined {
return this.#collection.client.users.get(
this.#collection.getUnderlyingObject(this.id).userId!,
);
}
/**
* Owner ID
*/
get ownerId(): string {
return this.#collection.getUnderlyingObject(this.id).ownerId!;
}
/**
* Owner of the group
*/
get owner(): User | undefined {
return this.#collection.client.users.get(
this.#collection.getUnderlyingObject(this.id).ownerId!,
);
}
/**
* Server ID
*/
get serverId(): string {
return this.#collection.getUnderlyingObject(this.id).serverId!;
}
/**
* Server this channel is in
*/
get server(): Server | undefined {
return this.#collection.client.servers.get(
this.#collection.getUnderlyingObject(this.id).serverId!,
);
}
/**
* Permissions allowed for users in this group
*/
get permissions(): bigint | undefined {
return this.#collection.getUnderlyingObject(this.id).permissions;
}
/**
* Default permissions for this server channel
*/
get defaultPermissions(): { a: bigint; d: bigint } | undefined {
return this.#collection.getUnderlyingObject(this.id).defaultPermissions;
}
/**
* Role permissions for this server channel
*/
get rolePermissions(): Record<string, { a: bigint; d: bigint }> | undefined {
return this.#collection.getUnderlyingObject(this.id).rolePermissions;
}
/**
* Whether this channel is marked as mature
*/
get mature(): boolean {
return this.#collection.getUnderlyingObject(this.id).nsfw;
}
/**
* ID of the last message sent in this channel
*/
get lastMessageId(): string | undefined {
return this.#collection.getUnderlyingObject(this.id).lastMessageId;
}
/**
* Last message sent in this channel
*/
get lastMessage(): Message | undefined {
return this.#collection.client.messages.get(this.lastMessageId!);
}
/**
* Time when the last message was sent
*/
get lastMessageAt(): Date | undefined {
return this.lastMessageId
? new Date(decodeTime(this.lastMessageId))
: undefined;
}
/**
* Time when the channel was last updated (either created or a message was sent)
*/
get updatedAt(): Date {
return this.lastMessageAt ?? this.createdAt;
}
/**
* Whether this channel is unread
*/
get unread(): boolean {
if (
!this.lastMessageId ||
this.type === "SavedMessages" ||
this.#collection.client.options.channelExclusiveMuted(this)
)
return false;
const unread = this.#collection.client.channelUnreads.for(this);
return (
(unread.lastMessageId ?? "0").localeCompare(this.lastMessageId) === -1 ||
unread.messageMentionIds.size > 0
);
}
/**
* Whether this channel is muted
*/
get muted(): boolean {
return this.#collection.client.options.channelIsMuted(this);
}
/**
* Get mentions in this channel for user.
*/
get mentions(): ReactiveSet<string> | undefined {
if (this.type === "SavedMessages") return undefined;
return this.#collection.client.channelUnreads.get(this.id)
?.messageMentionIds;
}
/**
* Whether this is a 'voice chats v2' channel
*
* NB. subject to change as vc(2) goes to production
*/
get isVoice(): boolean {
return (
this.type === "DirectMessage" ||
this.type === "Group" ||
typeof this.#collection.getUnderlyingObject(this.id).voice === "object"
);
}
/**
* URL to the channel icon
*/
get iconURL(): string | undefined {
return this.icon?.createFileURL() ?? this.recipient?.avatarURL;
}
/**
* URL to the animated channel icon
*/
get animatedIconURL(): string | undefined {
return this.icon?.createFileURL(true) ?? this.recipient?.animatedAvatarURL;
}
/**
* Whether this channel may be hidden to some users
*/
get potentiallyRestrictedChannel(): string | boolean | undefined {
if (!this.serverId) return false;
return (
bitwiseAndEq(this.defaultPermissions?.d ?? 0n, Permission.ViewChannel) ||
!bitwiseAndEq(this.server!.defaultPermissions, Permission.ViewChannel) ||
[...(this.server?.roles.keys() ?? [])].find(
(role) =>
bitwiseAndEq(
this.rolePermissions?.[role]?.d ?? 0n,
Permission.ViewChannel,
) ||
bitwiseAndEq(
this.server?.roles.get(role)?.permissions.d ?? 0n,
Permission.ViewChannel,
),
)
);
}
/**
* Permission the currently authenticated user has against this channel
*/
get permission(): bigint {
return calculatePermission(this.#collection.client, this);
}
/**
* Check whether we have a given permission in a channel
* @param permission Permission Names
* @returns Whether we have this permission
*/
havePermission(...permission: (keyof typeof Permission)[]): boolean {
return bitwiseAndEq(
this.permission,
...permission.map((x) => Permission[x]),
);
}
/**
* Check whether we have at least one of the given permissions in a channel
* @param permission Permission Names
* @returns Whether we have one of the permissions
*/
orPermission(...permission: (keyof typeof Permission)[]): boolean {
return (
permission.findIndex((x) =>
bitwiseAndEq(this.permission, Permission[x]),
) !== -1
);
}
/**
* Fetch a channel's members.
* @requires `Group`
* @returns An array of the channel's members.
*/
async fetchMembers(): Promise<User[]> {
const members = await this.#collection.client.api.get(
`/channels/${this.id as ""}/members`,
);
return batch(() =>
members.map((user) =>
this.#collection.client.users.getOrCreate(user._id, user),
),
);
}
/**
* Create a webhook
* @param name Webhook name
* @returns The newly-created webhook
*/
async createWebhook(name: string): Promise<ChannelWebhook> {
const webhook = await this.#collection.client.api.post(
`/channels/${this.id as ""}/webhooks`,
{
name,
},
);
return this.#collection.client.channelWebhooks.getOrCreate(
webhook.id,
webhook,
);
}
/**
* Fetch a channel's webhooks
* @requires `TextChannel`, `Group`
* @returns Webhooks
*/
async fetchWebhooks(): Promise<ChannelWebhook[]> {
const webhooks = await this.#collection.client.api.get(
`/channels/${this.id as ""}/webhooks`,
);
return batch(() =>
webhooks.map((webhook) =>
this.#collection.client.channelWebhooks.getOrCreate(
webhook.id,
webhook,
),
),
);
}
/**
* Edit a channel
* @param data Changes
*/
async edit(data: DataEditChannel) {
const channel = await this.#collection.client.api.patch(
`/channels/${this.id as ""}`,
data,
);
this.#collection.updateUnderlyingObject(
this.id,
hydrate("channel", channel, this.#collection.client, false),
);
}
/**
* Delete or leave a channel
* @param leaveSilently Whether to not send a message on leave
* @requires `DirectMessage`, `Group`, `TextChannel`
*/
async delete(leaveSilently?: boolean): Promise<void> {
await this.#collection.client.api.delete(`/channels/${this.id as ""}`, {
leave_silently: leaveSilently,
});
if (this.type === "DirectMessage") {
this.#collection.updateUnderlyingObject(this.id, "active", false);
return;
}
this.#collection.delete(this.id);
}
/**
* Add a user to a group
* @param user_id ID of the target user
* @requires `Group`
*/
async addMember(user_id: string): Promise<void> {
return await this.#collection.client.api.put(
`/channels/${this.id as ""}/recipients/${user_id as ""}`,
);
}
/**
* Remove a user from a group
* @param user_id ID of the target user
* @requires `Group`
*/
async removeMember(user_id: string): Promise<void> {
return await this.#collection.client.api.delete(
`/channels/${this.id as ""}/recipients/${user_id as ""}`,
);
}
/**
* Send a message
* @param data Either the message as a string or message sending route data
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Sent message
*/
async sendMessage(
data: string | DataMessageSend,
idempotencyKey: string = ulid(),
): Promise<Message> {
const msg: DataMessageSend =
typeof data === "string" ? { content: data } : data;
// Mark as silent message
if (msg.content?.startsWith("@silent ")) {
msg.content = msg.content.substring(8);
msg.flags ||= 1;
msg.flags |= 1;
}
const message = await this.#collection.client.api.post(
`/channels/${this.id as ""}/messages`,
msg,
{
headers: {
"Idempotency-Key": idempotencyKey,
},
},
);
return this.#collection.client.messages.getOrCreate(
message._id,
message,
true,
);
}
/**
* Fetch a message by its ID
* @param messageId ID of the target message
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Message
*/
async fetchMessage(messageId: string): Promise<Message> {
const message = await this.#collection.client.api.get(
`/channels/${this.id as ""}/messages/${messageId as ""}`,
);
return this.#collection.client.messages.getOrCreate(message._id, message);
}
/**
* Fetch multiple messages from a channel
* @param params Message fetching route data
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Messages
*/
async fetchMessages(
params?: Omit<
(APIRoutes & {
method: "get";
path: "/channels/{target}/messages";
})["params"],
"include_users"
>,
): Promise<Message[]> {
const messages = (await this.#collection.client.api.get(
`/channels/${this.id as ""}/messages`,
{ ...params },
)) as APIMessage[];
return messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
);
}
/**
* Fetch multiple messages from a channel including the users that sent them
* @param params Message fetching route data
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Object including messages and users
*/
async fetchMessagesWithUsers(
params?: Omit<
(APIRoutes & {
method: "get";
path: "/channels/{target}/messages";
})["params"],
"include_users"
>,
): Promise<{
messages: Message[];
users: User[];
members: ServerMember[] | undefined;
}> {
const data = (await this.#collection.client.api.get(
`/channels/${this.id as ""}/messages`,
{ ...params, include_users: true },
)) as { messages: APIMessage[]; users: APIUser[]; members?: APIMember[] };
return batch(() => ({
messages: data.messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
),
users: data.users.map((user) =>
this.#collection.client.users.getOrCreate(user._id, user),
),
members: data.members?.map((member) =>
this.#collection.client.serverMembers.getOrCreate(member._id, member),
),
}));
}
/**
* Search for messages
* @param params Message searching route data
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Messages
*/
async search(
params: Omit<DataMessageSearch, "include_users">,
): Promise<Message[]> {
const messages = (await this.#collection.client.api.post(
`/channels/${this.id as ""}/search`,
params,
)) as APIMessage[];
return batch(() =>
messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
),
);
}
/**
* Search for messages including the users that sent them
* @param params Message searching route data
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
* @returns Object including messages and users
*/
async searchWithUsers(
params: Omit<DataMessageSearch, "include_users">,
): Promise<{
messages: Message[];
users: User[];
members: ServerMember[] | undefined;
}> {
const data = (await this.#collection.client.api.post(
`/channels/${this.id as ""}/search`,
{
...params,
include_users: true,
},
)) as { messages: APIMessage[]; users: APIUser[]; members?: APIMember[] };
return batch(() => ({
messages: data.messages.map((message) =>
this.#collection.client.messages.getOrCreate(message._id, message),
),
users: data.users.map((user) =>
this.#collection.client.users.getOrCreate(user._id, user),
),
members: data.members?.map((member) =>
this.#collection.client.serverMembers.getOrCreate(member._id, member),
),
}));
}
/**
* Delete many messages by their IDs
* @param ids List of message IDs
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
*/
async deleteMessages(ids: string[]): Promise<void> {
await this.#collection.client.api.delete(
`/channels/${this.id as ""}/messages/bulk`,
{
ids,
},
);
}
/**
* Create an invite to the channel
* @requires `TextChannel`
* @returns Newly created invite code
*/
async createInvite(): Promise<Invite> {
return await this.#collection.client.api.post(
`/channels/${this.id as ""}/invites`,
);
}
#ackTimeout?: number;
#ackLimit?: number;
#manuallyMarked?: boolean;
/**
* Mark a channel as read
* @param message Last read message or its ID
* @param skipRateLimiter Whether to skip the internal rate limiter
* @param skipRequest For internal updates only
* @param skipNextMarking For internal usage only
* @requires `SavedMessages`, `DirectMessage`, `Group`, `TextChannel`
*/
async ack(
message?: Message | string,
skipRateLimiter?: boolean,
skipRequest?: boolean,
skipNextMarking?: boolean,
): Promise<void> {
if (!message && this.#manuallyMarked) {
this.#manuallyMarked = false;
return;
}
// Skip the next unread marking
else if (skipNextMarking) {
this.#manuallyMarked = true;
}
const lastMessageId =
(typeof message === "string" ? message : message?.id) ??
this.lastMessageId ??
ulid();
const channelUnread = this.#collection.client.channelUnreads.for(this);
batch(() => {
this.#collection.client.channelUnreads.updateUnderlyingObject(
this.id,
"lastMessageId",
lastMessageId,
);
if (channelUnread.messageMentionIds.size) {
channelUnread.messageMentionIds.clear();
}
});
// Skip request if not needed
if (skipRequest) return;
/**
* Send the actual acknowledgement request
*/
const performAck = (): void => {
this.#ackLimit = undefined;
this.#collection.client.api.put(
`/channels/${this.id}/ack/${lastMessageId as ""}`,
);
};
if (skipRateLimiter) return performAck();
clearTimeout(this.#ackTimeout);
if (this.#ackLimit && +new Date() > this.#ackLimit) {
performAck();
}
this.#ackTimeout = setTimeout(performAck, 1500) as unknown as number;
if (!this.#ackLimit) {
this.#ackLimit = +new Date() + 4e3;
}
}
/**
* Set role permissions
* @param role_id Role Id, set to 'default' to affect all users
* @param permissions Permission value
* @requires `Group`, `TextChannel`
*/
async setPermissions(
role_id = "default",
permissions: Override | number,
): Promise<APIChannel> {
return await this.#collection.client.api.put(
`/channels/${this.id as ""}/permissions/${role_id as ""}`,
{ permissions: permissions as never },
);
}
/**
* Join a call
* @param node Target node
* @param forceDisconnect Whether to disconnect existing call
* @param recipients Ring targets
* @returns LiveKit URL and Token
*/
async joinCall(
node?: string,
forceDisconnect = true,
recipients?: (User | string)[],
) {
return await this.#collection.client.api.post(
`/channels/${this.id as ""}/join_call`,
{
node,
recipients: recipients?.map((entry) =>
typeof entry === "string" ? entry : entry.id,
),
force_disconnect: forceDisconnect,
},
);
}
/**
* Start typing in this channel
* @requires `DirectMessage`, `Group`, `TextChannel`
*/
startTyping(): void {
this.#collection.client.events.send({
type: "BeginTyping",
channel: this.id,
});
}
/**
* Stop typing in this channel
* @requires `DirectMessage`, `Group`, `TextChannel`
*/
stopTyping(): void {
this.#collection.client.events.send({
type: "EndTyping",
channel: this.id,
});
}
}