summary refs log tree commit diff
path: root/gateway/src/opcodes
diff options
context:
space:
mode:
Diffstat (limited to 'gateway/src/opcodes')
-rw-r--r--gateway/src/opcodes/Heartbeat.ts11
-rw-r--r--gateway/src/opcodes/LazyRequest.ts173
-rw-r--r--gateway/src/opcodes/PresenceUpdate.ts24
-rw-r--r--gateway/src/opcodes/RequestGuildMembers.ts5
-rw-r--r--gateway/src/opcodes/Resume.ts12
-rw-r--r--gateway/src/opcodes/VoiceStateUpdate.ts116
-rw-r--r--gateway/src/opcodes/experiments.json76
-rw-r--r--gateway/src/opcodes/index.ts25
-rw-r--r--gateway/src/opcodes/instanceOf.ts18
9 files changed, 0 insertions, 460 deletions
diff --git a/gateway/src/opcodes/Heartbeat.ts b/gateway/src/opcodes/Heartbeat.ts
deleted file mode 100644

index 42b72d4b..00000000 --- a/gateway/src/opcodes/Heartbeat.ts +++ /dev/null
@@ -1,11 +0,0 @@ -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/gateway/src/opcodes/LazyRequest.ts b/gateway/src/opcodes/LazyRequest.ts deleted file mode 100644
index cd0586de..00000000 --- a/gateway/src/opcodes/LazyRequest.ts +++ /dev/null
@@ -1,173 +0,0 @@ -import { getPermission, listenEvent, Member, Role, getOrInitialiseDatabase, LazyRequest } from "@fosscord/util"; -import { Send } from "../util/Send"; -import { OPCODES } from "../util/Constants"; -import { WebSocket, Payload, handlePresenceUpdate } from "@fosscord/gateway"; -import { check } from "./instanceOf"; -import { getRepository } from "typeorm"; - -// 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 - // TODO: rewrite this, released in 0.3.0 - - let members = await (await getOrInitialiseDatabase()).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[]; - const items = []; - const member_roles = members - .map((m) => m.roles) - .flat() - .unique((r: Role) => r.id); - - const offlineItems = []; - - 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) - ); - 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 session = member.user.sessions.first(); - - // TODO: properly mock/hide offline/invisible status - const item = { - member: { - ...member, - roles, - user: { ...member.user, sessions: undefined }, - presence: { - ...session, - activities: session?.activities || [], - user: { id: member.user.id }, - }, - }, - } - - if (!member?.user?.sessions || !member.user.sessions.length) { - 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 (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: ops.map((x) => ({ - items: x.items, - op: "SYNC", - range: x.range, - })), - online_count: member_count, - member_count, - id: "everyone", - guild_id, - 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] - : [pass, [...fail, elem]]; - }, - [[], []] - ); -} diff --git a/gateway/src/opcodes/PresenceUpdate.ts b/gateway/src/opcodes/PresenceUpdate.ts deleted file mode 100644
index f31c9161..00000000 --- a/gateway/src/opcodes/PresenceUpdate.ts +++ /dev/null
@@ -1,24 +0,0 @@ -import { WebSocket, Payload } from "@fosscord/gateway"; -import { ActivitySchema, emitEvent, PresenceUpdateEvent, Session, User } from "@fosscord/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 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/opcodes/RequestGuildMembers.ts b/gateway/src/opcodes/RequestGuildMembers.ts deleted file mode 100644
index b80721dc..00000000 --- a/gateway/src/opcodes/RequestGuildMembers.ts +++ /dev/null
@@ -1,5 +0,0 @@ -import { Payload, WebSocket } from "@fosscord/gateway"; - -export function onRequestGuildMembers(this: WebSocket, data: Payload) { - // return this.close(CLOSECODES.Unknown_error); -} diff --git a/gateway/src/opcodes/Resume.ts b/gateway/src/opcodes/Resume.ts deleted file mode 100644
index 42dc586d..00000000 --- a/gateway/src/opcodes/Resume.ts +++ /dev/null
@@ -1,12 +0,0 @@ -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/gateway/src/opcodes/VoiceStateUpdate.ts b/gateway/src/opcodes/VoiceStateUpdate.ts deleted file mode 100644
index 73f73565..00000000 --- a/gateway/src/opcodes/VoiceStateUpdate.ts +++ /dev/null
@@ -1,116 +0,0 @@ -import { Payload, WebSocket } from "@fosscord/gateway"; -import { genVoiceToken } from "../util/SessionUtils"; -import { check } from "./instanceOf"; -import { - Config, - emitEvent, - Guild, - Member, - VoiceServerUpdateEvent, - VoiceState, - VoiceStateUpdateEvent, - VoiceStateUpdateSchema, -} from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; -import { Region } from "@fosscord/util/src/config"; -// 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; - - if(body.guild_id == null) { - console.log(`[Gateway] VoiceStateUpdate called with guild_id == null by user ${this.user_id}!`); - return; - } - - 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 = OrmUtils.mergeDeep(voiceState, body); - } catch (error) { - voiceState = OrmUtils.mergeDeep(new VoiceState(), { - ...body, - user_id: this.user_id, - deaf: false, - mute: false, - suppress: false, - }); - } - - //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/gateway/src/opcodes/experiments.json b/gateway/src/opcodes/experiments.json deleted file mode 100644
index 0370b5da..00000000 --- a/gateway/src/opcodes/experiments.json +++ /dev/null
@@ -1,76 +0,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/gateway/src/opcodes/index.ts b/gateway/src/opcodes/index.ts deleted file mode 100644
index 027739db..00000000 --- a/gateway/src/opcodes/index.ts +++ /dev/null
@@ -1,25 +0,0 @@ -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/gateway/src/opcodes/instanceOf.ts b/gateway/src/opcodes/instanceOf.ts deleted file mode 100644
index eb6f6ea1..00000000 --- a/gateway/src/opcodes/instanceOf.ts +++ /dev/null
@@ -1,18 +0,0 @@ -import { instanceOf } from "@fosscord/util"; -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; - } -}