forked from stoatchat/javascript-client-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.ts
More file actions
796 lines (703 loc) · 18.8 KB
/
Copy pathServer.ts
File metadata and controls
796 lines (703 loc) · 18.8 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
import { batch } from "solid-js";
import type { ReactiveMap } from "@solid-primitives/map";
import type { ReactiveSet } from "@solid-primitives/set";
import type {
Server as APIServer,
AllMemberResponse,
BannedUser,
Category,
DataBanCreate,
DataCreateEmoji,
DataCreateServerChannel,
DataEditRole,
DataEditServer,
Override,
OverrideField,
Role,
} from "stoat-api";
import { decodeTime } from "ulid";
import type { ServerCollection } from "../collections/ServerCollection.js";
import { hydrate } from "../hydration/index.js";
import type { ServerFlags } from "../hydration/server.js";
import {
bitwiseAndEq,
calculatePermission,
} from "../permissions/calculator.js";
import { Permission } from "../permissions/definitions.js";
import type { Channel } from "./Channel.js";
import type { Emoji } from "./Emoji.js";
import type { File } from "./File.js";
import { ChannelInvite } from "./Invite.js";
import { ServerBan } from "./ServerBan.js";
import { ServerMember } from "./ServerMember.js";
import { ServerRole } from "./ServerRole.js";
import { User } from "./User.js";
/**
* Server Class
*/
export class Server {
readonly #collection: ServerCollection;
readonly id: string;
/**
* Construct Server
* @param collection Collection
* @param id Id
*/
constructor(collection: ServerCollection, id: string) {
this.#collection = collection;
this.id = id;
}
/**
* Convert to string
* @returns 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));
}
/**
* Owner's user ID
*/
get ownerId(): string {
return this.#collection.getUnderlyingObject(this.id).ownerId;
}
/**
* Owner
*/
get owner(): User | undefined {
return this.#collection.client.users.get(
this.#collection.getUnderlyingObject(this.id).ownerId,
);
}
/**
* Absolute pathname to this server in the client
*/
get path(): string {
return `/server/${this.id}`;
}
/**
* Name
*/
get name(): string {
return this.#collection.getUnderlyingObject(this.id).name;
}
/**
* Description
*/
get description(): string | undefined {
return this.#collection.getUnderlyingObject(this.id).description;
}
/**
* Icon
*/
get icon(): File | undefined {
return this.#collection.getUnderlyingObject(this.id).icon;
}
/**
* Banner
*/
get banner(): File | undefined {
return this.#collection.getUnderlyingObject(this.id).banner;
}
/**
* Channel IDs
*/
get channelIds(): ReactiveSet<string> {
return this.#collection.getUnderlyingObject(this.id).channelIds;
}
/**
* Channels
*/
get channels(): Channel[] {
return [
...this.#collection.getUnderlyingObject(this.id).channelIds.values(),
]
.map((id) => this.#collection.client.channels.get(id)!)
.filter((x) => x);
}
/**
* Categories
*/
get categories(): Category[] | undefined {
return this.#collection.getUnderlyingObject(this.id).categories;
}
/**
* System message channels
*/
get systemMessages(): APIServer["system_messages"] {
return this.#collection.getUnderlyingObject(this.id).systemMessages;
}
/**
* Roles
*/
get roles(): ReactiveMap<string, ServerRole> {
return this.#collection.getUnderlyingObject(this.id).roles;
}
/**
* Default permissions
*/
get defaultPermissions(): bigint {
return this.#collection.getUnderlyingObject(this.id).defaultPermissions;
}
/**
* Server flags
*/
get flags(): ServerFlags {
return this.#collection.getUnderlyingObject(this.id).flags;
}
/**
* Whether analytics are enabled for this server
*/
get analytics(): boolean {
return this.#collection.getUnderlyingObject(this.id).analytics;
}
/**
* Whether this server is publicly discoverable
*/
get discoverable(): boolean {
return this.#collection.getUnderlyingObject(this.id).discoverable;
}
/**
* Whether this server is marked as mature
*/
get mature(): boolean {
return this.#collection.getUnderlyingObject(this.id).nsfw;
}
/**
* Get an array of ordered categories with their respective channels.
* Uncategorised channels are returned in `id="default"` category.
*/
get orderedChannels(): (Omit<Category, "channels"> & {
channels: Channel[];
})[] {
const uncategorised = new Set(this.channels.map((channel) => channel.id));
const elements = [];
let defaultCategory;
const categories = this.categories;
if (categories) {
for (const category of categories) {
const channels = [];
for (const key of category.channels) {
if (uncategorised.delete(key)) {
channels.push(this.#collection.client.channels.get(key)!);
}
}
const cat = {
...category,
channels,
};
if (cat.id === "default") {
if (channels.length === 0) continue;
defaultCategory = cat;
}
elements.push(cat);
}
}
// force Default category for client logic
// if (uncategorised.size > 0) {
const channels = [...uncategorised].map(
(key) => this.#collection.client.channels.get(key)!,
);
if (defaultCategory) {
defaultCategory.channels = [...defaultCategory.channels, ...channels];
} else {
elements.unshift({
id: "default",
title: "Default",
channels,
});
}
// }
return elements;
}
/**
* Default channel for this server
*/
get defaultChannel(): Channel | undefined {
return this.orderedChannels.find((cat) => cat.channels.length)?.channels[0];
}
/**
* Get an ordered array of roles with their IDs attached.
* The highest ranking roles will be first followed by lower
* ranking roles. This is dictated by the "rank" property
* which is smaller for higher priority roles.
*/
get orderedRoles(): {
name: string;
permissions: { a: bigint, d: bigint };
colour?: string | null;
hoist?: boolean;
rank?: number;
id: string;
}[] {
const roles = this.roles;
return roles
? [...roles.values()].sort((a, b) => (a.rank || 0) - (b.rank || 0))
: [];
}
/**
* Check whether the server is currently unread
* @returns Whether the server is unread
*/
get unread(): boolean {
return !!this.channels.find((channel) => channel.unread);
}
/**
* Find all message IDs of unread messages
* @returns Array of message IDs which are unread
*/
get mentions(): string[] {
const arr = this.channels.map((channel) =>
Array.from(channel.mentions?.values() ?? []),
);
return ([] as string[]).concat(...arr);
}
/**
* URL to the server's icon
*/
get iconURL(): string | undefined {
return this.icon?.createFileURL();
}
/**
* URL to the server's animated icon
*/
get animatedIconURL(): string | undefined {
return this.icon?.createFileURL(true);
}
/**
* URL to the server's banner
*/
get bannerURL(): string | undefined {
return this.banner?.createFileURL();
}
/**
* Own member object for this server
*/
get member(): ServerMember | undefined {
return this.#collection.client.serverMembers.getByKey({
server: this.id,
user: this.#collection.client.user!.id,
});
}
/**
* Permission the currently authenticated user has against this server
*/
get permission(): bigint {
return calculatePermission(this.#collection.client, this);
}
/**
* Check whether we have a given permission in a server
* @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 server
* @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
);
}
/**
* Helper function to retrieve cached server member by their ID in this server
* @param userId User's ID
* @returns Server Member (if cached)
*/
getMember(userId: string): ServerMember | undefined {
return this.#collection.client.serverMembers.getByKey({
server: this.id,
user: userId,
});
}
/**
* Create a channel
* @param data Channel create route data
* @returns The newly-created channel
*/
async createChannel(data: DataCreateServerChannel): Promise<Channel> {
const channel = await this.#collection.client.api.post(
`/servers/${this.id as ""}/channels`,
data,
);
return this.#collection.client.channels.getOrCreate(channel._id, channel);
}
/**
* Edit a server
* @param data Changes
*/
async edit(data: DataEditServer): Promise<void> {
this.#collection.updateUnderlyingObject(
this.id,
hydrate(
"server",
await this.#collection.client.api.patch(
`/servers/${this.id as ""}`,
data,
),
this.#collection.client,
false,
),
);
}
/**
* Set ordering of roles
* @param roleIds Role IDs
*/
async setRoleOrdering(roleIds: string[]): Promise<void> {
this.#collection.updateUnderlyingObject(
this.id,
hydrate(
"server",
await this.#collection.client.api.patch(
`/servers/${this.id as ""}/roles/ranks`,
{
ranks: roleIds,
},
),
this.#collection.client,
false,
),
);
}
/**
* Delete the underlying server
* @param leaveEvent Whether we are leaving
*/
$delete(leaveEvent?: boolean): void {
batch(() => {
const server = this.#collection.client.servers.getUnderlyingObject(
this.id,
);
// Avoid race conditions
if (server.id) {
this.#collection.client.emit(
leaveEvent ? "serverLeave" : "serverDelete",
server,
);
for (const channel of this.channelIds) {
this.#collection.client.channels.delete(channel);
}
this.#collection.delete(this.id);
}
// TODO: delete members, emoji, etc
});
}
/**
* Delete or leave a server
* @param leaveSilently Whether to not send a message on leave
*/
async delete(leaveSilently?: boolean): Promise<void> {
await this.#collection.client.api.delete(`/servers/${this.id as ""}`, {
leave_silently: leaveSilently,
});
this.$delete();
}
/**
* Mark a server as read
*/
async ack(): Promise<void> {
batch(() => {
for (const channel of this.channels) {
channel.ack(undefined, false, true);
}
});
await this.#collection.client.api.put(`/servers/${this.id}/ack`);
}
/**
* Ban user from this server
* @param user User
* @param options Ban options
*/
async banUser(
user: string | User | ServerMember,
options: DataBanCreate = {},
): Promise<ServerBan> {
const userId =
user instanceof User
? user.id
: user instanceof ServerMember
? user.id.user
: user;
const ban = await this.#collection.client.api.put(
`/servers/${this.id as ""}/bans/${userId as ""}`,
options,
);
return new ServerBan(this.#collection.client, ban);
}
/**
* Kick user from this server
* @param user User
*/
async kickUser(user: string | User | ServerMember): Promise<void> {
return await this.#collection.client.api.delete(
`/servers/${this.id as ""}/members/${typeof user === "string"
? user
: user instanceof User
? user.id
: user.id.user
}`,
);
}
/**
* Pardon user's ban
* @param user User
*/
async unbanUser(user: string | User): Promise<void> {
const userId = user instanceof User ? user.id : user;
return await this.#collection.client.api.delete(
`/servers/${this.id as ""}/bans/${userId}`,
);
}
/**
* Fetch a server's invites
* @returns An array of the server's invites
*/
async fetchInvites(): Promise<ChannelInvite[]> {
const invites = await this.#collection.client.api.get(
`/servers/${this.id as ""}/invites`,
);
return invites.map((invite) =>
ChannelInvite.from(this.#collection.client, invite),
);
}
/**
* Fetch a server's bans
* @returns An array of the server's bans.
*/
async fetchBans(): Promise<ServerBan[]> {
const { users, bans } = await this.#collection.client.api.get(
`/servers/${this.id as ""}/bans`,
);
const userDict = users.reduce(
(d, c) => ({ ...d, [c._id]: c }),
{} as Record<string, BannedUser>,
);
return bans.map(
(ban) =>
new ServerBan(this.#collection.client, ban, userDict[ban._id.user]),
);
}
/**
* Set role permissions
* @param roleId Role Id, set to 'default' to affect all users
* @param permissions Permission value
*/
async setPermissions(
roleId = "default",
permissions: Override | number,
): Promise<APIServer> {
return await this.#collection.client.api.put(
`/servers/${this.id as ""}/permissions/${roleId as ""}`,
{ permissions: permissions as Override },
);
}
/**
* Create role
* @param name Role name
*/
async createRole(name: string): Promise<{ id: string; role: Role }> {
return await this.#collection.client.api.post(
`/servers/${this.id as ""}/roles`,
{
name,
},
);
}
/**
* Edit a role
* @param roleId Role ID
* @param data Role editing route data
*/
async editRole(roleId: string, data: DataEditRole): Promise<ServerRole> {
const updated = await this.#collection.client.api.patch(
`/servers/${this.id as ""}/roles/${roleId as ""}`,
data,
);
const role = new ServerRole(
this.#collection.client,
this.id,
roleId,
updated,
);
this.roles.set(roleId, role);
return role;
}
/**
* Delete role
* @param roleId Role ID
*/
async deleteRole(roleId: string): Promise<void> {
return await this.#collection.client.api.delete(
`/servers/${this.id as ""}/roles/${roleId as ""}`,
);
}
/**
* Fetch a server member
* @param user User
* @returns Server member object
*/
async fetchMember(user: User | string): Promise<ServerMember> {
const userId = typeof user === "string" ? user : user.id;
const existing = this.#collection.client.serverMembers.getByKey({
server: this.id,
user: userId,
});
if (existing) return existing;
return this.#collection.client.serverMembers.fetch(this.id, userId);
}
#synced: undefined | "partial" | "full";
/**
* Optimised member fetch route
* @param excludeOffline
*/
async syncMembers(excludeOffline?: boolean): Promise<void> {
if (this.#synced && (this.#synced === "full" || excludeOffline)) return;
const data = await this.#collection.client.api.get(
`/servers/${this.id as ""}/members`,
{ exclude_offline: excludeOffline },
);
batch(() => {
if (excludeOffline) {
for (let i = 0; i < data.users.length; i++) {
const user = data.users[i];
if (user.online) {
this.#collection.client.users.getOrCreate(user._id, user);
this.#collection.client.serverMembers.getOrCreate(
data.members[i]._id,
data.members[i],
);
}
}
} else {
for (let i = 0; i < data.users.length; i++) {
this.#collection.client.users.getOrCreate(
data.users[i]._id,
data.users[i],
);
this.#collection.client.serverMembers.getOrCreate(
data.members[i]._id,
data.members[i],
);
}
}
});
}
/**
* Reset member sync status
*/
resetSyncStatus(): void {
this.#synced = undefined;
}
/**
* Fetch a server's members
* @returns List of the server's members and their user objects
*/
async fetchMembers(): Promise<{ members: ServerMember[]; users: User[] }> {
const data = (await this.#collection.client.api.get(
// @ts-expect-error TODO weird typing issue
`/servers/${this.id as ""}/members`,
)) as AllMemberResponse;
return batch(() => ({
members: data.members.map((member) =>
this.#collection.client.serverMembers.getOrCreate(member._id, member),
),
users: data.users.map((user) =>
this.#collection.client.users.getOrCreate(user._id, user),
),
}));
}
/**
* Query members from a server by name
* @param query Name
* @returns List of the server's members and their user objects
*/
async queryMembersExperimental(
query: string,
): Promise<{ members: ServerMember[]; users: User[] }> {
const data = (await this.#collection.client.api.get(
`/servers/${this.id as ""
}/members_experimental_query?experimental_api=true&query=${encodeURIComponent(
query,
)}` as never,
)) as AllMemberResponse;
return batch(() => ({
members: data.members.map((member) =>
this.#collection.client.serverMembers.getOrCreate(member._id, member),
),
users: data.users.map((user) =>
this.#collection.client.users.getOrCreate(user._id, user),
),
}));
}
/**
* Create an emoji on the server
* @param autumnId Autumn Id
* @param options Options
*/
async createEmoji(
autumnId: string,
options: Omit<DataCreateEmoji, "parent">,
): Promise<Emoji> {
const emoji = await this.#collection.client.api.put(
`/custom/emoji/${autumnId as ""}`,
{
parent: {
type: "Server",
id: this.id,
},
...options,
},
);
return this.#collection.client.emojis.getOrCreate(emoji._id, emoji, true);
}
/**
* Fetch a server's emoji
* @returns List of server emoji
*/
async fetchEmojis(): Promise<Emoji[]> {
const emojis = await this.#collection.client.api.get(
`/servers/${this.id as ""}/emojis`,
);
return batch(() =>
emojis.map((emoji) =>
this.#collection.client.emojis.getOrCreate(emoji._id, emoji),
),
);
}
/**
* All emojis tied to this server
*/
get emojis(): Emoji[] {
return this.#collection.client.emojis.filter(
(emoji) => emoji.parent.type === "Server" && emoji.parent.id === this.id,
);
}
/**
* Delete emoji
* @param emojiId Emoji ID
*/
async deleteEmoji(emojiId: string): Promise<void> {
await this.#collection.client.api.delete(`/custom/emoji/${emojiId}`);
}
}