From 0d23eaba09a4878520bf346af4cead90d76829fc Mon Sep 17 00:00:00 2001 From: Madeline <46743919+MaddyUnderStars@users.noreply.github.com> Date: Sun, 25 Sep 2022 18:24:21 +1000 Subject: Refactor to mono-repo + upgrade packages --- src/gateway/opcodes/Heartbeat.ts | 11 + src/gateway/opcodes/Identify.ts | 312 +++++++++++++++++++++++++++++ src/gateway/opcodes/LazyRequest.ts | 205 +++++++++++++++++++ src/gateway/opcodes/PresenceUpdate.ts | 25 +++ src/gateway/opcodes/RequestGuildMembers.ts | 5 + src/gateway/opcodes/Resume.ts | 12 ++ src/gateway/opcodes/VoiceStateUpdate.ts | 113 +++++++++++ src/gateway/opcodes/experiments.json | 76 +++++++ src/gateway/opcodes/index.ts | 25 +++ src/gateway/opcodes/instanceOf.ts | 18 ++ 10 files changed, 802 insertions(+) create mode 100644 src/gateway/opcodes/Heartbeat.ts create mode 100644 src/gateway/opcodes/Identify.ts create mode 100644 src/gateway/opcodes/LazyRequest.ts create mode 100644 src/gateway/opcodes/PresenceUpdate.ts create mode 100644 src/gateway/opcodes/RequestGuildMembers.ts create mode 100644 src/gateway/opcodes/Resume.ts create mode 100644 src/gateway/opcodes/VoiceStateUpdate.ts create mode 100644 src/gateway/opcodes/experiments.json create mode 100644 src/gateway/opcodes/index.ts create mode 100644 src/gateway/opcodes/instanceOf.ts (limited to 'src/gateway/opcodes') diff --git a/src/gateway/opcodes/Heartbeat.ts b/src/gateway/opcodes/Heartbeat.ts new file mode 100644 index 00000000..50394130 --- /dev/null +++ b/src/gateway/opcodes/Heartbeat.ts @@ -0,0 +1,11 @@ +import { Payload, WebSocket } from "@fosscord/gateway"; +import { setHeartbeat } from "../util/Heartbeat"; +import { Send } from "../util/Send"; + +export async function onHeartbeat(this: WebSocket, data: Payload) { + // TODO: validate payload + + setHeartbeat(this); + + await Send(this, { op: 11 }); +} diff --git a/src/gateway/opcodes/Identify.ts b/src/gateway/opcodes/Identify.ts new file mode 100644 index 00000000..3c40962c --- /dev/null +++ b/src/gateway/opcodes/Identify.ts @@ -0,0 +1,312 @@ +import { WebSocket, Payload } from "@fosscord/gateway"; +import { + checkToken, + Intents, + Member, + ReadyEventData, + User, + Session, + EVENTEnum, + Config, + PublicMember, + PublicUser, + PrivateUserProjection, + ReadState, + Application, + emitEvent, + SessionsReplace, + PrivateSessionProjection, + MemberPrivateProjection, + PresenceUpdateEvent, + DefaultUserGuildSettings, + UserGuildSettings, +} from "@fosscord/util"; +import { Send } from "../util/Send"; +import { CLOSECODES, OPCODES } from "../util/Constants"; +import { genSessionId } from "../util/SessionUtils"; +import { setupListener } from "../listener/listener"; +import { IdentifySchema } from "../schema/Identify"; +// import experiments from "./experiments.json"; +const experiments: any = []; +import { check } from "./instanceOf"; +import { Recipient } from "@fosscord/util"; + +// TODO: user sharding +// TODO: check privileged intents, if defined in the config +// TODO: check if already identified + +export async function onIdentify(this: WebSocket, data: Payload) { + clearTimeout(this.readyTimeout); + if (typeof data.d?.client_state?.highest_last_message_id === "number") + data.d.client_state.highest_last_message_id += ""; + check.call(this, IdentifySchema, data.d); + + const identify: IdentifySchema = data.d; + + try { + const { jwtSecret } = Config.get().security; + var { decoded } = await checkToken(identify.token, jwtSecret); // will throw an error if invalid + } catch (error) { + console.error("invalid token", error); + return this.close(CLOSECODES.Authentication_failed); + } + this.user_id = decoded.id; + + 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({ where: { 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 + Session.create({ + 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 || "offline", //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({ where: { id: this.user_id } }), + ]); + + if (!user) return this.close(CLOSECODES.Authentication_failed); + + if (!identify.intents) identify.intents = BigInt("0x6ffffffff"); + this.intents = new Intents(identify.intents); + if (identify.shard) { + this.shard_id = identify.shard[0]; + this.shard_count = identify.shard[1]; + if ( + this.shard_count == null || + this.shard_id == null || + this.shard_id >= this.shard_count || + this.shard_id < 0 || + this.shard_count <= 0 + ) { + console.log(identify.shard); + return this.close(CLOSECODES.Invalid_shard); + } + } + var users: PublicUser[] = []; + + const merged_members = members.map((x: Member) => { + return [ + { + ...x, + roles: x.roles.map((x) => x.id), + settings: undefined, + guild: undefined, + }, + ]; + }) as PublicMember[][]; + let guilds = members.map((x) => ({ ...x.guild, joined_at: x.joined_at })); + + // @ts-ignore + guilds = guilds.map((guild) => { + if (user.bot) { + setTimeout(() => { + var promise = Send(this, { + op: OPCODES.Dispatch, + t: EVENTEnum.GuildCreate, + s: this.sequence++, + d: guild, + }); + if (promise) promise.catch(console.error); + }, 500); + return { id: guild.id, unavailable: true }; + } + + return guild; + }); + + const user_guild_settings_entries = members.map((x) => ({ + ...DefaultUserGuildSettings, + ...x.settings, + guild_id: x.guild.id, + // disgusting + channel_overrides: Object.entries(x.settings.channel_overrides ?? {}).map(y => ({ + ...y[1], + channel_id: y[0], + })) + })) as any as UserGuildSettings[]; // VERY disgusting. don't care. + + 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 as unknown as User[]); + if (x.channel.isDm()) { + x.channel.recipients = x.channel.recipients!.filter( + (x) => x.id !== this.user_id + ); + } + return x.channel; + }); + + for (let relation of user.relationships) { + const related_user = relation.to; + const public_related_user = { + username: related_user.username, + discriminator: related_user.discriminator, + id: related_user.id, + public_flags: related_user.public_flags, + avatar: related_user.avatar, + bot: related_user.bot, + bio: related_user.bio, + premium_since: user.premium_since, + accent_color: related_user.accent_color, + }; + users.push(public_related_user); + } + + 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); + }); + + read_states.forEach((s: any) => { + s.id = s.channel_id; + delete s.user_id; + delete s.channel_id; + }); + + const privateUser = { + avatar: user.avatar, + mobile: user.mobile, + desktop: user.desktop, + discriminator: user.discriminator, + email: user.email, + flags: user.flags, + id: user.id, + mfa_enabled: user.mfa_enabled, + nsfw_allowed: user.nsfw_allowed, + phone: user.phone, + premium: user.premium, + premium_type: user.premium_type, + public_flags: user.public_flags, + premium_usage_flags: user.premium_usage_flags, + purchased_flags: user.purchased_flags, + username: user.username, + verified: user.verified, + bot: user.bot, + accent_color: user.accent_color, + banner: user.banner, + bio: user.bio, + premium_since: user.premium_since + }; + + const d: ReadyEventData = { + v: 8, + application: application ?? undefined, + user: privateUser, + user_settings: user.settings, + // @ts-ignore + guilds: guilds.map((x) => { + // @ts-ignore + x.guild_hashes = {}; // @ts-ignore + x.guild_scheduled_events = []; // @ts-ignore + x.threads = []; + return x; + }), + guild_experiments: [], // TODO + geo_ordered_rtc_regions: [], // TODO + relationships: user.relationships.map((x) => x.toPublicRelationship()), + read_state: { + entries: read_states, + partial: false, + version: 304128, + }, + user_guild_settings: { + entries: user_guild_settings_entries, + partial: false, // TODO partial + version: 642, + }, + private_channels: channels, + session_id: session_id, + analytics_token: "", // TODO + connected_accounts: [], // TODO + consents: { + personalization: { + consented: false, // TODO + }, + }, + country_code: user.settings.locale, + friend_suggestion_count: 0, // TODO + // @ts-ignore + experiments: experiments, // TODO + guild_join_requests: [], // TODO what is this? + users: users.filter((x) => x).unique(), + merged_members: merged_members, + // shard // TODO: only for user sharding + sessions: [], // TODO: + presences: [], // TODO: + }; + + // TODO: send real proper data structure + await Send(this, { + op: OPCODES.Dispatch, + t: EVENTEnum.Ready, + s: this.sequence++, + d, + }); + + //TODO send READY_SUPPLEMENTAL + //TODO send GUILD_MEMBER_LIST_UPDATE + //TODO send SESSIONS_REPLACE + //TODO send VOICE_STATE_UPDATE to let the client know if another device is already connected to a voice channel + + await setupListener.call(this); + + console.log(`${this.ipAddress} identified as ${d.user.id}`); +} diff --git a/src/gateway/opcodes/LazyRequest.ts b/src/gateway/opcodes/LazyRequest.ts new file mode 100644 index 00000000..82342224 --- /dev/null +++ b/src/gateway/opcodes/LazyRequest.ts @@ -0,0 +1,205 @@ +import { getDatabase, getPermission, listenEvent, Member, Role, Session } from "@fosscord/util"; +import { WebSocket, Payload, handlePresenceUpdate, OPCODES, Send } from "@fosscord/gateway"; +import { LazyRequest } from "../schema/LazyRequest"; +import { check } from "./instanceOf"; + +// 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 + +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 + + let members: Member[] = []; + try { + members = await getDatabase()!.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("user.settings") + .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(); + } + catch (e) { + console.error(`LazyRequest`, e); + } + + if (!members) { + return { + items: [], + groups: [], + range: [], + members: [], + }; + } + + const groups = [] as any[]; + const items = []; + const member_roles = members + .map((m) => m.roles) + .flat() + .unique((r: Role) => r.id); + member_roles.push(member_roles.splice(member_roles.findIndex(x => x.id === x.guild_id), 1)[0]); + + const offlineItems = []; + + for (const role of member_roles) { + // @ts-ignore + const [role_members, other_members]: Member[][] = partition(members, (m: Member) => + m.roles.find((r) => r.id === role.id) + ); + const group = { + count: role_members.length, + id: role.id === guild_id ? "online" : role.id, + }; + + items.push({ group }); + 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 statusMap = { + "online": 0, + "idle": 1, + "dnd": 2, + "invisible": 3, + "offline": 4, + }; + // sort sessions by relevance + const sessions = member.user.sessions.sort((a, b) => { + return (statusMap[a.status] - statusMap[b.status]) + ((a.activities.length - b.activities.length) * 2); + }); + var session: Session | undefined = sessions.first(); + + if (session?.status == "offline") { + session.status = member.user.settings.status || "online"; + } + + const item = { + member: { + ...member, + roles, + user: { ...member.user, sessions: undefined }, + presence: { + ...session, + activities: session?.activities || [], + user: { id: member.user.id }, + }, + }, + }; + + if (!session || session.status == "invisible" || session.status == "offline") { + item.member.presence.status = "offline"; + offlineItems.push(item); + group.count--; + continue; + } + + items.push(item); + } + members = other_members; + } + + if (offlineItems.length) { + const group = { + count: offlineItems.length, + id: "offline", + }; + items.push({ group }); + groups.push(group); + + items.push(...offlineItems); + } + + return { + items, + groups, + range, + members: items.map((x) => 'member' in x ? x.member : undefined).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({ where: { 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 (!member) return; + 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 + ); + }); + }); + + const groups = ops + .map((x) => x.groups) + .flat() + .unique(); + + return await Send(this, { + op: OPCODES.Dispatch, + s: this.sequence++, + t: "GUILD_MEMBER_LIST_UPDATE", + d: { + ops: ops.map((x) => ({ + items: x.items, + op: "SYNC", + range: x.range, + })), + online_count: member_count - (groups.find(x => x.id == "offline")?.count ?? 0), + member_count, + id: "everyone", + guild_id, + groups, + }, + }); +} + +function partition(array: T[], isValid: Function) { + // @ts-ignore + return array.reduce( + // @ts-ignore + ([pass, fail], elem) => { + return isValid(elem) + ? [[...pass, elem], fail] + : [pass, [...fail, elem]]; + }, + [[], []] + ); +} diff --git a/src/gateway/opcodes/PresenceUpdate.ts b/src/gateway/opcodes/PresenceUpdate.ts new file mode 100644 index 00000000..415df6ee --- /dev/null +++ b/src/gateway/opcodes/PresenceUpdate.ts @@ -0,0 +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 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/src/gateway/opcodes/RequestGuildMembers.ts b/src/gateway/opcodes/RequestGuildMembers.ts new file mode 100644 index 00000000..b80721dc --- /dev/null +++ b/src/gateway/opcodes/RequestGuildMembers.ts @@ -0,0 +1,5 @@ +import { Payload, WebSocket } from "@fosscord/gateway"; + +export function onRequestGuildMembers(this: WebSocket, data: Payload) { + // return this.close(CLOSECODES.Unknown_error); +} diff --git a/src/gateway/opcodes/Resume.ts b/src/gateway/opcodes/Resume.ts new file mode 100644 index 00000000..42dc586d --- /dev/null +++ b/src/gateway/opcodes/Resume.ts @@ -0,0 +1,12 @@ +import { WebSocket, Payload } from "@fosscord/gateway"; +import { Send } from "../util/Send"; + +export async function onResume(this: WebSocket, data: Payload) { + console.log("Got Resume -> cancel not implemented"); + await Send(this, { + op: 9, + d: false, + }); + + // return this.close(CLOSECODES.Invalid_session); +} diff --git a/src/gateway/opcodes/VoiceStateUpdate.ts b/src/gateway/opcodes/VoiceStateUpdate.ts new file mode 100644 index 00000000..fa63f7fc --- /dev/null +++ b/src/gateway/opcodes/VoiceStateUpdate.ts @@ -0,0 +1,113 @@ +import { VoiceStateUpdateSchema } from "../schema/VoiceStateUpdateSchema"; +import { Payload, WebSocket } from "@fosscord/gateway"; +import { genVoiceToken } from "../util/SessionUtils"; +import { check } from "./instanceOf"; +import { + Config, + emitEvent, + Guild, + Member, + Region, + VoiceServerUpdateEvent, + VoiceState, + VoiceStateUpdateEvent, +} from "@fosscord/util"; +// TODO: check if a voice server is setup +// Notice: Bot users respect the voice channel's user limit, if set. When the voice channel is full, you will not receive the Voice State Update or Voice Server Update events in response to your own Voice State Update. Having MANAGE_CHANNELS permission bypasses this limit and allows you to join regardless of the channel being full or not. + +export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { + check.call(this, VoiceStateUpdateSchema, data.d); + const body = data.d as VoiceStateUpdateSchema; + + let voiceState: VoiceState; + try { + voiceState = await VoiceState.findOneOrFail({ + where: { user_id: this.user_id }, + }); + 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 + ) { + await emitEvent({ + event: "VOICE_STATE_UPDATE", + data: { ...voiceState, channel_id: null }, + guild_id: voiceState.guild_id, + }); + } + + //The event send by Discord's client on channel leave has both guild_id and channel_id as null + if (body.guild_id === null) body.guild_id = voiceState.guild_id; + voiceState.assign(body); + } catch (error) { + voiceState = VoiceState.create({ + ...body, + user_id: this.user_id, + deaf: false, + mute: false, + suppress: false, + }); + } + + // 'Fix' for this one voice state error + if (!voiceState.guild_id) return; + + //TODO the member should only have these properties: hoisted_role, deaf, joined_at, mute, roles, user + //TODO the member.user should only have these properties: avatar, discriminator, id, username + //TODO this may fail + voiceState.member = await Member.findOneOrFail({ + where: { id: voiceState.user_id, guild_id: voiceState.guild_id }, + relations: ["user", "roles"], + }); + + //If the session changed we generate a new token + if (voiceState.session_id !== this.session_id) + voiceState.token = genVoiceToken(); + voiceState.session_id = this.session_id; + + const { id, ...newObj } = voiceState; + + await Promise.all([ + voiceState.save(), + emitEvent({ + event: "VOICE_STATE_UPDATE", + data: newObj, + guild_id: voiceState.guild_id, + } as VoiceStateUpdateEvent), + ]); + + //If it's null it means that we are leaving the channel and this event is not needed + if (voiceState.channel_id !== null) { + const guild = await Guild.findOne({ where: { id: voiceState.guild_id } }); + const regions = Config.get().regions; + let guildRegion: Region; + if (guild && guild.region) { + guildRegion = regions.available.filter( + (r) => r.id === guild.region + )[0]; + } else { + guildRegion = regions.available.filter( + (r) => r.id === regions.default + )[0]; + } + + await emitEvent({ + event: "VOICE_SERVER_UPDATE", + data: { + token: voiceState.token, + guild_id: voiceState.guild_id, + endpoint: guildRegion.endpoint, + }, + guild_id: voiceState.guild_id, + } as VoiceServerUpdateEvent); + } +} diff --git a/src/gateway/opcodes/experiments.json b/src/gateway/opcodes/experiments.json new file mode 100644 index 00000000..0370b5da --- /dev/null +++ b/src/gateway/opcodes/experiments.json @@ -0,0 +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] +] diff --git a/src/gateway/opcodes/index.ts b/src/gateway/opcodes/index.ts new file mode 100644 index 00000000..027739db --- /dev/null +++ b/src/gateway/opcodes/index.ts @@ -0,0 +1,25 @@ +import { WebSocket, Payload } from "@fosscord/gateway"; +import { onHeartbeat } from "./Heartbeat"; +import { onIdentify } from "./Identify"; +import { onLazyRequest } from "./LazyRequest"; +import { onPresenceUpdate } from "./PresenceUpdate"; +import { onRequestGuildMembers } from "./RequestGuildMembers"; +import { onResume } from "./Resume"; +import { onVoiceStateUpdate } from "./VoiceStateUpdate"; + +export type OPCodeHandler = (this: WebSocket, data: Payload) => any; + +export default { + 1: onHeartbeat, + 2: onIdentify, + 3: onPresenceUpdate, + 4: onVoiceStateUpdate, + // 5: Voice Server Ping + 6: onResume, + // 7: Reconnect: You should attempt to reconnect and resume immediately. + 8: onRequestGuildMembers, + // 9: Invalid Session + // 10: Hello + // 13: Dm_update + 14: onLazyRequest, +}; diff --git a/src/gateway/opcodes/instanceOf.ts b/src/gateway/opcodes/instanceOf.ts new file mode 100644 index 00000000..6fd50852 --- /dev/null +++ b/src/gateway/opcodes/instanceOf.ts @@ -0,0 +1,18 @@ +import { instanceOf } from "lambert-server"; +import { WebSocket } from "@fosscord/gateway"; +import { CLOSECODES } from "../util/Constants"; + +export function check(this: WebSocket, schema: any, data: any) { + try { + const error = instanceOf(schema, data, { path: "body" }); + if (error !== true) { + throw error; + } + return true; + } catch (error) { + console.error(error); + // invalid payload + this.close(CLOSECODES.Decode_error); + throw error; + } +} -- cgit 1.4.1