heavy code optimization; async/await, arrow functions, etc.

This commit is contained in:
Daniel Sommer 2022-03-25 13:52:41 +01:00
parent b0c55b9e86
commit 823598aeb3
6 changed files with 227 additions and 321 deletions

View file

@ -1,4 +1,3 @@
const cache = require('./cache.js');
const commands = require('./commands.js'); const commands = require('./commands.js');
const os = require('os'); const os = require('os');

View file

@ -11,62 +11,46 @@ const ttl2jsonld = require('@frogcat/ttl2jsonld').parse;
let pedalboardIdBypassOrigin; let pedalboardIdBypassOrigin;
function reset() { async function reset() {
return new Promise(function (resolve, reject) { await util.httpGET(global.config.modep.host, global.config.modep.port, '/reset');
util.httpGET(global.config.modep.host, global.config.modep.port, '/reset')
.then(resolve)
.catch(reject);
});
} }
function getBanks() { async function getBanks() {
return new Promise(function (resolve, reject) {
let banks = cache.getBanks(); let banks = cache.getBanks();
if (banks != undefined) { if (banks !== undefined) {
return resolve(banks); return banks;
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/banks') banks = await util.httpGET(global.config.modep.host, global.config.modep.port, '/banks');
.then(function (banks) {
for (let index = 0; index < banks.length; index++) { for (let index = 0; index < banks.length; index++) {
let bank = banks[index]; let bank = banks[index];
bank.id = index; bank.id = index;
} }
banks = util.sortById(banks); banks = util.sortById(banks);
cache.setBanks(banks); cache.setBanks(banks);
return resolve(banks); return banks;
})
.catch(reject);
});
} }
function getBankById(bankId) { async function getBankById(bankId) {
return new Promise(function (resolve, reject) { const banks = await getBanks();
getBanks()
.then(function (banks) {
for (let index = 0; index < banks.length; index++) { for (let index = 0; index < banks.length; index++) {
if (banks[index].id != bankId) { if (banks[index].id != bankId) {
continue; continue;
} }
return resolve(banks[index]); return banks[index];
} }
return reject('could not find bank by id \'' + bankId + '\''); throw new Error('could not find bank by id \'' + bankId + '\'');
})
.catch(reject);
});
} }
function getPedalboards() { async function getPedalboards() {
return new Promise(function (resolve, reject) {
let pedalboards = cache.getPedalboards(); let pedalboards = cache.getPedalboards();
if (pedalboards != undefined) { if (pedalboards !== undefined) {
return resolve(pedalboards); return pedalboards;
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/list') pedalboards = await util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/list');
.then(function (pedalboards) {
let id = 1; let id = 1;
for (let index = 0; index < pedalboards.length; index++) { for (let index = 0; index < pedalboards.length; index++) {
let pedalboard = pedalboards[index]; let pedalboard = pedalboards[index];
if (pedalboard.bundle == constants.PEDALBOARD_DEFAULT) { if (pedalboard.bundle === constants.PEDALBOARD_DEFAULT) {
pedalboard.id = 0; pedalboard.id = 0;
defaultPedalboard = pedalboard; defaultPedalboard = pedalboard;
continue; continue;
@ -76,124 +60,85 @@ function getPedalboards() {
} }
pedalboards = util.sortById(pedalboards); pedalboards = util.sortById(pedalboards);
cache.setPedalboards(pedalboards); cache.setPedalboards(pedalboards);
return resolve(pedalboards); return pedalboards;
})
.catch(reject);
});
} }
function getDefaultPedalboard() { async function getDefaultPedalboard() {
return new Promise(function (resolve, reject) {
let defaultPedalboard = cache.getDefaultPedalboard(); let defaultPedalboard = cache.getDefaultPedalboard();
if (defaultPedalboard != undefined) { if (defaultPedalboard !== undefined) {
return resolve(defaultPedalboard); return defaultPedalboard;
} }
getPedalboardByBundle(constants.PEDALBOARD_DEFAULT) defaultPedalboard = await getPedalboardByBundle(constants.PEDALBOARD_DEFAULT);
.then(function (defaultPedalboard) {
cache.setDefaultPedalboard(defaultPedalboard); cache.setDefaultPedalboard(defaultPedalboard);
return resolve(defaultPedalboard); return defaultPedalboard;
})
.catch(reject);
});
} }
function getCurrentPedalboard() { async function getCurrentPedalboard() {
return new Promise(function (resolve, reject) {
let currentPedalboard = cache.getCurrentPedalboard(); let currentPedalboard = cache.getCurrentPedalboard();
if (currentPedalboard != undefined && currentPedalboard.id != undefined) { if (currentPedalboard !== undefined) {
return resolve(currentPedalboard); return currentPedalboard;
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/current') currentPedalboard = await getPedalboardByBundle(await util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/current'));
.then(getPedalboardByBundle)
.then(function (currentPedalboard) {
cache.setCurrentPedalboard(currentPedalboard); cache.setCurrentPedalboard(currentPedalboard);
return resolve(currentPedalboard) return currentPedalboard;
})
.catch(reject);
});
} }
function getPedalboardById(pedalboardId) { async function getPedalboardById(pedalboardId) {
return new Promise(function (resolve, reject) { const pedalboards = await getPedalboards();
getPedalboards() if (pedalboards === undefined) {
.then(function (pedalboards) { return;
}
for (let index = 0; index < pedalboards.length; index++) { for (let index = 0; index < pedalboards.length; index++) {
if (pedalboards[index].id != pedalboardId) { if (pedalboards[index].id != pedalboardId) {
continue; continue;
} }
return resolve(pedalboards[index]); return pedalboards[index];
} }
return reject('could not find pedalboard by id \'' + pedalboardId + '\''); throw new Error('could not find pedalboard by id \'' + pedalboardId + '\'');
})
.catch(reject);
});
} }
function getPedalboardByBundle(pedalboardBundle) { async function getPedalboardByBundle(pedalboardBundle) {
return new Promise(function (resolve, reject) { if (pedalboardBundle === undefined) {
if (pedalboardBundle == undefined) { return await getDefaultPedalboard();
getDefaultPedalboard()
.then(resolve)
.catch(reject);
return;
} }
getPedalboards() const pedalboards = await getPedalboards();
.then(function (pedalboards) {
for (let index = 0; index < pedalboards.length; index++) { for (let index = 0; index < pedalboards.length; index++) {
if (pedalboards[index].bundle != pedalboardBundle) { if (pedalboards[index].bundle != pedalboardBundle) {
continue; continue;
} }
return resolve(pedalboards[index]); return pedalboards[index];
} }
return reject('could not find pedalboard by bundle \'' + pedalboardBundle + '\''); throw new Error('could not find pedalboard by bundle \'' + pedalboardBundle + '\'');
})
.catch(reject);
});
} }
function getPedalControlById(pedalId, controlId) { async function getPedalControlById(pedalId, controlId) {
return new Promise(function (resolve, reject) { const pedal = await getCurrentPedalById(pedalId);
getCurrentPedalById(pedalId)
.then(function (pedal) {
for (let index = 0; index < pedal.controls.length; index++) { for (let index = 0; index < pedal.controls.length; index++) {
if (pedal.controls[index].id != controlId) { if (pedal.controls[index].id != controlId) {
continue; continue;
} }
return resolve(pedal.controls[index]); return pedal.controls[index];
} }
return reject('could not find control for pedal \'' + pedalId + '\' by id \'' + controlId + '\''); throw new Error('could not find control for pedal \'' + pedalId + '\' by id \'' + controlId + '\'');
})
.catch(reject);
});
} }
function getCurrentPedalById(id) { async function getCurrentPedalById(id) {
return new Promise(function (resolve, reject) { const currentPedals = await getCurrentPedals();
getCurrentPedals()
.then(function (currentPedals) {
for (let index = 0; index < currentPedals.length; index++) { for (let index = 0; index < currentPedals.length; index++) {
if (currentPedals[index].id != id) { if (currentPedals[index].id != id) {
continue; continue;
} }
return resolve(currentPedals[index]); return currentPedals[index];
} }
return reject('could not find current pedal by id \'' + id + '\''); throw new Error('could not find current pedal by id \'' + id + '\'');
})
.catch(reject);
});
} }
function getCurrentPedals() { async function getCurrentPedals() {
return new Promise(function (resolve, reject) {
let currentPedals = cache.getCurrentPedals(); let currentPedals = cache.getCurrentPedals();
if (currentPedals) { if (currentPedals !== undefined) {
return resolve(currentPedals); return currentPedals;
} }
getCurrentPedalboard() return await parseCurrentPedalboard(await getCurrentPedalboard());
.then(parseCurrentPedalboard)
.then(resolve)
.catch(reject);
});
} }
async function parseCurrentPedalboard(currentPedalboard) { async function parseCurrentPedalboard(currentPedalboard) {
@ -204,7 +149,6 @@ async function parseCurrentPedalboard(currentPedalboard) {
blinky.setStatus(pedals); blinky.setStatus(pedals);
return pedals; return pedals;
} }
let startTime = new Date(); let startTime = new Date();
logger.debug('parsing current pedalboard \'' + currentPedalboard.title + '\'...'); logger.debug('parsing current pedalboard \'' + currentPedalboard.title + '\'...');
if (currentPedalboard.uri === undefined) { if (currentPedalboard.uri === undefined) {
@ -213,21 +157,23 @@ async function parseCurrentPedalboard(currentPedalboard) {
// FAKE DATA // FAKE DATA
let file = path.resolve(path.dirname(__dirname) + '/dev/' + currentPedalboard.uri.substring(currentPedalboard.uri.lastIndexOf('/') + 1)); let file = path.resolve(path.dirname(__dirname) + '/dev/' + currentPedalboard.uri.substring(currentPedalboard.uri.lastIndexOf('/') + 1));
// let file = path.resolve(currentPedalboard.uri.replace('file://', '')); // let file = path.resolve(currentPedalboard.uri.replace('file://', ''));
pedals = await new Promise((resolve, reject) => { const data = await new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => { fs.readFile(file, (err, data) => {
if (err) { if (err) {
return reject('could not parse current pedalboard file \'' + file + '\' >>> ' + err); return reject('could not parse current pedalboard file \'' + file + '\' >>> ' + err);
} }
resolve(data);
});
});
let json = ttl2jsonld(data.toString())['@graph']; let json = ttl2jsonld(data.toString())['@graph'];
let id = 0; let id = 0;
let currentPedals = [];
for (let index = 0; index < json.length; index++) { for (let index = 0; index < json.length; index++) {
let tmp = json[index]; let tmp = json[index];
if (tmp['lv2:prototype'] === undefined) { if (tmp['lv2:prototype'] === undefined) {
continue; continue;
} }
let name = tmp['@id']; let name = tmp['@id'];
currentPedals.push({ id: id, name: name, controls: [] }); pedals.push({ id: id, name: name, controls: [] });
id++; id++;
} }
for (let index = 0; index < json.length; index++) { for (let index = 0; index < json.length; index++) {
@ -238,11 +184,11 @@ async function parseCurrentPedalboard(currentPedalboard) {
continue; continue;
} }
let pedal = undefined; let pedal = undefined;
for (let pedalIndex = 0; pedalIndex < currentPedals.length; pedalIndex++) { for (let pedalIndex = 0; pedalIndex < pedals.length; pedalIndex++) {
if (!name.startsWith(currentPedals[pedalIndex].name)) { if (!name.startsWith(pedals[pedalIndex].name)) {
continue; continue;
} }
pedal = currentPedals[pedalIndex]; pedal = pedals[pedalIndex];
break; break;
} }
if (pedal === undefined) { if (pedal === undefined) {
@ -263,32 +209,30 @@ async function parseCurrentPedalboard(currentPedalboard) {
control.midi = { channel: midi['midi:channel'], controller: midi['midi:controllerNumber'] } control.midi = { channel: midi['midi:channel'], controller: midi['midi:controllerNumber'] }
} }
logger.debug('parsing current pedalboard file \'' + file + '\' took ' + util.timeDiff(startTime) + 'ms') logger.debug('parsing current pedalboard file \'' + file + '\' took ' + util.timeDiff(startTime) + 'ms')
resolve(currentPedals);
});
});
cache.setCurrentPedals(pedals); cache.setCurrentPedals(pedals);
blinky.setStatus(pedals); blinky.setStatus(pedals);
return pedals; return pedals;
} }
function setControlByRequest(pedalId, requestParams) { async function setControlByRequest(pedalId, requestParams) {
return new Promise(function (resolve, reject) { if (requestParams === undefined) {
throw new Error('could not handle POST missing all parameters', 400);
}
let controlId = requestParams.get('id'); let controlId = requestParams.get('id');
if (controlId === undefined) { if (controlId === undefined || controlId === null) {
reject('could not handle POST - missing parameter \'id\'', 400); throw new Error('could not handle POST - missing parameter \'id\'', 400);
} }
let value = parseInt(requestParams.get('value')); if (isNaN(controlId)) {
if (value === undefined) { throw new Error('parameter \'id\' is not a number', 400);
reject('could not handle POST - missing parameter \'value\'', 400);
} else if (isNaN(value)) {
reject('parameter \'value\' is not a number', 400);
} }
getPedalControlById(pedalId, controlId) let value = requestParams.get('value');
.then(function (control) { if (value === undefined || value === null) {
resolve(setControl(control, value)); throw new Error('could not handle POST - missing parameter \'value\'', 400);
}) }
.catch(reject); if (isNaN(value)) {
}); throw new Error('parameter \'value\' is not a number', 400);
}
return await setControl(await getPedalControlById(pedalId, controlId), parseInt(value));
} }
async function setControl(control, value) { async function setControl(control, value) {
@ -299,42 +243,27 @@ async function setControl(control, value) {
cache.updateControl(control); cache.updateControl(control);
} }
function setPedalboardById(pedalboardId) { async function setPedalboardById(pedalboardId) {
return new Promise(function (resolve, reject) { if (pedalboardId === undefined) {
if (pedalboardId == undefined) { throw new Error('no pedalboard id given');
return reject('no pedalboard id given');
} }
getPedalboardById(pedalboardId) if (isNaN(pedalboardId)) {
.then(setPedalboard) throw new Error('given pedalboard id \'' + pedalboardId + '\' is not a number');
.then(resolve) }
.catch(reject); return await setPedalboard(await getPedalboardById(pedalboardId));
});
} }
function setPedalboard(pedalboard) { async function setPedalboard(pedalboard) {
return new Promise(function (resolve, reject) { if (pedalboard?.bundle === undefined) {
if (!pedalboard || !pedalboard.bundle) { throw new Error('no bundle set for pedalboard \'' + pedalboard.title + '\'');
return reject('no bundle set for pedalboard');
} }
getCurrentPedalboard() if (pedalboard.id === await getCurrentPedalboard().id) {
.then(function (currentPedalboard) { throw new Error('pedalboard with id \'' + currentPedalboard.id + '\' is already active');
if (pedalboard.id === currentPedalboard.id) {
return Promise.reject('pedalboard with id \'' + currentPedalboard.id + '\' is already active');
} }
}) await reset();
.then(function () { await util.httpPOST(global.config.modep.host, global.config.modep.port, '/pedalboard/load_bundle/?bundlepath=' + pedalboard.bundle);
return reset()
})
.then(function () {
return util.httpPOST(global.config.modep.host, global.config.modep.port, '/pedalboard/load_bundle/?bundlepath=' + pedalboard.bundle)
})
.then(function () {
cache.setCurrentPedalboard(pedalboard); cache.setCurrentPedalboard(pedalboard);
return parseCurrentPedalboard(pedalboard); return await parseCurrentPedalboard(pedalboard);
})
.then(resolve)
.catch(reject);
});
} }
function hasControlMidiBindings(control) { function hasControlMidiBindings(control) {

View file

@ -5,7 +5,7 @@ const commands = require('./commands.js');
const CMD = 'oscsend'; const CMD = 'oscsend';
async function send(controller, channel, value) { async function send(controller, channel, value) {
if (controller == undefined || channel === undefined) { if (controller === undefined || channel === undefined) {
return; return;
} }
if (value === undefined || isNaN(value) || value < 0) { if (value === undefined || isNaN(value) || value < 0) {
@ -14,14 +14,13 @@ async function send(controller, channel, value) {
value = 127; value = 127;
} }
logger.debug('sending value \'' + value + '\' to controller \'' + controller + '\' on channel \'' + channel + '\'...'); logger.debug('sending value \'' + value + '\' to controller \'' + controller + '\' on channel \'' + channel + '\'...');
let args = [ try {
await commands.execute(CMD, [
global.config.osc.host, global.config.osc.port, global.config.osc.host, global.config.osc.port,
global.config.osc.address, global.config.osc.address,
'm', 'm',
'00' + util.toHex(value) + '0' + util.toHex(controller) + 'b' + util.toHex(channel) '00' + util.toHex(value) + '0' + util.toHex(controller) + 'b' + util.toHex(channel)
]; ]);
try {
await commands.execute(CMD, args);
} catch (err) { } catch (err) {
throw new Error(err); throw new Error(err);
} }

View file

@ -11,7 +11,7 @@ async function start() {
if (!server) { if (!server) {
server = http.createServer(); server = http.createServer();
} }
server.listen(global.config.server.port, global.config.server.listen).on('listening', function () { server.listen(global.config.server.port, global.config.server.listen).on('listening', () => {
logger.debug('server listening on ' + global.config.server.listen + ':' + global.config.server.port + '...'); logger.debug('server listening on ' + global.config.server.listen + ':' + global.config.server.port + '...');
blinky.setActive(true); blinky.setActive(true);
handleRequests(); handleRequests();
@ -19,7 +19,7 @@ async function start() {
} }
function handleRequests() { function handleRequests() {
server.on('request', function (request, response) { server.on('request', (request, response) => {
request.timestamp = new Date().getTime(); request.timestamp = new Date().getTime();
if (request.url.length > 1 && request.url.endsWith('/')) { if (request.url.length > 1 && request.url.endsWith('/')) {
request.url = request.url.substring(0, request.url.length - 1); request.url = request.url.substring(0, request.url.length - 1);
@ -54,13 +54,13 @@ function handleRequests() {
return; return;
} }
getRequestParams(request) getRequestParams(request)
.then(function (params) { .then((params) => {
return endpoint.method(id, params); return endpoint.method(id, params);
}) })
.then(function (result) { .then((result) => {
endRequest(request, response, result); endRequest(request, response, result);
}) })
.catch(function (err, code) { .catch((err, code) => {
if (code == undefined) { if (code == undefined) {
code = 500; code = 500;
} }
@ -84,20 +84,20 @@ function endRequest(request, response, msg, code) {
object.data = msg; object.data = msg;
} }
} }
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); response.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
response.writeHead(object.code); response.writeHead(object.code);
response.end(object.data); response.end(object.data);
logger.http(object); logger.http(object);
} }
function getRequestParams(request) { function getRequestParams(request) {
return new Promise(function (resolve, reject) { return new Promise((resolve, reject) => {
var params = ""; var params = '';
request.on("data", function (data) { request.on('data', (data) => {
params += data; params += data;
}); });
request.on("end", function () { request.on('end', () => {
if (params == undefined || params.length == 0) { if (params == undefined || params.length == 0) {
return resolve(); return resolve();
} }

View file

@ -1,7 +1,6 @@
const logger = require('./logger.js'); const logger = require('./logger.js');
const commands = require('./commands.js'); const commands = require('./commands.js');
const constants = require('./constants.js'); const constants = require('./constants.js');
const blinky = require('./blinky.js');
async function getServiceState(name) { async function getServiceState(name) {
if (name === undefined) { if (name === undefined) {

View file

@ -29,8 +29,8 @@ function httpPOST(host, port, path, args) {
function httpRequest(host, port, path, method, args) { function httpRequest(host, port, path, method, args) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!path.startsWith("/")) { if (!path.startsWith('/')) {
path = "/" + path; path = '/' + path;
} }
const options = { const options = {
hostname: host, hostname: host,
@ -53,7 +53,7 @@ function httpRequest(host, port, path, method, args) {
if (!response) { if (!response) {
return reject('no response from host for ' + requestName); return reject('no response from host for ' + requestName);
} }
let responseData = ""; let responseData = '';
response.on('data', (data) => { response.on('data', (data) => {
responseData += data; responseData += data;
}); });
@ -89,8 +89,7 @@ function httpRequest(host, port, path, method, args) {
} }
function toHex(value) { function toHex(value) {
let hex = Number(value).toString(16); return Number(value).toString(16);
return hex;
} }
function hexToRGB(hex) { function hexToRGB(hex) {
@ -98,14 +97,13 @@ function hexToRGB(hex) {
if (!validHEXInput) { if (!validHEXInput) {
return; return;
} }
let output = [ return [
{ {
red: parseInt(validHEXInput[1], 16), red: parseInt(validHEXInput[1], 16),
green: parseInt(validHEXInput[2], 16), green: parseInt(validHEXInput[2], 16),
blue: parseInt(validHEXInput[3], 16), blue: parseInt(validHEXInput[3], 16),
}, }
]; ];
return output;
} }
function sortById(array) { function sortById(array) {
@ -114,37 +112,19 @@ function sortById(array) {
}); });
} }
function fileExists(file) { async function fileExists(file) {
return new Promise((resolve, reject) => { const path = await resolvePath(file);
if (file == undefined) { const stats = await stat(path);
reject('can not check the existence of an undefined file'); return {path, stats};
}
resolvePath(file)
.then((path) => {
stat(path)
.then((stats) => {
resolve({ path, stats });
})
})
.catch(reject);
});
} }
function resolvePath(file) { async function resolvePath(file) {
return new Promise((resolve, reject) => { if (file === undefined) {
if (file == undefined) { throw new Error('can not resolve a path to an undefined file');
reject('can not resolve a path to an undefined file');
} }
realpath(file) return await realpath(file);
.then(resolve)
.catch((err) => {
reject('resolving path \'' + file + '\' encountered an error >>> ' + err);
});
});
} }
module.exports = { module.exports = {
timeDiff, timeDiff,
clone, clone,