-
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathClient.ts
More file actions
462 lines (406 loc) · 13.2 KB
/
Client.ts
File metadata and controls
462 lines (406 loc) · 13.2 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
import type { Accessor, Setter } from "solid-js";
import { batch, createSignal } from "solid-js";
import { AsyncEventEmitter } from "@vladfrangu/async_event_emitter";
import { API } from "stoat-api";
import type { DataLogin, RevoltConfig, Role } from "stoat-api";
import type { Channel } from "./classes/Channel.js";
import type { Emoji } from "./classes/Emoji.js";
import type { Message } from "./classes/Message.js";
import type { Server } from "./classes/Server.js";
import type { ServerMember } from "./classes/ServerMember.js";
import type { User } from "./classes/User.js";
import { AccountCollection } from "./collections/AccountCollection.js";
import { BotCollection } from "./collections/BotCollection.js";
import { ChannelCollection } from "./collections/ChannelCollection.js";
import { ChannelUnreadCollection } from "./collections/ChannelUnreadCollection.js";
import { ChannelWebhookCollection } from "./collections/ChannelWebhookCollection.js";
import { EmojiCollection } from "./collections/EmojiCollection.js";
import { MessageCollection } from "./collections/MessageCollection.js";
import { ServerCollection } from "./collections/ServerCollection.js";
import { ServerMemberCollection } from "./collections/ServerMemberCollection.js";
import { SessionCollection } from "./collections/SessionCollection.js";
import { UserCollection } from "./collections/UserCollection.js";
import {
ConnectionState,
EventClient,
type EventClientOptions,
} from "./events/EventClient.js";
import { ProtocolV1, handleEvent } from "./events/v1.js";
import type { HydratedChannel } from "./hydration/channel.js";
import type { HydratedEmoji } from "./hydration/emoji.js";
import type { HydratedMessage } from "./hydration/message.js";
import type { HydratedServer } from "./hydration/server.js";
import type { HydratedServerMember } from "./hydration/serverMember.js";
import type { HydratedUser } from "./hydration/user.js";
import { RE_CHANNELS, RE_MENTIONS, RE_SPOILER } from "./lib/regex.js";
export type Session = { _id: string; token: string; user_id: string } | string;
/**
* Events provided by the client
*/
export type Events = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: [error: any];
connected: [];
connecting: [];
disconnected: [];
ready: [];
logout: [];
policyChanges: [
policyChanges: ProtocolV1["types"]["policyChange"][],
acknowledge: () => Promise<void>,
];
messageCreate: [message: Message];
messageUpdate: [message: Message, previousMessage: HydratedMessage];
messageDelete: [message: HydratedMessage];
messageDeleteBulk: [messages: HydratedMessage[], channel?: Channel];
messageReactionAdd: [message: Message, userId: string, emoji: string];
messageReactionRemove: [message: Message, userId: string, emoji: string];
messageReactionRemoveEmoji: [message: Message, emoji: string];
channelCreate: [channel: Channel];
channelUpdate: [channel: Channel, previousChannel: HydratedChannel];
channelDelete: [channel: HydratedChannel];
channelGroupJoin: [channel: Channel, user: User];
channelGroupLeave: [channel: Channel, user?: User];
channelStartTyping: [channel: Channel, user?: User];
channelStopTyping: [channel: Channel, user?: User];
channelAcknowledged: [channel: Channel, messageId: string];
serverCreate: [server: Server];
serverUpdate: [server: Server, previousServer: HydratedServer];
serverDelete: [server: HydratedServer];
serverLeave: [server: HydratedServer];
serverRoleUpdate: [server: Server, roleId: string, previousRole: Role];
serverRoleDelete: [server: Server, roleId: string, role: Role];
serverMemberUpdate: [
member: ServerMember,
previousMember: HydratedServerMember,
];
serverMemberJoin: [member: ServerMember];
serverMemberLeave: [member: HydratedServerMember];
userUpdate: [user: User, previousUser: HydratedUser];
// ^ userRelationshipChanged: [user: User, previousRelationship: RelationshipStatus];
// ^ userPresenceChanged: [user: User, previousPresence: boolean];
userSettingsUpdate: [id: string, update: Record<string, [number, string]>];
emojiCreate: [emoji: Emoji];
emojiDelete: [emoji: HydratedEmoji];
};
/**
* Client options object
*/
export type ClientOptions = Partial<EventClientOptions> & {
/**
* Base URL of the API server
*/
baseURL: string;
/**
* Whether to allow partial objects to emit from events
* @default false
*/
partials: boolean;
/**
* Whether to eagerly fetch users and members for incoming events
* @default true
* @deprecated
*/
eagerFetching: boolean;
/**
* Whether to automatically sync unreads information
* @default false
*/
syncUnreads: boolean;
/**
* Whether to reconnect when disconnected
* @default true
*/
autoReconnect: boolean;
/**
* Whether to rewrite sent messages that include identifiers such as @silent
* @default true
*/
messageRewrites: boolean;
/**
* Retry delay function
* @param retryCount Count
* @returns Delay in seconds
* @default (2^x-1) ±20%
*/
retryDelayFunction(retryCount: number): number;
/**
* Check whether a channel is muted
* @param channel Channel
* @return Whether it is muted or through inheritance
* @default false
*/
channelIsMuted(channel: Channel): boolean;
/**
* Check whether a channel is exclusively muted (irrespective of server)
* @param channel Channel
* @return Whether it is exclusively muted
* @default false
*/
channelExclusiveMuted(channel: Channel): boolean;
};
/**
* Stoat.js Clients
*/
export class Client extends AsyncEventEmitter<Events> {
readonly account;
readonly bots;
readonly channels;
readonly channelUnreads;
readonly channelWebhooks;
readonly emojis;
readonly messages;
readonly servers;
readonly serverMembers;
readonly sessions;
readonly users;
readonly api: API;
readonly options: ClientOptions;
readonly events: EventClient<1>;
configuration: RevoltConfig | undefined;
#session: Session | undefined;
user: User | undefined;
readonly ready: Accessor<boolean>;
#setReady: Setter<boolean>;
readonly configured: Accessor<boolean>;
#setConfigured: Setter<boolean>;
readonly connectionFailureCount: Accessor<number>;
#setConnectionFailureCount: Setter<number>;
#reconnectTimeout: number | undefined;
/**
* Create Stoat.js Client
*/
constructor(options?: Partial<ClientOptions>, configuration?: RevoltConfig) {
super();
this.options = {
baseURL: "https://stoat.chat/api",
partials: false,
eagerFetching: true,
syncUnreads: false,
autoReconnect: true,
messageRewrites: true,
/**
* Retry delay function
* @param retryCount Count
* @returns Delay in seconds
*/
retryDelayFunction(retryCount) {
return (Math.pow(2, retryCount) - 1) * (0.8 + Math.random() * 0.4);
},
/**
* Check whether a channel is muted
* @param channel Channel
* @return Whether it is muted
*/
channelIsMuted() {
return false;
},
/**
* Check whether a channel is exclusively muted (irrespective of server)
* @param channel Channel
* @return Whether it is exclusively muted
* @default false
*/
channelExclusiveMuted() {
return false;
},
...options,
};
this.configuration = configuration;
this.api = new API({
baseURL: this.options.baseURL,
});
const [configured, setConfigured] = createSignal(configuration !== undefined);
this.configured = configured;
this.#setConfigured = setConfigured;
this.#fetchConfiguration();
const [ready, setReady] = createSignal(false);
this.ready = ready;
this.#setReady = setReady;
const [connectionFailureCount, setConnectionFailureCount] = createSignal(0);
this.connectionFailureCount = connectionFailureCount;
this.#setConnectionFailureCount = setConnectionFailureCount;
this.account = new AccountCollection(this);
this.bots = new BotCollection(this);
this.channels = new ChannelCollection(this);
this.channelUnreads = new ChannelUnreadCollection(this);
this.channelWebhooks = new ChannelWebhookCollection(this);
this.emojis = new EmojiCollection(this);
this.messages = new MessageCollection(this);
this.servers = new ServerCollection(this);
this.serverMembers = new ServerMemberCollection(this);
this.sessions = new SessionCollection(this);
this.users = new UserCollection(this);
this.events = new EventClient(1, "json", this.options);
this.events.on("error", (error) => this.emit("error", error));
this.events.on("state", (state) => {
switch (state) {
case ConnectionState.Connected:
batch(() => {
this.servers.forEach((server) => server.resetSyncStatus());
this.#setConnectionFailureCount(0);
this.emit("connected");
});
break;
case ConnectionState.Connecting:
this.emit("connecting");
break;
case ConnectionState.Disconnected:
this.emit("disconnected");
if (this.options.autoReconnect) {
this.#reconnectTimeout = setTimeout(
() => this.connect(),
this.options.retryDelayFunction(this.connectionFailureCount()) *
1e3,
) as never;
this.#setConnectionFailureCount((count) => count + 1);
}
break;
}
});
this.events.on("event", (event) =>
handleEvent(this, event, this.#setReady),
);
}
/**
* Current session id
*/
get sessionId(): string | undefined {
return typeof this.#session === "string" ? undefined : this.#session?._id;
}
/**
* Get authentication header
*/
get authenticationHeader(): [string, string] {
return typeof this.#session === "string"
? ["X-Bot-Token", this.#session]
: ["X-Session-Token", this.#session?.token as string];
}
/**
* Connect to Revolt
*/
connect(): void {
clearTimeout(this.#reconnectTimeout);
this.events.disconnect();
this.#setReady(false);
this.events.connect(
this.configuration?.ws ?? "wss://stoat.chat/events",
typeof this.#session === "string" ? this.#session : this.#session!.token,
);
}
/**
* Fetches the configuration of the server if it has not been already fetched.
*/
async #fetchConfiguration(): Promise<void> {
if (!this.configuration) {
this.configuration = await this.api.get("/");
this.#setConfigured(true);
}
}
/**
* Update API object to use authentication.
*/
#updateHeaders(): void {
(this.api as API) = new API({
baseURL: this.options.baseURL,
authentication: {
revolt: this.#session,
},
});
}
/**
* Log in with auth data, creating a new session in the process.
* @param details Login data object
* @returns An on-boarding function if on-boarding is required, undefined otherwise
*/
async login(details: DataLogin): Promise<void> {
await this.#fetchConfiguration();
const data = await this.api.post("/auth/session/login", details);
if (data.result === "Success") {
this.#session = data;
// TODO: return await this.connect();
} else {
throw "MFA not implemented!";
}
}
/**
* Use an existing session
*/
useExistingSession(session: Session): void {
this.#session = session;
this.#updateHeaders();
}
/**
* Log in as a bot
* @param token Bot token
*/
async loginBot(token: string): Promise<void> {
await this.#fetchConfiguration();
this.#session = token;
this.#updateHeaders();
this.connect();
}
/**
* Prepare a markdown-based message to be displayed to the user as plain text.
* @param source Source markdown text
* @returns Modified plain text
*/
markdownToText(source: string): string {
return source
.replace(RE_MENTIONS, (sub: string, id: string) => {
const user = this.users.get(id as string);
if (user) {
return `@${user.username}`;
}
return sub;
})
.replace(RE_CHANNELS, (sub: string, id: string) => {
const channel = this.channels.get(id as string);
if (channel) {
return `#${channel.displayName}`;
}
return sub;
})
.replace(RE_SPOILER, "<spoiler>");
}
/**
* Proxy a file through January.
* @param url URL to proxy
* @returns Proxied media URL
*/
proxyFile(url: string): string | undefined {
if (this.configuration?.features.january.enabled) {
return `${this.configuration.features.january.url}/proxy?url=${encodeURIComponent(
url,
)}`;
} else {
return url;
}
}
/**
* Upload a file
* @param tag Tag
* @param file File
* @param uploadUrl Media server upload route
*/
async uploadFile(
tag: string,
file: File,
uploadUrl?: string,
): Promise<string> {
const body = new FormData();
body.append("file", file);
const [key, value] = this.authenticationHeader;
const data: { id: string } = await fetch(
`${uploadUrl ?? this.configuration?.features.autumn.url}/${tag}`,
{
method: "POST",
body,
headers: {
[key]: value,
},
},
).then((res) => res.json());
return data.id;
}
}