diff --git a/src/gateway/Server.ts b/src/gateway/Server.ts
index 9fba2d4c..5921e9b5 100644
--- a/src/gateway/Server.ts
+++ b/src/gateway/Server.ts
@@ -19,13 +19,7 @@
import "missing-native-js-functions";
import dotenv from "dotenv";
dotenv.config();
-import {
- closeDatabase,
- Config,
- initDatabase,
- initEvent,
- Sentry,
-} from "@spacebar/util";
+import { closeDatabase, Config, initDatabase, initEvent, Sentry } from "@spacebar/util";
import ws from "ws";
import { Connection } from "./events/Connection";
import http from "http";
@@ -36,15 +30,7 @@ export class Server {
public server: http.Server;
public production: boolean;
- constructor({
- port,
- server,
- production,
- }: {
- port: number;
- server?: http.Server;
- production?: boolean;
- }) {
+ constructor({ port, server, production }: { port: number; server?: http.Server; production?: boolean }) {
this.port = port;
this.production = production || false;
diff --git a/src/gateway/events/Connection.ts b/src/gateway/events/Connection.ts
index 1991ebbe..2150ec7b 100644
--- a/src/gateway/events/Connection.ts
+++ b/src/gateway/events/Connection.ts
@@ -40,15 +40,9 @@ try {
// TODO: specify rate limit in config
// TODO: check msg max size
-export async function Connection(
- this: WS.Server,
- socket: WebSocket,
- request: IncomingMessage,
-) {
+export async function Connection(this: WS.Server, socket: WebSocket, request: IncomingMessage) {
const forwardedFor = Config.get().security.forwardedFor;
- const ipAddress = forwardedFor
- ? (request.headers[forwardedFor] as string)
- : request.socket.remoteAddress;
+ const ipAddress = forwardedFor ? (request.headers[forwardedFor] as string) : request.socket.remoteAddress;
socket.ipAddress = ipAddress;
@@ -85,21 +79,17 @@ export async function Connection(
const { searchParams } = new URL(`http://localhost${request.url}`);
// @ts-ignore
socket.encoding = searchParams.get("encoding") || "json";
- if (!["json", "etf"].includes(socket.encoding))
- return socket.close(CLOSECODES.Decode_error);
+ if (!["json", "etf"].includes(socket.encoding)) return socket.close(CLOSECODES.Decode_error);
- if (socket.encoding === "etf" && !erlpack)
- throw new Error("Erlpack is not installed: 'npm i erlpack'");
+ if (socket.encoding === "etf" && !erlpack) throw new Error("Erlpack is not installed: 'npm i erlpack'");
socket.version = Number(searchParams.get("version")) || 8;
- if (socket.version != 8)
- return socket.close(CLOSECODES.Invalid_API_version);
+ if (socket.version != 8) return socket.close(CLOSECODES.Invalid_API_version);
// @ts-ignore
socket.compress = searchParams.get("compress") || "";
if (socket.compress) {
- if (socket.compress !== "zlib-stream")
- return socket.close(CLOSECODES.Decode_error);
+ if (socket.compress !== "zlib-stream") return socket.close(CLOSECODES.Decode_error);
socket.deflate = new Deflate();
socket.inflate = new Inflate();
}
diff --git a/src/gateway/events/Message.ts b/src/gateway/events/Message.ts
index 52d9edd8..8415d04e 100644
--- a/src/gateway/events/Message.ts
+++ b/src/gateway/events/Message.ts
@@ -60,22 +60,15 @@ export async function Message(this: WebSocket, buffer: WS.Data) {
}
} else return this.close(CLOSECODES.Decode_error);
- if (process.env.WS_VERBOSE)
- console.log(`[Websocket] Incomming message: ${JSON.stringify(data)}`);
+ if (process.env.WS_VERBOSE) console.log(`[Websocket] Incomming message: ${JSON.stringify(data)}`);
if (process.env.WS_DUMP) {
const id = this.session_id || "unknown";
await fs.mkdir(path.join("dump", id), { recursive: true });
- await fs.writeFile(
- path.join("dump", id, `${Date.now()}.in.json`),
- JSON.stringify(data, null, 2),
- );
+ await fs.writeFile(path.join("dump", id, `${Date.now()}.in.json`), JSON.stringify(data, null, 2));
- if (!this.session_id)
- console.log(
- "[Gateway] Unknown session id, dumping to unknown folder",
- );
+ if (!this.session_id) console.log("[Gateway] Unknown session id, dumping to unknown folder");
}
check.call(this, PayloadSchema, data);
@@ -102,7 +95,7 @@ export async function Message(this: WebSocket, buffer: WS.Data) {
const ret = await OPCodeHandler.call(this, data);
Sentry.setUser({ id: this.user_id });
return ret;
- },
+ }
);
} catch (error) {
Sentry.captureException(error, {
diff --git a/src/gateway/listener/listener.ts b/src/gateway/listener/listener.ts
index b624b8e0..612f7313 100644
--- a/src/gateway/listener/listener.ts
+++ b/src/gateway/listener/listener.ts
@@ -42,10 +42,7 @@ import { Recipient } from "@spacebar/util";
// Sharding: calculate if the current shard id matches the formula: shard_id = (guild_id >> 22) % num_shards
// https://discord.com/developers/docs/topics/gateway#sharding
-export function handlePresenceUpdate(
- this: WebSocket,
- { event, acknowledge, data }: EventOpts,
-) {
+export function handlePresenceUpdate(this: WebSocket, { event, acknowledge, data }: EventOpts) {
acknowledge?.();
if (event === EVENTEnum.PresenceUpdate) {
return Send(this, {
@@ -96,11 +93,7 @@ export async function setupListener(this: WebSocket) {
this.events[this.user_id] = await listenEvent(this.user_id, consumer, opts);
relationships.forEach(async (relationship) => {
- this.events[relationship.to_id] = await listenEvent(
- relationship.to_id,
- handlePresenceUpdate.bind(this),
- opts,
- );
+ this.events[relationship.to_id] = await listenEvent(relationship.to_id, handlePresenceUpdate.bind(this), opts);
});
dm_channels.forEach(async (channel) => {
@@ -113,16 +106,8 @@ export async function setupListener(this: WebSocket) {
this.events[guild.id] = await listenEvent(guild.id, consumer, opts);
guild.channels.forEach(async (channel) => {
- if (
- permission
- .overwriteChannel(channel.permission_overwrites ?? [])
- .has("VIEW_CHANNEL")
- ) {
- this.events[channel.id] = await listenEvent(
- channel.id,
- consumer,
- opts,
- );
+ if (permission.overwriteChannel(channel.permission_overwrites ?? []).has("VIEW_CHANNEL")) {
+ this.events[channel.id] = await listenEvent(channel.id, consumer, opts);
}
});
});
@@ -158,7 +143,7 @@ async function consume(this: WebSocket, opts: EventOpts) {
this.member_events[data.user.id] = await listenEvent(
data.user.id,
handlePresenceUpdate.bind(this),
- this.listen_options,
+ this.listen_options
);
break;
case "GUILD_MEMBER_UPDATE":
@@ -172,11 +157,7 @@ async function consume(this: WebSocket, opts: EventOpts) {
opts.cancel();
break;
case "CHANNEL_CREATE":
- if (
- !permission
- .overwriteChannel(data.permission_overwrites)
- .has("VIEW_CHANNEL")
- ) {
+ if (!permission.overwriteChannel(data.permission_overwrites).has("VIEW_CHANNEL")) {
return;
}
this.events[id] = await listenEvent(id, consumer, listenOpts);
@@ -185,7 +166,7 @@ async function consume(this: WebSocket, opts: EventOpts) {
this.events[data.user.id] = await listenEvent(
data.user.id,
handlePresenceUpdate.bind(this),
- this.listen_options,
+ this.listen_options
);
break;
case "GUILD_CREATE":
@@ -193,11 +174,7 @@ async function consume(this: WebSocket, opts: EventOpts) {
break;
case "CHANNEL_UPDATE": {
const exists = this.events[id];
- if (
- permission
- .overwriteChannel(data.permission_overwrites)
- .has("VIEW_CHANNEL")
- ) {
+ if (permission.overwriteChannel(data.permission_overwrites).has("VIEW_CHANNEL")) {
if (exists) break;
this.events[id] = await listenEvent(id, consumer, listenOpts);
} else {
diff --git a/src/gateway/opcodes/Identify.ts b/src/gateway/opcodes/Identify.ts
index 330ce561..90c001df 100644
--- a/src/gateway/opcodes/Identify.ts
+++ b/src/gateway/opcodes/Identify.ts
@@ -16,15 +16,7 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-import {
- CLOSECODES,
- Capabilities,
- OPCODES,
- Payload,
- Send,
- WebSocket,
- setupListener,
-} from "@spacebar/gateway";
+import { CLOSECODES, Capabilities, OPCODES, Payload, Send, WebSocket, setupListener } from "@spacebar/gateway";
import {
Application,
Config,
@@ -109,9 +101,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
this.shard_count <= 0
) {
// TODO: why do we even care about this right now?
- console.log(
- `[Gateway] Invalid sharding from ${user.id}: ${identify.shard}`,
- );
+ console.log(`[Gateway] Invalid sharding from ${user.id}: ${identify.shard}`);
return this.close(CLOSECODES.Invalid_shard);
}
}
@@ -134,93 +124,77 @@ export async function onIdentify(this: WebSocket, data: Payload) {
// * guild members for this user
// * recipients ( dm channels )
// * the bot application, if it exists
- const [, application, read_states, members, recipients] = await Promise.all(
- [
- session.save(),
-
- Application.findOne({
- where: { id: this.user_id },
- select: ["id", "flags"],
- }),
-
- ReadState.find({
- where: { user_id: this.user_id },
- select: [
- "id",
- "channel_id",
- "last_message_id",
- "last_pin_timestamp",
- "mention_count",
- ],
- }),
-
- Member.find({
- where: { id: this.user_id },
- select: {
- // We only want some member props
- ...Object.fromEntries(
- MemberPrivateProjection.map((x) => [x, true]),
- ),
- settings: true, // guild settings
- roles: { id: true }, // the full role is fetched from the `guild` relation
-
- // TODO: we don't really need every property of
- // guild channels, emoji, roles, stickers
- // but we do want almost everything from guild.
- // How do you do that without just enumerating the guild props?
- guild: Object.fromEntries(
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- getDatabase()!
- .getMetadata(Guild)
- .columns.map((x) => [x.propertyName, true]),
- ),
- },
- relations: [
- "guild",
- "guild.channels",
- "guild.emojis",
- "guild.roles",
- "guild.stickers",
- "roles",
-
- // For these entities, `user` is always just the logged in user we fetched above
- // "user",
- ],
- }),
-
- Recipient.find({
- where: { user_id: this.user_id, closed: false },
- relations: [
- "channel",
- "channel.recipients",
- "channel.recipients.user",
- ],
- select: {
- channel: {
+ const [, application, read_states, members, recipients] = await Promise.all([
+ session.save(),
+
+ Application.findOne({
+ where: { id: this.user_id },
+ select: ["id", "flags"],
+ }),
+
+ ReadState.find({
+ where: { user_id: this.user_id },
+ select: ["id", "channel_id", "last_message_id", "last_pin_timestamp", "mention_count"],
+ }),
+
+ Member.find({
+ where: { id: this.user_id },
+ select: {
+ // We only want some member props
+ ...Object.fromEntries(MemberPrivateProjection.map((x) => [x, true])),
+ settings: true, // guild settings
+ roles: { id: true }, // the full role is fetched from the `guild` relation
+
+ // TODO: we don't really need every property of
+ // guild channels, emoji, roles, stickers
+ // but we do want almost everything from guild.
+ // How do you do that without just enumerating the guild props?
+ guild: Object.fromEntries(
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ getDatabase()!
+ .getMetadata(Guild)
+ .columns.map((x) => [x.propertyName, true])
+ ),
+ },
+ relations: [
+ "guild",
+ "guild.channels",
+ "guild.emojis",
+ "guild.roles",
+ "guild.stickers",
+ "roles",
+
+ // For these entities, `user` is always just the logged in user we fetched above
+ // "user",
+ ],
+ }),
+
+ Recipient.find({
+ where: { user_id: this.user_id, closed: false },
+ relations: ["channel", "channel.recipients", "channel.recipients.user"],
+ select: {
+ channel: {
+ id: true,
+ flags: true,
+ // is_spam: true, // TODO
+ last_message_id: true,
+ last_pin_timestamp: true,
+ type: true,
+ icon: true,
+ name: true,
+ owner_id: true,
+ recipients: {
+ // we don't actually need this ID or any other information about the recipient info,
+ // but typeorm does not select anything from the users relation of recipients unless we select
+ // at least one column.
id: true,
- flags: true,
- // is_spam: true, // TODO
- last_message_id: true,
- last_pin_timestamp: true,
- type: true,
- icon: true,
- name: true,
- owner_id: true,
- recipients: {
- // we don't actually need this ID or any other information about the recipient info,
- // but typeorm does not select anything from the users relation of recipients unless we select
- // at least one column.
- id: true,
- // We only want public user data for each dm channel
- user: Object.fromEntries(
- PublicUserProjection.map((x) => [x, true]),
- ),
- },
+ // We only want public user data for each dm channel
+ user: Object.fromEntries(PublicUserProjection.map((x) => [x, true])),
},
},
- }),
- ],
- );
+ },
+ }),
+ ]);
// We forgot to migrate user settings from the JSON column of `users`
// to the `user_settings` table theyre in now,
@@ -273,9 +247,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
return perms.has("VIEW_CHANNEL");
})
.map((channel) => {
- channel.position = member.guild.channel_ordering.indexOf(
- channel.id,
- );
+ channel.position = member.guild.channel_ordering.indexOf(channel.id);
return channel;
})
.sort((a, b) => a.position - b.position);
@@ -294,18 +266,15 @@ export async function onIdentify(this: WebSocket, data: Payload) {
});
// Generate user_guild_settings
- const user_guild_settings_entries: ReadyUserGuildSettingsEntries[] =
- members.map((x) => ({
- ...DefaultUserGuildSettings,
- ...x.settings,
- guild_id: x.guild_id,
- channel_overrides: Object.entries(
- x.settings.channel_overrides ?? {},
- ).map((y) => ({
- ...y[1],
- channel_id: y[0],
- })),
- }));
+ const user_guild_settings_entries: ReadyUserGuildSettingsEntries[] = members.map((x) => ({
+ ...DefaultUserGuildSettings,
+ ...x.settings,
+ guild_id: x.guild_id,
+ channel_overrides: Object.entries(x.settings.channel_overrides ?? {}).map((y) => ({
+ ...y[1],
+ channel_id: y[0],
+ })),
+ }));
// Popultaed with users from private channels, relationships.
// Uses a set to dedupe for us.
@@ -320,16 +289,11 @@ export async function onIdentify(this: WebSocket, data: Payload) {
const channel = r.channel as DMChannel;
// Remove ourself from the list of other users in dm channel
- channel.recipients = channel.recipients.filter(
- (recipient) => recipient.user.id !== this.user_id,
- );
+ channel.recipients = channel.recipients.filter((recipient) => recipient.user.id !== this.user_id);
- const channelUsers = channel.recipients?.map((recipient) =>
- recipient.user.toPublicUser(),
- );
+ const channelUsers = channel.recipients?.map((recipient) => recipient.user.toPublicUser());
- if (channelUsers && channelUsers.length > 0)
- channelUsers.forEach((user) => users.add(user));
+ if (channelUsers && channelUsers.length > 0) channelUsers.forEach((user) => users.add(user));
return {
id: channel.id,
@@ -386,9 +350,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
const d: ReadyEventData = {
v: 9,
- application: application
- ? { id: application.id, flags: application.flags }
- : undefined,
+ application: application ? { id: application.id, flags: application.flags } : undefined,
user: user.toPrivateUser(),
user_settings: user.settings,
guilds: this.capabilities.has(Capabilities.FLAGS.CLIENT_STATE_V2)
@@ -413,15 +375,11 @@ export async function onIdentify(this: WebSocket, data: Payload) {
sessions: allSessions,
resume_gateway_url:
- Config.get().gateway.endpointClient ||
- Config.get().gateway.endpointPublic ||
- "ws://127.0.0.1:3001",
+ Config.get().gateway.endpointClient || Config.get().gateway.endpointPublic || "ws://127.0.0.1:3001",
// lol hack whatever
required_action:
- Config.get().login.requireVerification && !user.verified
- ? "REQUIRE_VERIFIED_EMAIL"
- : undefined,
+ Config.get().login.requireVerification && !user.verified ? "REQUIRE_VERIFIED_EMAIL" : undefined,
consents: {
personalization: {
@@ -457,10 +415,8 @@ export async function onIdentify(this: WebSocket, data: Payload) {
t: EVENTEnum.GuildCreate,
s: this.sequence++,
d: x,
- })?.catch((e) =>
- console.error(`[Gateway] error when sending bot guilds`, e),
- ),
- ),
+ })?.catch((e) => console.error(`[Gateway] error when sending bot guilds`, e))
+ )
);
// TODO: ready supplemental
diff --git a/src/gateway/opcodes/LazyRequest.ts b/src/gateway/opcodes/LazyRequest.ts
index 3c21b708..1318e30e 100644
--- a/src/gateway/opcodes/LazyRequest.ts
+++ b/src/gateway/opcodes/LazyRequest.ts
@@ -30,13 +30,7 @@ import {
Channel,
Permissions,
} from "@spacebar/util";
-import {
- WebSocket,
- Payload,
- handlePresenceUpdate,
- OPCODES,
- Send,
-} from "@spacebar/gateway";
+import { WebSocket, Payload, handlePresenceUpdate, OPCODES, Send } from "@spacebar/gateway";
import murmur from "murmurhash-js/murmurhash3_gc";
import { check } from "./instanceOf";
@@ -55,9 +49,7 @@ const getMostRelevantSession = (sessions: Session[]) => {
// sort sessions by relevance
sessions = sessions.sort((a, b) => {
return (
- statusMap[a.status] -
- statusMap[b.status] +
- ((a.activities?.length ?? 0) - (b.activities?.length ?? 0)) * 2
+ statusMap[a.status] - statusMap[b.status] + ((a.activities?.length ?? 0) - (b.activities?.length ?? 0)) * 2
);
});
@@ -81,10 +73,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
.leftJoinAndSelect("member.user", "user")
.leftJoinAndSelect("user.sessions", "session")
.addSelect("user.settings")
- .addSelect(
- "CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END",
- "_status",
- )
+ .addSelect("CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END", "_status")
.orderBy("role.position", "DESC")
.addOrderBy("_status", "DESC")
.addOrderBy("user.username", "ASC")
@@ -113,8 +102,8 @@ async function getMembers(guild_id: string, range: [number, number]) {
member_roles.push(
member_roles.splice(
member_roles.findIndex((x) => x.id === x.guild_id),
- 1,
- )[0],
+ 1
+ )[0]
);
const offlineItems = [];
@@ -122,7 +111,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
for (const role of member_roles) {
const [role_members, other_members] = partition(
members,
- (m: Member) => !!m.roles.find((r) => r.id === role.id),
+ (m: Member) => !!m.roles.find((r) => r.id === role.id)
);
const group = {
count: role_members.length,
@@ -133,13 +122,9 @@ async function getMembers(guild_id: string, range: [number, number]) {
groups.push(group);
for (const member of role_members) {
- const roles = member.roles
- .filter((x: Role) => x.id !== guild_id)
- .map((x: Role) => x.id);
+ const roles = member.roles.filter((x: Role) => x.id !== guild_id).map((x: Role) => x.id);
- const session: Session | undefined = getMostRelevantSession(
- member.user.sessions,
- );
+ const session: Session | undefined = getMostRelevantSession(member.user.sessions);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@@ -160,11 +145,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
},
};
- if (
- !session ||
- session.status == "invisible" ||
- session.status == "offline"
- ) {
+ if (!session || session.status == "invisible" || session.status == "offline") {
item.member.presence.status = "offline";
offlineItems.push(item);
group.count--;
@@ -192,11 +173,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
groups,
range,
members: items
- .map((x) =>
- "member" in x
- ? { ...x.member, settings: undefined }
- : undefined,
- )
+ .map((x) => ("member" in x ? { ...x.member, settings: undefined } : undefined))
.filter((x) => !!x),
};
}
@@ -204,11 +181,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
async function subscribeToMemberEvents(this: WebSocket, user_id: string) {
if (this.events[user_id]) return false; // already subscribed as friend
if (this.member_events[user_id]) return false; // already subscribed in member list
- this.member_events[user_id] = await listenEvent(
- user_id,
- handlePresenceUpdate.bind(this),
- this.listen_options,
- );
+ this.member_events[user_id] = await listenEvent(user_id, handlePresenceUpdate.bind(this), this.listen_options);
return true;
}
@@ -216,8 +189,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
// TODO: check data
check.call(this, LazyRequestSchema, d);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { guild_id, typing, channels, activities, members } =
- d as LazyRequestSchema;
+ const { guild_id, typing, channels, activities, members } = d as LazyRequestSchema;
if (members) {
// Client has requested a PRESENCE_UPDATE for specific member
@@ -225,10 +197,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
await Promise.all([
members.map(async (x) => {
if (!x) return;
- const didSubscribe = await subscribeToMemberEvents.call(
- this,
- x,
- );
+ const didSubscribe = await subscribeToMemberEvents.call(this, x);
if (!didSubscribe) return;
// if we didn't subscribe just now, this is a new subscription
@@ -270,9 +239,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
if (!Array.isArray(ranges)) throw new Error("Not a valid Array");
const member_count = await Member.count({ where: { guild_id } });
- const ops = await Promise.all(
- ranges.map((x) => getMembers(guild_id, x as [number, number])),
- );
+ const ops = await Promise.all(ranges.map((x) => getMembers(guild_id, x as [number, number])));
let list_id = "everyone";
@@ -285,10 +252,8 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
channel.permission_overwrites.forEach((overwrite) => {
const { id, allow, deny } = overwrite;
- if (allow.toBigInt() & Permissions.FLAGS.VIEW_CHANNEL)
- perms.push(`allow:${id}`);
- else if (deny.toBigInt() & Permissions.FLAGS.VIEW_CHANNEL)
- perms.push(`deny:${id}`);
+ if (allow.toBigInt() & Permissions.FLAGS.VIEW_CHANNEL) perms.push(`allow:${id}`);
+ else if (deny.toBigInt() & Permissions.FLAGS.VIEW_CHANNEL) perms.push(`deny:${id}`);
});
if (perms.length > 0) {
@@ -320,9 +285,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
op: "SYNC",
range: x.range,
})),
- online_count:
- member_count -
- (groups.find((x) => x.id == "offline")?.count ?? 0),
+ online_count: member_count - (groups.find((x) => x.id == "offline")?.count ?? 0),
member_count,
id: list_id,
guild_id,
diff --git a/src/gateway/opcodes/PresenceUpdate.ts b/src/gateway/opcodes/PresenceUpdate.ts
index 03736263..24a3461b 100644
--- a/src/gateway/opcodes/PresenceUpdate.ts
+++ b/src/gateway/opcodes/PresenceUpdate.ts
@@ -17,23 +17,14 @@
*/
import { WebSocket, Payload } from "@spacebar/gateway";
-import {
- emitEvent,
- PresenceUpdateEvent,
- Session,
- User,
- ActivitySchema,
-} from "@spacebar/util";
+import { emitEvent, PresenceUpdateEvent, Session, User, ActivitySchema } from "@spacebar/util";
import { check } from "./instanceOf";
export async function onPresenceUpdate(this: WebSocket, { d }: Payload) {
check.call(this, ActivitySchema, d);
const presence = d as ActivitySchema;
- await Session.update(
- { session_id: this.session_id },
- { status: presence.status, activities: presence.activities },
- );
+ await Session.update({ session_id: this.session_id }, { status: presence.status, activities: presence.activities });
await emitEvent({
event: "PRESENCE_UPDATE",
diff --git a/src/gateway/opcodes/VoiceStateUpdate.ts b/src/gateway/opcodes/VoiceStateUpdate.ts
index ffc143ed..a543c143 100644
--- a/src/gateway/opcodes/VoiceStateUpdate.ts
+++ b/src/gateway/opcodes/VoiceStateUpdate.ts
@@ -45,20 +45,14 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
voiceState = await VoiceState.findOneOrFail({
where: { user_id: this.user_id },
});
- if (
- voiceState.session_id !== this.session_id &&
- body.channel_id === null
- ) {
+ if (voiceState.session_id !== this.session_id && body.channel_id === null) {
//Should we also check guild_id === null?
//changing deaf or mute on a client that's not the one with the same session of the voicestate in the database should be ignored
return;
}
//If a user change voice channel between guild we should send a left event first
- if (
- voiceState.guild_id !== body.guild_id &&
- voiceState.session_id === this.session_id
- ) {
+ if (voiceState.guild_id !== body.guild_id && voiceState.session_id === this.session_id) {
await emitEvent({
event: "VOICE_STATE_UPDATE",
data: { ...voiceState, channel_id: null },
@@ -95,8 +89,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
});
//If the session changed we generate a new token
- if (voiceState.session_id !== this.session_id)
- voiceState.token = genVoiceToken();
+ if (voiceState.session_id !== this.session_id) voiceState.token = genVoiceToken();
voiceState.session_id = this.session_id;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -119,13 +112,9 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
const regions = Config.get().regions;
let guildRegion: Region;
if (guild && guild.region) {
- guildRegion = regions.available.filter(
- (r) => r.id === guild.region,
- )[0];
+ guildRegion = regions.available.filter((r) => r.id === guild.region)[0];
} else {
- guildRegion = regions.available.filter(
- (r) => r.id === regions.default,
- )[0];
+ guildRegion = regions.available.filter((r) => r.id === regions.default)[0];
}
await emitEvent({
diff --git a/src/gateway/opcodes/experiments.json b/src/gateway/opcodes/experiments.json
index 0370b5da..be6985bc 100644
--- a/src/gateway/opcodes/experiments.json
+++ b/src/gateway/opcodes/experiments.json
@@ -1,76 +1,76 @@
[
- [4047587481, 0, 0, -1, 0],
- [1509401575, 0, 1, -1, 0],
- [1865079242, 0, 1, -1, 0],
- [1962538549, 1, 0, -1, 0],
- [3816091942, 3, 2, -1, 0],
- [4130837190, 0, 10, -1, 0],
- [1861568052, 0, 1, -1, 0],
- [2290910058, 6, 2, -1, 0],
- [1578940118, 1, 1, -1, 0],
- [1571676964, 0, 1, -1, 2],
- [3640172371, 0, 2, -1, 2],
- [1658164312, 2, 1, -1, 0],
- [98883956, 1, 1, -1, 0],
- [3114091169, 0, 1, -1, 0],
- [2570684145, 4, 1, -1, 2],
- [4007615411, 0, 1, -1, 0],
- [3665310159, 2, 1, -1, 1],
- [852550504, 3, 1, -1, 0],
- [2333572067, 0, 1, -1, 0],
- [935994771, 1, 1, -1, 0],
- [1127795596, 1, 1, -1, 0],
- [4168223991, 0, 1, -1, 0],
- [18585280, 0, 1, -1, 1],
- [327482016, 0, 1, -1, 2],
- [3458098201, 7, 1, -1, 0],
- [478613943, 2, 1, -1, 1],
- [2792197902, 0, 1, -1, 2],
- [284670956, 0, 1, -1, 0],
- [2099185390, 0, 1, -1, 0],
- [1202202685, 0, 1, -1, 0],
- [2122174751, 0, 1, -1, 0],
- [3633864632, 0, 1, -1, 0],
- [3103053065, 0, 1, -1, 0],
- [820624960, 0, 1, -1, 0],
- [1134479292, 0, 1, -1, 0],
- [2511257455, 3, 1, -1, 3],
- [2599708267, 0, 1, -1, 0],
- [613180822, 1, 1, -1, 0],
- [2885186814, 0, 1, -1, 0],
- [221503477, 0, 1, -1, 0],
- [1054317075, 0, 1, -1, 3],
- [683872522, 0, 1, -1, 1],
- [1739278764, 0, 2, -1, 0],
- [2855249023, 0, 1, -1, 0],
- [3721841948, 0, 1, -1, 0],
- [1285203515, 0, 1, -1, 0],
- [1365487849, 6, 1, -1, 0],
- [955229746, 0, 1, -1, 0],
- [3128009767, 0, 10, -1, 0],
- [441885003, 0, 1, -1, 0],
- [3433971238, 0, 1, -1, 2],
- [1038765354, 3, 1, -1, 0],
- [1174347196, 0, 1, -1, 0],
- [3649806352, 1, 1, -1, 0],
- [2973729510, 2, 1, -1, 0],
- [2571931329, 1, 6, -1, 0],
- [3884442008, 0, 1, -1, 0],
- [978673395, 1, 1, -1, 0],
- [4050927174, 0, 1, -1, 0],
- [1260103069, 0, 1, -1, 0],
- [4168894280, 0, 1, -1, 0],
- [4045587091, 0, 1, -1, 0],
- [2003494159, 1, 1, -1, 0],
- [51193042, 0, 1, -1, 0],
- [2634540382, 3, 1, -1, 0],
- [886364171, 0, 1, -1, 0],
- [3898604944, 0, 1, -1, 0],
- [3388129398, 0, 1, -1, 0],
- [3964382884, 2, 1, -1, 1],
- [3305874255, 0, 1, -1, 0],
- [156590431, 0, 1, -1, 0],
- [3106485751, 0, 0, -1, 0],
- [3035674767, 0, 1, -1, 0],
- [851697110, 0, 1, -1, 0]
+ [4047587481, 0, 0, -1, 0],
+ [1509401575, 0, 1, -1, 0],
+ [1865079242, 0, 1, -1, 0],
+ [1962538549, 1, 0, -1, 0],
+ [3816091942, 3, 2, -1, 0],
+ [4130837190, 0, 10, -1, 0],
+ [1861568052, 0, 1, -1, 0],
+ [2290910058, 6, 2, -1, 0],
+ [1578940118, 1, 1, -1, 0],
+ [1571676964, 0, 1, -1, 2],
+ [3640172371, 0, 2, -1, 2],
+ [1658164312, 2, 1, -1, 0],
+ [98883956, 1, 1, -1, 0],
+ [3114091169, 0, 1, -1, 0],
+ [2570684145, 4, 1, -1, 2],
+ [4007615411, 0, 1, -1, 0],
+ [3665310159, 2, 1, -1, 1],
+ [852550504, 3, 1, -1, 0],
+ [2333572067, 0, 1, -1, 0],
+ [935994771, 1, 1, -1, 0],
+ [1127795596, 1, 1, -1, 0],
+ [4168223991, 0, 1, -1, 0],
+ [18585280, 0, 1, -1, 1],
+ [327482016, 0, 1, -1, 2],
+ [3458098201, 7, 1, -1, 0],
+ [478613943, 2, 1, -1, 1],
+ [2792197902, 0, 1, -1, 2],
+ [284670956, 0, 1, -1, 0],
+ [2099185390, 0, 1, -1, 0],
+ [1202202685, 0, 1, -1, 0],
+ [2122174751, 0, 1, -1, 0],
+ [3633864632, 0, 1, -1, 0],
+ [3103053065, 0, 1, -1, 0],
+ [820624960, 0, 1, -1, 0],
+ [1134479292, 0, 1, -1, 0],
+ [2511257455, 3, 1, -1, 3],
+ [2599708267, 0, 1, -1, 0],
+ [613180822, 1, 1, -1, 0],
+ [2885186814, 0, 1, -1, 0],
+ [221503477, 0, 1, -1, 0],
+ [1054317075, 0, 1, -1, 3],
+ [683872522, 0, 1, -1, 1],
+ [1739278764, 0, 2, -1, 0],
+ [2855249023, 0, 1, -1, 0],
+ [3721841948, 0, 1, -1, 0],
+ [1285203515, 0, 1, -1, 0],
+ [1365487849, 6, 1, -1, 0],
+ [955229746, 0, 1, -1, 0],
+ [3128009767, 0, 10, -1, 0],
+ [441885003, 0, 1, -1, 0],
+ [3433971238, 0, 1, -1, 2],
+ [1038765354, 3, 1, -1, 0],
+ [1174347196, 0, 1, -1, 0],
+ [3649806352, 1, 1, -1, 0],
+ [2973729510, 2, 1, -1, 0],
+ [2571931329, 1, 6, -1, 0],
+ [3884442008, 0, 1, -1, 0],
+ [978673395, 1, 1, -1, 0],
+ [4050927174, 0, 1, -1, 0],
+ [1260103069, 0, 1, -1, 0],
+ [4168894280, 0, 1, -1, 0],
+ [4045587091, 0, 1, -1, 0],
+ [2003494159, 1, 1, -1, 0],
+ [51193042, 0, 1, -1, 0],
+ [2634540382, 3, 1, -1, 0],
+ [886364171, 0, 1, -1, 0],
+ [3898604944, 0, 1, -1, 0],
+ [3388129398, 0, 1, -1, 0],
+ [3964382884, 2, 1, -1, 1],
+ [3305874255, 0, 1, -1, 0],
+ [156590431, 0, 1, -1, 0],
+ [3106485751, 0, 0, -1, 0],
+ [3035674767, 0, 1, -1, 0],
+ [851697110, 0, 1, -1, 0]
]
diff --git a/src/gateway/util/Send.ts b/src/gateway/util/Send.ts
index 57f87d8b..86f75a9a 100644
--- a/src/gateway/util/Send.ts
+++ b/src/gateway/util/Send.ts
@@ -37,15 +37,13 @@ const recurseJsonReplace = (json: any) => {
json[key] = JSONReplacer.call(json, key, json[key]);
- if (typeof json[key] == "object" && json[key] !== null)
- json[key] = recurseJsonReplace(json[key]);
+ if (typeof json[key] == "object" && json[key] !== null) json[key] = recurseJsonReplace(json[key]);
}
return json;
};
export function Send(socket: WebSocket, data: Payload) {
- if (process.env.WS_VERBOSE)
- console.log(`[Websocket] Outgoing message: ${JSON.stringify(data)}`);
+ if (process.env.WS_VERBOSE) console.log(`[Websocket] Outgoing message: ${JSON.stringify(data)}`);
if (process.env.WS_DUMP) {
const id = socket.session_id || "unknown";
@@ -54,10 +52,7 @@ export function Send(socket: WebSocket, data: Payload) {
await fs.mkdir(path.join("dump", id), {
recursive: true,
});
- await fs.writeFile(
- path.join("dump", id, `${Date.now()}.out.json`),
- JSON.stringify(data, null, 2),
- );
+ await fs.writeFile(path.join("dump", id, `${Date.now()}.out.json`), JSON.stringify(data, null, 2));
})();
}
@@ -68,8 +63,7 @@ export function Send(socket: WebSocket, data: Payload) {
buffer = erlpack.pack(data);
}
// TODO: encode circular object
- else if (socket.encoding === "json")
- buffer = JSON.stringify(data, JSONReplacer);
+ else if (socket.encoding === "json") buffer = JSON.stringify(data, JSONReplacer);
else return;
// TODO: compression
if (socket.deflate) {
diff --git a/src/gateway/util/SessionUtils.ts b/src/gateway/util/SessionUtils.ts
index 9238db72..26e7bdd6 100644
--- a/src/gateway/util/SessionUtils.ts
+++ b/src/gateway/util/SessionUtils.ts
@@ -25,7 +25,5 @@ export function genVoiceToken() {
}
function genRanHex(size: number) {
- return [...Array(size)]
- .map(() => Math.floor(Math.random() * 16).toString(16))
- .join("");
+ return [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join("");
}
|