This repository has been archived on 2022-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
brainlet/api/v2/gateway/messageparser.js

57 lines
2.2 KiB
JavaScript
Raw Normal View History

const opcodes = {
0: { name: "HELLO", data: "JSON" },
1: { name: "YOO", data: "JSON" },
2: { name: "YOO_ACK", data: "JSON" },
3: { name: "ACTION_CREATE_MESSAGE", data: "JSON" },
4: { name: "EVENT_CREATE_MESSAGE", data: "JSON" },
5: { name: "ACTION_UPDATE_STATUS", data: "JSON" },
6: { name: "EVENT_CHANNEL_MEMBERS", data: "JSON" },
2021-09-08 00:18:44 +03:00
7: { name: "ACTION_PING", data: "string" },
21: { name: "ACTION_VOICE_REQUEST_SESSION", data: "JSON" },
22: { name: "EVENT_VOICE_ASSIGN_SERVER", data: "JSON" },
23: { name: "ACTION_VOICE_CONNECTION_REQUEST", data: "JSON" },
24: { name: "EVENT_VOICE_CONNECTION_ANSWER", data: "JSON" },
25: { name: "EVENT_RENEGOTIATE_REQUIRED", data: "JSON" },
2021-06-02 04:44:52 +03:00
26: { name: "EVENT_TRACK_NOTIFICATION", data: "JSON" }
};
const opcodeSeparator = "@";
const parseMessage = (message) => {
if (typeof message !== "string") throw new Error("msg: message not a string");
const stringParts = message.split(opcodeSeparator);
if (stringParts < 2) throw new Error("msg: message does not split into more than 2 parts");
const components = [ stringParts.shift(), stringParts.join(opcodeSeparator) ];
const op = parseInt(components[0]);
if (isNaN(op)) throw new Error(`msg: message does not contain valid opcode: ${op}`);
const opcodeData = opcodes[op];
let data = components[1];
if (!opcodeData) throw new Error(`msg: message contains unknown opcode ${op}`);
if (opcodeData.data === "JSON") {
data = JSON.parse(data);
} else if (opcodeData.data === "string") {
data = data.toString(); // NOTE: This isnt needed lol
} else {
throw new Error(`msg: invalid data type on opcode ${op}`);
}
return {
opcode: op,
data: data,
dataType: opcodeData.data,
opcodeType: opcodeData.name || null
};
};
const getOpcodeByName = (name) => {
for (const [key, value] of Object.entries(opcodes)) if (value.name === name) return key;
};
const packet = (op, data) => {
if (typeof op === "string") op = getOpcodeByName(op);
return `${op}${opcodeSeparator}${JSON.stringify(data)}`;
};
module.exports = { opcodes, parseMessage, opcodeSeparator, getOpcodeByName, packet };