const logger = require('./logger.js'); const FILTER_START = 'Testing ... (interrupt to exit)'; const KEY_PREFIX = 'KEY_'; const ACTION_KEYUP = { id: 0, action: 'keyup' }; const ACTION_KEYDOWN = { id: 1, action: 'keydown' }; const ACTION_KEYHOLD = { id: 2, action: 'keyhold' }; class Keyfilter { constructor(config) { if (config == undefined || config.length == 0) { return; } this.actions = new Map(); for (var index = 0; index < config.length; index++) { var type = ACTION_KEYDOWN; switch (config[index].type.toLowerCase()) { case ACTION_KEYUP.action: type = ACTION_KEYUP; break; case ACTION_KEYHOLD.action: type = ACTION_KEYHOLD; break; } var command = config[index].command; var args = config[index].args; var delay = config[index].delay; this.actions.set(KEY_PREFIX + config[index].key.toUpperCase(), { type, command, args, delay }); } } filterActive(input) { if (this.active) { return true; } input = input.toString(); var index = input.indexOf(FILTER_START); if (index == -1) { return; } input = input.substring(index + FILTER_START.length).trim(); this.active = true; return true; } filter(input) { if (input == undefined || input.length == 0) { return; } input = input.toString(); if (!this.filterActive(input)) { return; } var lines = input.split("\n"); for (var index = 0; index < lines.length; index++) { var line = lines[index]; if (line.length == 0) { continue; } for (var [key, value] of this.actions) { if (!line.includes(key)) { continue; } if (!line.endsWith('value ' + value.type.id)) { continue; } var action = this.actions.get(key); if (this.shouldBeDelayed(action)) { return { key: key, type: action.type.action, delayed: true }; } action.executed = new Date().getTime(); return { key: key, type: action.type.action, command: action.command, args: action.args }; } } } shouldBeDelayed(action) { if (action.delay == undefined || action.delay == 0 || action.executed == undefined) { return false; } return new Date().getTime() - action.executed < action.delay; } } module.exports = Keyfilter;