discord-rpc/test-rpc-server/rpc-message.js

78 lines
1.9 KiB
JavaScript
Raw Normal View History

const path = require('path');
2017-06-27 20:23:09 +01:00
const VERSION = 1;
const OPCODES = {
HANDSHAKE: 0,
FRAME: 1,
CLOSE: 2,
2017-07-18 22:49:44 +01:00
PING: 3,
PONG: 4,
};
let PipePath;
if (process.platform == 'win32') {
PipePath = '\\\\?\\pipe\\discord-ipc';
}
else {
const temp = process.env.XDG_RUNTIME_DIR || process.env.TMPDIR || process.env.TMP || process.env.TEMP || '/tmp';
PipePath = path.join(temp, 'discord-ipc');
}
class RpcMessage {
static serialize(opcode, obj) {
2017-06-27 20:23:09 +01:00
const serializedJson = JSON.stringify(obj);
const msgLen = serializedJson.length;
let buff = Buffer.alloc(8 + msgLen);
buff.writeInt32LE(opcode, 0);
buff.writeInt32LE(msgLen, 4);
buff.write(serializedJson, 8, serializedJson.length, 'utf-8');
2017-06-27 20:23:09 +01:00
return buff;
}
static handshake(id) {
const opcode = OPCODES.HANDSHAKE;
return RpcMessage.serialize(opcode, {
client_id: id,
v: VERSION
});
}
static send(obj) {
const opcode = OPCODES.FRAME;
return RpcMessage.serialize(opcode, obj);
}
static sendClose(code, message) {
const opcode = OPCODES.CLOSE;
return RpcMessage.serialize(opcode, {code, message});
}
2017-07-18 22:49:44 +01:00
static sendPing(message) {
const opcode = OPCODES.PING;
return RpcMessage.serialize(opcode, {message});
}
2017-06-27 20:23:09 +01:00
static deserialize(buff) {
const opcode = buff.readInt32LE(0);
const msgLen = buff.readInt32LE(4);
2017-07-18 22:49:44 +01:00
if (msgLen == 0) {
return {opcode, data: ''};
}
if (buff.length < (msgLen + 8)) {
2017-06-27 20:23:09 +01:00
return null;
}
const msg = buff.toString('utf-8', 8, msgLen + 8);
2017-06-27 20:23:09 +01:00
try {
return {opcode, data: JSON.parse(msg)};
2017-06-27 20:23:09 +01:00
} catch(e) {
console.log(`failed to parse "${msg}"`);
console.error(e);
2017-07-10 22:54:58 +01:00
return {opcode: OPCODES.CLOSE, message: e.message};
2017-06-27 20:23:09 +01:00
}
}
};
module.exports = {OPCODES, PipePath, RpcMessage};