migrate parsing to backend

This commit is contained in:
jane 2021-06-04 16:14:40 -04:00
parent 03bbf03279
commit be73eaa4cd
4 changed files with 192 additions and 194 deletions

10
bot.js
View file

@ -1,6 +1,6 @@
import { createRequire } from 'module'; import { createRequire } from 'module';
import { discover } from './lights/light_parser.js'; //import { discover } from './lights/light_parser.js';
import { contactServer } from './lights/request.js'; //import { contactServer } from './lights/request.js';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
import Eris from 'eris'; import Eris from 'eris';
@ -105,6 +105,6 @@ let cmd_dir = path.join(dir, 'cmd');
log.debug(dir); log.debug(dir);
let files = fs.readdirSync(cmd_dir); let files = fs.readdirSync(cmd_dir);
load_commands(); load_commands();
contactServer(discover, (err) => { // contactServer(discover, (err) => {
log.error(err); // log.error(err);
}) // });

View file

@ -1,5 +1,5 @@
import { CommandInitializer, Command } from '../parser.js'; import { CommandInitializer, Command } from '../parser.js';
import parse, { discover, initialize, instructions } from '../lights/light_parser.js'; //import parse, { discover, initialize, instructions } from '../lights/light_parser.js';
import req from '../lights/request.js'; import req from '../lights/request.js';
const initializer = new CommandInitializer(); const initializer = new CommandInitializer();
@ -7,7 +7,7 @@ const initializer = new CommandInitializer();
class LightsParser extends Command { class LightsParser extends Command {
init(ctx, log) { init(ctx, log) {
this.log = log; this.log = log;
initialize(ctx); //initialize(ctx);
} }
name = 'lights'; name = 'lights';
whitelist = true; whitelist = true;
@ -20,21 +20,20 @@ class LightsParser extends Command {
msg.channel.createMessage('no args found.'); msg.channel.createMessage('no args found.');
return; return;
} }
let instructions = parse(args[0]); // let instructions = parse(args[0]);
this.log.debug(instructions); // this.log.debug(instructions);
let res = '```\n'; // let res = '```\n';
instructions.forEach((instruction) => { // instructions.forEach((instruction) => {
res += JSON.stringify(instruction) + '\n'; // res += JSON.stringify(instruction) + '\n';
}); // });
res += '```'; // res += '```';
msg.channel.createMessage(`parsed instructions:\n${res}`); // msg.channel.createMessage(`parsed instructions:\n${res}`);
req( req(
instructions.filter((i) => i.valid), args.join(' '),
(response) => { (response) => {
msg.channel.createMessage(`${response}`); msg.channel.createMessage(`\`\`\`\n${response}\`\`\``);
}, },
discover,
(error) => { (error) => {
msg.channel.createMessage(`error: ${error.message}`); msg.channel.createMessage(`error: ${error.message}`);
} }

View file

@ -1,169 +1,169 @@
import Logger, { levels } from '../logger.js'; // import Logger, { levels } from '../logger.js';
import { filename } from '../utils.js'; // import { filename } from '../utils.js';
const log = new Logger(filename(import.meta.url), "DEBUG"); // const log = new Logger(filename(import.meta.url), "DEBUG");
class Target { // class Target {
constructor(channel) { // constructor(channel) {
this.channel = channel; // this.channel = channel;
} // }
channel; // channel;
value; // value;
} // }
const available_targets = { // const available_targets = {
r: new Target('r'), // r: new Target('r'),
g: new Target('g'), // g: new Target('g'),
b: new Target('b'), // b: new Target('b'),
stack: new Target('stack'), // stack: new Target('stack'),
stack2: new Target('stack2'), // stack2: new Target('stack2'),
stack3: new Target('stack3'), // stack3: new Target('stack3'),
stack4: new Target('stack4'), // stack4: new Target('stack4'),
stack5: new Target('stack5'), // stack5: new Target('stack5'),
stack6: new Target('stack6'), // stack6: new Target('stack6'),
stack6: new Target('stackr'), // stack6: new Target('stackr'),
stack6: new Target('stackg'), // stack6: new Target('stackg'),
stack6: new Target('stackb'), // stack6: new Target('stackb'),
tick: new Target('tick'), // tick: new Target('tick'),
index: new Target('index'), // index: new Target('index'),
}; // };
class Instruction { // class Instruction {
constructor(name, targets, args) { // constructor(name, targets, args) {
let valid_targets = []; // let valid_targets = [];
let matched_args = []; // let matched_args = [];
targets.forEach((t, i) => { // targets.forEach((t, i) => {
if (t instanceof Target) { // if (t instanceof Target) {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel); // let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (match) { // if (match) {
if (args[i]) { // if (args[i]) {
matched_args.push({ // matched_args.push({
...t, // ...t,
arg: args[i] // arg: args[i]
}) // })
} // }
else { // else {
matched_args.push(t); // matched_args.push(t);
} // }
} // }
} // }
}); // });
this.name = name; // this.name = name;
this.targets = valid_targets; // this.targets = valid_targets;
this.args = matched_args; // this.args = matched_args;
} // }
name; // name;
targets; // targets;
args; // args;
} // }
export const instructions = [ // export const instructions = [
]; // ];
export function initialize(ctx) { // export function initialize(ctx) {
log.s(ctx.log_level); // log.s(ctx.log_level);
} // }
function parseSingleInstruction(str = '') { // function parseSingleInstruction(str = '') {
let item = { // let item = {
valid: false, // valid: false,
instruction: undefined, // instruction: undefined,
errors: undefined, // errors: undefined,
}; // };
let split = str.split(' '); // let split = str.split(' ');
let cmd = split[0]; // let cmd = split[0];
log.debug(cmd); // log.debug(cmd);
let match = instructions.filter((i) => i.n == cmd.toUpperCase()); // let match = instructions.filter((i) => i.n == cmd.toUpperCase());
log.debug(match); // log.debug(match);
split = split.slice(1); // split = split.slice(1);
if (match.length) { // if (match.length) {
let inst_targets = []; // let inst_targets = [];
let inst_args = []; // let inst_args = [];
let parsed_args = []; // let parsed_args = [];
let join_index = -1; // let join_index = -1;
let add = true; // let add = true;
for (let index in split) { // for (let index in split) {
if (split[index].startsWith('[')) { // if (split[index].startsWith('[')) {
join_index = index; // join_index = index;
add = false; // add = false;
} // }
if (add) { // if (add) {
parsed_args.push(split[index]); // parsed_args.push(split[index]);
} // }
if (split[index].endsWith(']') && join_index != -1) { // if (split[index].endsWith(']') && join_index != -1) {
let joined = split // let joined = split
.slice(join_index, index + 1) // .slice(join_index, index + 1)
.join(' ') // .join(' ')
.replace(/[\[\]]/g, ''); // .replace(/[\[\]]/g, '');
parsed_args.push(joined); // parsed_args.push(joined);
add = true; // add = true;
join_index = -1; // join_index = -1;
} // }
} // }
inst_targets = parsed_args[0] // inst_targets = parsed_args[0]
.split(',') // .split(',')
.map((s) => s.trim()) // .map((s) => s.trim())
.map((t) => new Target(t)); // .map((t) => new Target(t));
if (!inst_targets.length) { // if (!inst_targets.length) {
item.errors = 'No valid targets.'; // item.errors = 'No valid targets.';
} // }
inst_targets.forEach((t) => { // inst_targets.forEach((t) => {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel); // let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (!match) { // if (!match) {
item.errors = `Invalid target: ${t.channel}`; // item.errors = `Invalid target: ${t.channel}`;
} // }
}); // });
if (match[0].a) { // if (match[0].a) {
if (parsed_args.length < 2) { // if (parsed_args.length < 2) {
item.errors = 'Not enough arguments.'; // item.errors = 'Not enough arguments.';
return item; // return item;
} // }
inst_args = parsed_args[1] // inst_args = parsed_args[1]
.split(',') // .split(',')
.map((s) => s.trim()) // .map((s) => s.trim())
.map((s) => (available_targets[s] ? s : parseInt(s))); // .map((s) => (available_targets[s] ? s : parseInt(s)));
if (!inst_args.length) { // if (!inst_args.length) {
item.errors = 'No valid args.'; // item.errors = 'No valid args.';
} // }
inst_args.forEach((arg) => { // inst_args.forEach((arg) => {
if (arg === NaN) { // if (arg === NaN) {
item.errors = 'An argument is null or undefined.'; // item.errors = 'An argument is null or undefined.';
} // }
}); // });
} // }
if (item.errors) { // if (item.errors) {
return item; // return item;
} // }
item.instruction = new Instruction(match[0].n, inst_targets, inst_args || []); // item.instruction = new Instruction(match[0].n, inst_targets, inst_args || []);
} else { // } else {
item.errors = 'No command matched.'; // item.errors = 'No command matched.';
return item; // return item;
} // }
item.valid = true; // item.valid = true;
return item; // return item;
} // }
export function discover(data) { // export function discover(data) {
for (let value of data) { // for (let value of data) {
if (value.n != undefined) { // if (value.n != undefined) {
let found = instructions.filter((val) => { return val.n == value.n }); // let found = instructions.filter((val) => { return val.n == value.n });
if (!found.length) { // if (!found.length) {
log.debug(`discovered new keyword ${value.n}`); // log.debug(`discovered new keyword ${value.n}`);
instructions.push(value); // instructions.push(value);
} // }
} // }
} // }
} // }
export default function parse(str) { // export default function parse(str) {
let parsed = []; // let parsed = [];
let split = str.split('\n').filter((s) => s.length > 0); // let split = str.split('\n').filter((s) => s.length > 0);
split.forEach((item) => { // split.forEach((item) => {
let parsedItem = parseSingleInstruction(item); // let parsedItem = parseSingleInstruction(item);
parsed.push(parsedItem); // parsed.push(parsedItem);
log.debug(item); // log.debug(item);
}); // });
return parsed; // return parsed;
} // }

View file

@ -7,22 +7,22 @@ function getBinarySize(string) {
return Buffer.byteLength(string, 'utf8'); return Buffer.byteLength(string, 'utf8');
} }
export function contactServer(callback, errorCallback) { // export function contactServer(callback, errorCallback) {
let client = new net.Socket(); // let client = new net.Socket();
let c_port = global.ctx.lights.port || port; // let c_port = global.ctx.lights.port || port;
let c_addr = global.ctx.lights.addr || hostname; // let c_addr = global.ctx.lights.addr || hostname;
client.connect(c_port, c_addr, () => { // client.connect(c_port, c_addr, () => {
}); // });
client.on('data', (dat) => { // client.on('data', (dat) => {
let arr = JSON.parse(dat); // let arr = JSON.parse(dat);
callback(arr); // callback(arr);
client.destroy(); // client.destroy();
}) // })
} // }
export default function req(data, callback, newFuncCallback, errorCallback) { export default function req(data, callback, errorCallback) {
let string_data = JSON.stringify(data); let string_data = JSON.stringify(data);
let size = getBinarySize(string_data); let size = getBinarySize(string_data);
if (size > 9999) { if (size > 9999) {
@ -35,13 +35,12 @@ export default function req(data, callback, newFuncCallback, errorCallback) {
let c_port = global.ctx.lights.port || port; let c_port = global.ctx.lights.port || port;
let c_addr = global.ctx.lights.addr || hostname; let c_addr = global.ctx.lights.addr || hostname;
client.connect(c_port, c_addr, () => { }); client.connect(c_port, c_addr, () => { });
client.on('connect', () => {
client.on('data', (dat) => {
let arr = JSON.parse(dat);
newFuncCallback(arr);
client.write(string_data); client.write(string_data);
})
client.on('data', (dat) => {
callback(dat);
client.destroy(); client.destroy();
callback('success.');
}) })
client.on('error', (e) => { client.on('error', (e) => {