summary refs log tree commit diff
path: root/src/gateway/events/Message.ts
blob: 569f5fc70258d1342e95874ce3ae518578e4ff05 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { CLOSECODES } from "../util/Constants";
import { WebSocket, Payload } from "@fosscord/gateway";
let erlpack: any;
try {
	erlpack = require("@yukikaze-bot/erlpack");
} catch (error) {}
import OPCodeHandlers from "../opcodes";
import { check } from "../opcodes/instanceOf";

const PayloadSchema = {
	op: Number,
	$d: Object || Number, // or number for heartbeat sequence
	$s: Number,
	$t: String,
};

export async function Message(this: WebSocket, buffer: Buffer) {
	// TODO: compression
	let data: Payload;

	if (this.encoding === "etf" && buffer instanceof Buffer)
		data = erlpack.unpack(buffer);
	else if (this.encoding === "json")
		data = JSON.parse(buffer as unknown as string); //TODO: is this even correct?? seems to work for web clients...
	else if(/--debug|--inspect/.test(process.execArgv.join(' '))) {
		debugger;
		return;
	}
	else {
		console.log("Invalid gateway connection! Use a debugger to inspect!");
		return;
	}

	if(process.env.WS_VERBOSE)
		console.log(`[Websocket] Incomming message: ${JSON.stringify(data)}`);
	if(data.op !== 1)
		check.call(this, PayloadSchema, data);
	else { //custom validation for numbers, because heartbeat
		if(data.s || data.t || (typeof data.d !== "number" && data.d)) {
			console.log("Invalid heartbeat...");
			this.close(CLOSECODES.Decode_error);
		}
	}

	// @ts-ignore
	const OPCodeHandler = OPCodeHandlers[data.op];
	if (!OPCodeHandler) {
		console.error("[Gateway] Unkown opcode " + data.op);
		// TODO: if all opcodes are implemented comment this out:
		// this.close(CLOSECODES.Unknown_opcode);
		return;
	}

	try {
		return await OPCodeHandler.call(this, data);
	} catch (error) {
		console.error(error);
		if (!this.CLOSED && this.CLOSING)
			return this.close(CLOSECODES.Unknown_error);
	}
}