diff --git a/gateway/src/Server.ts b/gateway/src/Server.ts
index cf4f906c..7e1489be 100644
--- a/gateway/src/Server.ts
+++ b/gateway/src/Server.ts
@@ -32,7 +32,6 @@ export class Server {
}
this.server.on("upgrade", (request, socket, head) => {
- console.log("socket requests upgrade", request.url);
// @ts-ignore
this.ws.handleUpgrade(request, socket, head, (socket) => {
this.ws.emit("connection", socket, request);
diff --git a/gateway/src/events/Close.ts b/gateway/src/events/Close.ts
index 1299ad5c..5b7c512c 100644
--- a/gateway/src/events/Close.ts
+++ b/gateway/src/events/Close.ts
@@ -1,10 +1,46 @@
import { WebSocket } from "@fosscord/gateway";
-import { Message } from "./Message";
-import { Session } from "@fosscord/util";
+import {
+ emitEvent,
+ PresenceUpdateEvent,
+ PrivateSessionProjection,
+ Session,
+ SessionsReplace,
+ User,
+} from "@fosscord/util";
export async function Close(this: WebSocket, code: number, reason: string) {
console.log("[WebSocket] closed", code, reason);
- if (this.session_id) await Session.delete({ session_id: this.session_id });
- // @ts-ignore
- this.off("message", Message);
+ if (this.heartbeatTimeout) clearTimeout(this.heartbeatTimeout);
+ if (this.readyTimeout) clearTimeout(this.readyTimeout);
+ this.deflate?.close();
+ this.removeAllListeners();
+
+ if (this.session_id) {
+ await Session.delete({ session_id: this.session_id });
+ const sessions = await Session.find({
+ where: { user_id: this.user_id },
+ select: PrivateSessionProjection,
+ });
+ await emitEvent({
+ event: "SESSIONS_REPLACE",
+ user_id: this.user_id,
+ data: sessions,
+ } as SessionsReplace);
+ const session = sessions.first() || {
+ activities: [],
+ client_info: {},
+ status: "offline",
+ };
+
+ await emitEvent({
+ event: "PRESENCE_UPDATE",
+ user_id: this.user_id,
+ data: {
+ user: await User.getPublicUser(this.user_id),
+ activities: session.activities,
+ client_status: session?.client_info,
+ status: session.status,
+ },
+ } as PresenceUpdateEvent);
+ }
}
diff --git a/gateway/src/events/Connection.ts b/gateway/src/events/Connection.ts
index c1a6b618..4954cd08 100644
--- a/gateway/src/events/Connection.ts
+++ b/gateway/src/events/Connection.ts
@@ -8,7 +8,6 @@ import { Close } from "./Close";
import { Message } from "./Message";
import { createDeflate } from "zlib";
import { URL } from "url";
-import { Session } from "@fosscord/util";
var erlpack: any;
try {
erlpack = require("@yukikaze-bot/erlpack");
@@ -24,9 +23,11 @@ export async function Connection(
request: IncomingMessage
) {
try {
+ // @ts-ignore
socket.on("close", Close);
// @ts-ignore
socket.on("message", Message);
+ console.log(`[Gateway] Connections: ${this.clients.size}`);
const { searchParams } = new URL(`http://localhost${request.url}`);
// @ts-ignore
@@ -55,6 +56,7 @@ export async function Connection(
}
socket.events = {};
+ socket.member_events = {};
socket.permissions = {};
socket.sequence = 0;
@@ -68,12 +70,10 @@ export async function Connection(
});
socket.readyTimeout = setTimeout(() => {
- Session.delete({ session_id: socket.session_id }); //should we await?
return socket.close(CLOSECODES.Session_timed_out);
}, 1000 * 30);
} catch (error) {
console.error(error);
- Session.delete({ session_id: socket.session_id }); //should we await?
return socket.close(CLOSECODES.Unknown_error);
}
}
diff --git a/gateway/src/events/Message.ts b/gateway/src/events/Message.ts
index af318bfd..acc39bb9 100644
--- a/gateway/src/events/Message.ts
+++ b/gateway/src/events/Message.ts
@@ -37,8 +37,6 @@ export async function Message(this: WebSocket, buffer: WS.Data) {
return;
}
- console.log("[Gateway] Opcode " + OPCODES[data.op]);
-
try {
return await OPCodeHandler.call(this, data);
} catch (error) {
diff --git a/gateway/src/listener/listener.ts b/gateway/src/listener/listener.ts
index ee640f38..79659a1f 100644
--- a/gateway/src/listener/listener.ts
+++ b/gateway/src/listener/listener.ts
@@ -6,6 +6,9 @@ import {
EventOpts,
ListenEventOpts,
Member,
+ EVENTEnum,
+ Relationship,
+ RelationshipType,
} from "@fosscord/util";
import { OPCODES } from "../util/Constants";
import { Send } from "../util/Send";
@@ -21,22 +24,45 @@ import { Recipient } from "@fosscord/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
+) {
+ acknowledge?.();
+ if (event === EVENTEnum.PresenceUpdate) {
+ return Send(this, {
+ op: OPCODES.Dispatch,
+ t: event,
+ d: data,
+ s: this.sequence++,
+ });
+ }
+}
+
// TODO: use already queried guilds/channels of Identify and don't fetch them again
export async function setupListener(this: WebSocket) {
- const members = await Member.find({
- where: { id: this.user_id },
- relations: ["guild", "guild.channels"],
- });
+ const [members, recipients, relationships] = await Promise.all([
+ Member.find({
+ where: { id: this.user_id },
+ relations: ["guild", "guild.channels"],
+ }),
+ Recipient.find({
+ where: { user_id: this.user_id, closed: false },
+ relations: ["channel"],
+ }),
+ Relationship.find({
+ from_id: this.user_id,
+ type: RelationshipType.friends,
+ }),
+ ]);
+
const guilds = members.map((x) => x.guild);
- const recipients = await Recipient.find({
- where: { user_id: this.user_id, closed: false },
- relations: ["channel"],
- });
const dm_channels = recipients.map((x) => x.channel);
const opts: { acknowledge: boolean; channel?: AMQChannel } = {
acknowledge: true,
};
+ this.listen_options = opts;
const consumer = consume.bind(this);
if (RabbitMQ.connection) {
@@ -47,45 +73,44 @@ export async function setupListener(this: WebSocket) {
this.events[this.user_id] = await listenEvent(this.user_id, consumer, opts);
- for (const channel of dm_channels) {
+ relationships.forEach(async (relationship) => {
+ this.events[relationship.to_id] = await listenEvent(
+ relationship.to_id,
+ handlePresenceUpdate.bind(this),
+ opts
+ );
+ });
+
+ dm_channels.forEach(async (channel) => {
this.events[channel.id] = await listenEvent(channel.id, consumer, opts);
- }
+ });
- for (const guild of guilds) {
- // contains guild and dm channels
+ guilds.forEach(async (guild) => {
+ const permission = await getPermission(this.user_id, guild.id);
+ this.permissions[guild.id] = permission;
+ this.events[guild.id] = await listenEvent(guild.id, consumer, opts);
- getPermission(this.user_id, guild.id)
- .then(async (x) => {
- this.permissions[guild.id] = x;
- this.listeners;
- this.events[guild.id] = await listenEvent(
- guild.id,
+ guild.channels.forEach(async (channel) => {
+ if (
+ permission
+ .overwriteChannel(channel.permission_overwrites!)
+ .has("VIEW_CHANNEL")
+ ) {
+ this.events[channel.id] = await listenEvent(
+ channel.id,
consumer,
opts
);
-
- for (const channel of guild.channels) {
- if (
- x
- .overwriteChannel(channel.permission_overwrites!)
- .has("VIEW_CHANNEL")
- ) {
- this.events[channel.id] = await listenEvent(
- channel.id,
- consumer,
- opts
- );
- }
- }
- })
- .catch((e) =>
- console.log("couldn't get permission for guild " + guild, e)
- );
- }
+ }
+ });
+ });
this.once("close", () => {
if (opts.channel) opts.channel.close();
- else Object.values(this.events).forEach((x) => x());
+ else {
+ Object.values(this.events).forEach((x) => x());
+ Object.values(this.member_events).forEach((x) => x());
+ }
});
}
@@ -97,10 +122,23 @@ async function consume(this: WebSocket, opts: EventOpts) {
const consumer = consume.bind(this);
const listenOpts = opts as ListenEventOpts;
+ opts.acknowledge?.();
// console.log("event", event);
// subscription managment
switch (event) {
+ case "GUILD_MEMBER_REMOVE":
+ this.member_events[data.user.id]?.();
+ delete this.member_events[data.user.id];
+ case "GUILD_MEMBER_ADD":
+ if (this.member_events[data.user.id]) break; // already subscribed
+ this.member_events[data.user.id] = await listenEvent(
+ data.user.id,
+ handlePresenceUpdate.bind(this),
+ this.listen_options
+ );
+ break;
+ case "RELATIONSHIP_REMOVE":
case "CHANNEL_DELETE":
case "GUILD_DELETE":
delete this.events[id];
@@ -178,7 +216,7 @@ async function consume(this: WebSocket, opts: EventOpts) {
case "CHANNEL_CREATE":
case "CHANNEL_DELETE":
case "CHANNEL_UPDATE":
- case "GUILD_EMOJI_UPDATE":
+ case "GUILD_EMOJIS_UPDATE":
case "READY": // will be sent by the gateway
case "USER_UPDATE":
case "APPLICATION_COMMAND_CREATE":
@@ -196,5 +234,4 @@ async function consume(this: WebSocket, opts: EventOpts) {
d: data,
s: this.sequence++,
});
- opts.acknowledge?.();
}
diff --git a/gateway/src/opcodes/Identify.ts b/gateway/src/opcodes/Identify.ts
index b81c7bf4..f39ac808 100644
--- a/gateway/src/opcodes/Identify.ts
+++ b/gateway/src/opcodes/Identify.ts
@@ -12,6 +12,12 @@ import {
PublicUser,
PrivateUserProjection,
ReadState,
+ Application,
+ emitEvent,
+ SessionsReplace,
+ PrivateSessionProjection,
+ MemberPrivateProjection,
+ PresenceUpdateEvent,
} from "@fosscord/util";
import { Send } from "../util/Send";
import { CLOSECODES, OPCODES } from "../util/Constants";
@@ -41,7 +47,61 @@ export async function onIdentify(this: WebSocket, data: Payload) {
return this.close(CLOSECODES.Authentication_failed);
}
this.user_id = decoded.id;
- if (!identify.intents) identify.intents = 0b11111111111111n;
+
+ const session_id = genSessionId();
+ this.session_id = session_id; //Set the session of the WebSocket object
+
+ const [user, read_states, members, recipients, session, application] =
+ await Promise.all([
+ User.findOneOrFail({
+ where: { id: this.user_id },
+ relations: ["relationships", "relationships.to"],
+ select: [...PrivateUserProjection, "relationships"],
+ }),
+ ReadState.find({ user_id: this.user_id }),
+ Member.find({
+ where: { id: this.user_id },
+ select: MemberPrivateProjection,
+ relations: [
+ "guild",
+ "guild.channels",
+ "guild.emojis",
+ "guild.emojis.user",
+ "guild.roles",
+ "guild.stickers",
+ "user",
+ "roles",
+ ],
+ }),
+ Recipient.find({
+ where: { user_id: this.user_id, closed: false },
+ relations: [
+ "channel",
+ "channel.recipients",
+ "channel.recipients.user",
+ ],
+ // TODO: public user selection
+ }),
+ // save the session and delete it when the websocket is closed
+ new Session({
+ user_id: this.user_id,
+ session_id: session_id,
+ // TODO: check if status is only one of: online, dnd, offline, idle
+ status: identify.presence?.status || "online", //does the session always start as online?
+ client_info: {
+ //TODO read from identity
+ client: "desktop",
+ os: identify.properties?.os,
+ version: 0,
+ },
+ activities: [],
+ }).save(),
+ Application.findOne({ id: this.user_id }),
+ ]);
+
+ if (!user) return this.close(CLOSECODES.Authentication_failed);
+
+ if (!identify.intents) identify.intents = BigInt("0b11111111111111");
this.intents = new Intents(identify.intents);
if (identify.shard) {
this.shard_id = identify.shard[0];
@@ -59,18 +119,6 @@ export async function onIdentify(this: WebSocket, data: Payload) {
}
var users: PublicUser[] = [];
- const members = await Member.find({
- where: { id: this.user_id },
- relations: [
- "guild",
- "guild.channels",
- "guild.emojis",
- "guild.roles",
- "guild.stickers",
- "user",
- "roles",
- ],
- });
const merged_members = members.map((x: Member) => {
return [
{
@@ -81,19 +129,32 @@ export async function onIdentify(this: WebSocket, data: Payload) {
},
];
}) as PublicMember[][];
- const guilds = members.map((x) => ({ ...x.guild, joined_at: x.joined_at }));
- const user_guild_settings_entries = members.map((x) => x.settings);
+ let guilds = members.map((x) => ({ ...x.guild, joined_at: x.joined_at }));
- const recipients = await Recipient.find({
- where: { user_id: this.user_id, closed: false },
- relations: ["channel", "channel.recipients", "channel.recipients.user"],
- // TODO: public user selection
+ // @ts-ignore
+ guilds = guilds.map((guild) => {
+ if (user.bot) {
+ setTimeout(() => {
+ Send(this, {
+ op: OPCODES.Dispatch,
+ t: EVENTEnum.GuildCreate,
+ s: this.sequence++,
+ d: guild,
+ });
+ }, 500);
+ return { id: guild.id, unavailable: true };
+ }
+
+ return guild;
});
+
+ const user_guild_settings_entries = members.map((x) => x.settings);
+
const channels = recipients.map((x) => {
// @ts-ignore
x.channel.recipients = x.channel.recipients?.map((x) => x.user);
//TODO is this needed? check if users in group dm that are not friends are sent in the READY event
- //users = users.concat(x.channel.recipients);
+ users = users.concat(x.channel.recipients as unknown as User[]);
if (x.channel.isDm()) {
x.channel.recipients = x.channel.recipients!.filter(
(x) => x.id !== this.user_id
@@ -101,12 +162,6 @@ export async function onIdentify(this: WebSocket, data: Payload) {
}
return x.channel;
});
- const user = await User.findOneOrFail({
- where: { id: this.user_id },
- relations: ["relationships", "relationships.to"],
- select: [...PrivateUserProjection, "relationships"],
- });
- if (!user) return this.close(CLOSECODES.Authentication_failed);
for (let relation of user.relationships) {
const related_user = relation.to;
@@ -122,24 +177,28 @@ export async function onIdentify(this: WebSocket, data: Payload) {
users.push(public_related_user);
}
- const session_id = genSessionId();
- this.session_id = session_id; //Set the session of the WebSocket object
- const session = new Session({
- user_id: this.user_id,
- session_id: session_id,
- status: "online", //does the session always start as online?
- client_info: {
- //TODO read from identity
- client: "desktop",
- os: "linux",
- version: 0,
- },
+ setImmediate(async () => {
+ // run in seperate "promise context" because ready payload is not dependent on those events
+ emitEvent({
+ event: "SESSIONS_REPLACE",
+ user_id: this.user_id,
+ data: await Session.find({
+ where: { user_id: this.user_id },
+ select: PrivateSessionProjection,
+ }),
+ } as SessionsReplace);
+ emitEvent({
+ event: "PRESENCE_UPDATE",
+ user_id: this.user_id,
+ data: {
+ user: await User.getPublicUser(this.user_id),
+ activities: session.activities,
+ client_status: session?.client_info,
+ status: session.status,
+ },
+ } as PresenceUpdateEvent);
});
- //We save the session and we delete it when the websocket is closed
- await session.save();
-
- const read_states = await ReadState.find({ user_id: this.user_id });
read_states.forEach((s: any) => {
s.id = s.channel_id;
delete s.user_id;
@@ -170,6 +229,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
const d: ReadyEventData = {
v: 8,
+ application,
user: privateUser,
user_settings: user.settings,
// @ts-ignore
@@ -178,6 +238,8 @@ export async function onIdentify(this: WebSocket, data: Payload) {
x.guild_hashes = {}; // @ts-ignore
x.guild_scheduled_events = []; // @ts-ignore
x.threads = [];
+ x.premium_subscription_count = 30;
+ x.premium_tier = 3;
return x;
}),
guild_experiments: [], // TODO
@@ -207,14 +269,11 @@ export async function onIdentify(this: WebSocket, data: Payload) {
// @ts-ignore
experiments: experiments, // TODO
guild_join_requests: [], // TODO what is this?
- users: users.unique(),
+ users: users.filter((x) => x).unique(),
merged_members: merged_members,
// shard // TODO: only for bots sharding
- // application // TODO for applications
};
- console.log("Send ready");
-
// TODO: send real proper data structure
await Send(this, {
op: OPCODES.Dispatch,
diff --git a/gateway/src/opcodes/LazyRequest.ts b/gateway/src/opcodes/LazyRequest.ts
index d37e32da..c304dfe7 100644
--- a/gateway/src/opcodes/LazyRequest.ts
+++ b/gateway/src/opcodes/LazyRequest.ts
@@ -1,46 +1,56 @@
import {
+ EVENTEnum,
+ EventOpts,
getPermission,
+ listenEvent,
Member,
- PublicMemberProjection,
Role,
} from "@fosscord/util";
import { LazyRequest } from "../schema/LazyRequest";
import { Send } from "../util/Send";
import { OPCODES } from "../util/Constants";
-import { WebSocket, Payload } from "@fosscord/gateway";
+import { WebSocket, Payload, handlePresenceUpdate } from "@fosscord/gateway";
import { check } from "./instanceOf";
import "missing-native-js-functions";
+import { getRepository } from "typeorm";
+import "missing-native-js-functions";
-// TODO: check permission and only show roles/members that have access to this channel
+// TODO: only show roles/members that have access to this channel
// TODO: config: to list all members (even those who are offline) sorted by role, or just those who are online
// TODO: rewrite typeorm
-export async function onLazyRequest(this: WebSocket, { d }: Payload) {
- // TODO: check data
- check.call(this, LazyRequest, d);
- const { guild_id, typing, channels, activities } = d as LazyRequest;
-
- const permissions = await getPermission(this.user_id, guild_id);
- permissions.hasThrow("VIEW_CHANNEL");
-
- var members = await Member.find({
- where: { guild_id: guild_id },
- relations: ["roles", "user"],
- select: PublicMemberProjection,
- });
+async function getMembers(guild_id: string, range: [number, number]) {
+ if (!Array.isArray(range) || range.length !== 2) {
+ throw new Error("range is not a valid array");
+ }
+ // TODO: wait for typeorm to implement ordering for .find queries https://github.com/typeorm/typeorm/issues/2620
- const roles = await Role.find({
- where: { guild_id: guild_id },
- order: {
- position: "DESC",
- },
- });
+ let members = await getRepository(Member)
+ .createQueryBuilder("member")
+ .where("member.guild_id = :guild_id", { guild_id })
+ .leftJoinAndSelect("member.roles", "role")
+ .leftJoinAndSelect("member.user", "user")
+ .leftJoinAndSelect("user.sessions", "session")
+ .addSelect(
+ "CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END",
+ "_status"
+ )
+ .orderBy("role.position", "DESC")
+ .addOrderBy("_status", "DESC")
+ .addOrderBy("user.username", "ASC")
+ .offset(Number(range[0]) || 0)
+ .limit(Number(range[1]) || 100)
+ .getMany();
const groups = [] as any[];
- var member_count = 0;
const items = [];
+ const member_roles = members
+ .map((m) => m.roles)
+ .flat()
+ .unique((r) => r.id);
- for (const role of roles) {
+ for (const role of member_roles) {
+ // @ts-ignore
const [role_members, other_members] = partition(members, (m: Member) =>
m.roles.find((r) => r.id === role.id)
);
@@ -53,38 +63,94 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
groups.push(group);
for (const member of role_members) {
- member.roles = member.roles.filter((x) => x.id !== guild_id);
+ const roles = member.roles
+ .filter((x: Role) => x.id !== guild_id)
+ .map((x: Role) => x.id);
+
+ const session = member.user.sessions.first();
+
+ // TODO: properly mock/hide offline/invisible status
items.push({
- member: { ...member, roles: member.roles.map((x) => x.id) },
+ member: {
+ ...member,
+ roles,
+ user: { ...member.user, sessions: undefined },
+ presence: {
+ ...session,
+ activities: session?.activities || [],
+ user: { id: member.user.id },
+ },
+ },
});
}
members = other_members;
- member_count += role_members.length;
}
+ return {
+ items,
+ groups,
+ range,
+ members: items.map((x) => x.member).filter((x) => x),
+ };
+}
+
+export async function onLazyRequest(this: WebSocket, { d }: Payload) {
+ // TODO: check data
+ check.call(this, LazyRequest, d);
+ const { guild_id, typing, channels, activities } = d as LazyRequest;
+
+ const channel_id = Object.keys(channels || {}).first();
+ if (!channel_id) return;
+
+ const permissions = await getPermission(this.user_id, guild_id, channel_id);
+ permissions.hasThrow("VIEW_CHANNEL");
+
+ const ranges = channels![channel_id];
+ if (!Array.isArray(ranges)) throw new Error("Not a valid Array");
+
+ const member_count = await Member.count({ guild_id });
+ const ops = await Promise.all(ranges.map((x) => getMembers(guild_id, x)));
+
+ // TODO: unsubscribe member_events that are not in op.members
+
+ ops.forEach((op) => {
+ op.members.forEach(async (member) => {
+ if (this.events[member.user.id]) return; // already subscribed as friend
+ if (this.member_events[member.user.id]) return; // already subscribed in member list
+ this.member_events[member.user.id] = await listenEvent(
+ member.user.id,
+ handlePresenceUpdate.bind(this),
+ this.listen_options
+ );
+ });
+ });
+
return Send(this, {
op: OPCODES.Dispatch,
s: this.sequence++,
t: "GUILD_MEMBER_LIST_UPDATE",
d: {
- ops: [
- {
- range: [0, 99],
- op: "SYNC",
- items,
- },
- ],
- online_count: member_count, // TODO count online count
+ ops: ops.map((x) => ({
+ items: x.items,
+ op: "SYNC",
+ range: x.range,
+ })),
+ online_count: member_count,
member_count,
id: "everyone",
guild_id,
- groups,
+ groups: ops
+ .map((x) => x.groups)
+ .flat()
+ .unique(),
},
});
}
function partition<T>(array: T[], isValid: Function) {
+ // @ts-ignore
return array.reduce(
+ // @ts-ignore
([pass, fail], elem) => {
return isValid(elem)
? [[...pass, elem], fail]
diff --git a/gateway/src/opcodes/PresenceUpdate.ts b/gateway/src/opcodes/PresenceUpdate.ts
index 53d7b9d2..415df6ee 100644
--- a/gateway/src/opcodes/PresenceUpdate.ts
+++ b/gateway/src/opcodes/PresenceUpdate.ts
@@ -1,5 +1,25 @@
import { WebSocket, Payload } from "@fosscord/gateway";
+import { emitEvent, PresenceUpdateEvent, Session, User } from "@fosscord/util";
+import { ActivitySchema } from "../schema/Activity";
+import { check } from "./instanceOf";
-export function onPresenceUpdate(this: WebSocket, data: Payload) {
- // return this.close(CLOSECODES.Unknown_error);
+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 emitEvent({
+ event: "PRESENCE_UPDATE",
+ user_id: this.user_id,
+ data: {
+ user: await User.getPublicUser(this.user_id),
+ activities: presence.activities,
+ client_status: {}, // TODO:
+ status: presence.status,
+ },
+ } as PresenceUpdateEvent);
}
diff --git a/gateway/src/schema/Activity.ts b/gateway/src/schema/Activity.ts
index f1665efd..b1ac5638 100644
--- a/gateway/src/schema/Activity.ts
+++ b/gateway/src/schema/Activity.ts
@@ -1,4 +1,4 @@
-import { EmojiSchema } from "./Emoji";
+import { Activity, Status } from "@fosscord/util";
export const ActivitySchema = {
afk: Boolean,
@@ -21,7 +21,7 @@ export const ActivitySchema = {
$emoji: {
$name: String,
$id: String,
- $amimated: Boolean,
+ $animated: Boolean,
},
$party: {
$id: String,
@@ -47,40 +47,7 @@ export const ActivitySchema = {
export interface ActivitySchema {
afk: boolean;
- status: string;
- activities?: [
- {
- name: string; // the activity's name
- type: number; // activity type // TODO: check if its between range 0-5
- url?: string; // stream url, is validated when type is 1
- created_at?: number; // unix timestamp of when the activity was added to the user's session
- timestamps?: {
- // unix timestamps for start and/or end of the game
- start: number;
- end: number;
- };
- application_id?: string; // application id for the game
- details?: string;
- state?: string;
- emoji?: EmojiSchema;
- party?: {
- id?: string;
- size?: [number]; // used to show the party's current and maximum size // TODO: array length 2
- };
- assets?: {
- large_image?: string; // the id for a large asset of the activity, usually a snowflake
- large_text?: string; // text displayed when hovering over the large image of the activity
- small_image?: string; // the id for a small asset of the activity, usually a snowflake
- small_text?: string; // text displayed when hovering over the small image of the activity
- };
- secrets?: {
- join?: string; // the secret for joining a party
- spectate?: string; // the secret for spectating a game
- match?: string; // the secret for a specific instanced match
- };
- instance?: boolean;
- flags: string; // activity flags OR d together, describes what the payload includes
- }
- ];
+ status: Status;
+ activities?: Activity[];
since?: number; // unix time (in milliseconds) of when the client went idle, or null if the client is not idle
}
diff --git a/gateway/src/schema/Emoji.ts b/gateway/src/schema/Emoji.ts
deleted file mode 100644
index 413b8359..00000000
--- a/gateway/src/schema/Emoji.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const EmojiSchema = {
- name: String, // the name of the emoji
- $id: String, // the id of the emoji
- animated: Boolean, // whether this emoji is animated
-};
-
-export interface EmojiSchema {
- name: string;
- id?: string;
- animated: Boolean;
-}
diff --git a/gateway/src/schema/LazyRequest.ts b/gateway/src/schema/LazyRequest.ts
index 7c828ac6..1fe658bb 100644
--- a/gateway/src/schema/LazyRequest.ts
+++ b/gateway/src/schema/LazyRequest.ts
@@ -1,6 +1,6 @@
export interface LazyRequest {
guild_id: string;
- channels?: Record<string, [number, number]>;
+ channels?: Record<string, [number, number][]>;
activities?: boolean;
threads?: boolean;
typing?: true;
diff --git a/gateway/src/util/Send.ts b/gateway/src/util/Send.ts
index 4defa898..196d4205 100644
--- a/gateway/src/util/Send.ts
+++ b/gateway/src/util/Send.ts
@@ -18,6 +18,9 @@ export async function Send(socket: WebSocket, data: Payload) {
}
return new Promise((res, rej) => {
+ if (socket.readyState !== 1) {
+ return rej("socket not open");
+ }
socket.send(buffer, (err: any) => {
if (err) return rej(err);
return res(null);
diff --git a/gateway/src/util/WebSocket.ts b/gateway/src/util/WebSocket.ts
index 49626b2a..e3313f40 100644
--- a/gateway/src/util/WebSocket.ts
+++ b/gateway/src/util/WebSocket.ts
@@ -17,4 +17,6 @@ export interface WebSocket extends WS {
sequence: number;
permissions: Record<string, Permissions>;
events: Record<string, Function>;
+ member_events: Record<string, Function>;
+ listen_options: any;
}
|