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,189 +11,134 @@ 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 banks;
return resolve(banks); }
banks = await util.httpGET(global.config.modep.host, global.config.modep.port, '/banks');
for (let index = 0; index < banks.length; index++) {
let bank = banks[index];
bank.id = index;
}
banks = util.sortById(banks);
cache.setBanks(banks);
return banks;
}
async function getBankById(bankId) {
const banks = await getBanks();
for (let index = 0; index < banks.length; index++) {
if (banks[index].id != bankId) {
continue;
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/banks') return banks[index];
.then(function (banks) { }
for (let index = 0; index < banks.length; index++) { throw new Error('could not find bank by id \'' + bankId + '\'');
let bank = banks[index];
bank.id = index;
}
banks = util.sortById(banks);
cache.setBanks(banks);
return resolve(banks);
})
.catch(reject);
});
} }
function getBankById(bankId) { async function getPedalboards() {
return new Promise(function (resolve, reject) { let pedalboards = cache.getPedalboards();
getBanks() if (pedalboards !== undefined) {
.then(function (banks) { return pedalboards;
for (let index = 0; index < banks.length; index++) { }
if (banks[index].id != bankId) { pedalboards = await util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/list');
continue; let id = 1;
} for (let index = 0; index < pedalboards.length; index++) {
return resolve(banks[index]); let pedalboard = pedalboards[index];
} if (pedalboard.bundle === constants.PEDALBOARD_DEFAULT) {
return reject('could not find bank by id \'' + bankId + '\''); pedalboard.id = 0;
}) defaultPedalboard = pedalboard;
.catch(reject); continue;
});
}
function getPedalboards() {
return new Promise(function (resolve, reject) {
let pedalboards = cache.getPedalboards();
if (pedalboards != undefined) {
return resolve(pedalboards);
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/list') pedalboard.id = id;
.then(function (pedalboards) { id++;
let id = 1; }
for (let index = 0; index < pedalboards.length; index++) { pedalboards = util.sortById(pedalboards);
let pedalboard = pedalboards[index]; cache.setPedalboards(pedalboards);
if (pedalboard.bundle == constants.PEDALBOARD_DEFAULT) { return pedalboards;
pedalboard.id = 0;
defaultPedalboard = pedalboard;
continue;
}
pedalboard.id = id;
id++;
}
pedalboards = util.sortById(pedalboards);
cache.setPedalboards(pedalboards);
return resolve(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 defaultPedalboard;
return resolve(defaultPedalboard); }
defaultPedalboard = await getPedalboardByBundle(constants.PEDALBOARD_DEFAULT);
cache.setDefaultPedalboard(defaultPedalboard);
return defaultPedalboard;
}
async function getCurrentPedalboard() {
let currentPedalboard = cache.getCurrentPedalboard();
if (currentPedalboard !== undefined) {
return currentPedalboard;
}
currentPedalboard = await getPedalboardByBundle(await util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/current'));
cache.setCurrentPedalboard(currentPedalboard);
return currentPedalboard;
}
async function getPedalboardById(pedalboardId) {
const pedalboards = await getPedalboards();
if (pedalboards === undefined) {
return;
}
for (let index = 0; index < pedalboards.length; index++) {
if (pedalboards[index].id != pedalboardId) {
continue;
} }
getPedalboardByBundle(constants.PEDALBOARD_DEFAULT) return pedalboards[index];
.then(function (defaultPedalboard) { }
cache.setDefaultPedalboard(defaultPedalboard); throw new Error('could not find pedalboard by id \'' + pedalboardId + '\'');
return resolve(defaultPedalboard);
})
.catch(reject);
});
} }
function getCurrentPedalboard() { async function getPedalboardByBundle(pedalboardBundle) {
return new Promise(function (resolve, reject) { if (pedalboardBundle === undefined) {
let currentPedalboard = cache.getCurrentPedalboard(); return await getDefaultPedalboard();
if (currentPedalboard != undefined && currentPedalboard.id != undefined) { }
return resolve(currentPedalboard); const pedalboards = await getPedalboards();
for (let index = 0; index < pedalboards.length; index++) {
if (pedalboards[index].bundle != pedalboardBundle) {
continue;
} }
util.httpGET(global.config.modep.host, global.config.modep.port, '/pedalboard/current') return pedalboards[index];
.then(getPedalboardByBundle) }
.then(function (currentPedalboard) { throw new Error('could not find pedalboard by bundle \'' + pedalboardBundle + '\'');
cache.setCurrentPedalboard(currentPedalboard);
return resolve(currentPedalboard)
})
.catch(reject);
});
} }
function getPedalboardById(pedalboardId) { async function getPedalControlById(pedalId, controlId) {
return new Promise(function (resolve, reject) { const pedal = await getCurrentPedalById(pedalId);
getPedalboards() for (let index = 0; index < pedal.controls.length; index++) {
.then(function (pedalboards) { if (pedal.controls[index].id != controlId) {
for (let index = 0; index < pedalboards.length; index++) { continue;
if (pedalboards[index].id != pedalboardId) {
continue;
}
return resolve(pedalboards[index]);
}
return reject('could not find pedalboard by id \'' + pedalboardId + '\'');
})
.catch(reject);
});
}
function getPedalboardByBundle(pedalboardBundle) {
return new Promise(function (resolve, reject) {
if (pedalboardBundle == undefined) {
getDefaultPedalboard()
.then(resolve)
.catch(reject);
return;
} }
getPedalboards() return pedal.controls[index];
.then(function (pedalboards) { }
for (let index = 0; index < pedalboards.length; index++) { throw new Error('could not find control for pedal \'' + pedalId + '\' by id \'' + controlId + '\'');
if (pedalboards[index].bundle != pedalboardBundle) {
continue;
}
return resolve(pedalboards[index]);
}
return reject('could not find pedalboard by bundle \'' + pedalboardBundle + '\'');
})
.catch(reject);
});
} }
function getPedalControlById(pedalId, controlId) { async function getCurrentPedalById(id) {
return new Promise(function (resolve, reject) { const currentPedals = await getCurrentPedals();
getCurrentPedalById(pedalId) for (let index = 0; index < currentPedals.length; index++) {
.then(function (pedal) { if (currentPedals[index].id != id) {
for (let index = 0; index < pedal.controls.length; index++) { continue;
if (pedal.controls[index].id != controlId) {
continue;
}
return resolve(pedal.controls[index]);
}
return reject('could not find control for pedal \'' + pedalId + '\' by id \'' + controlId + '\'');
})
.catch(reject);
});
}
function getCurrentPedalById(id) {
return new Promise(function (resolve, reject) {
getCurrentPedals()
.then(function (currentPedals) {
for (let index = 0; index < currentPedals.length; index++) {
if (currentPedals[index].id != id) {
continue;
}
return resolve(currentPedals[index]);
}
return reject('could not find current pedal by id \'' + id + '\'');
})
.catch(reject);
});
}
function getCurrentPedals() {
return new Promise(function (resolve, reject) {
let currentPedals = cache.getCurrentPedals();
if (currentPedals) {
return resolve(currentPedals);
} }
getCurrentPedalboard() return currentPedals[index];
.then(parseCurrentPedalboard) }
.then(resolve) throw new Error('could not find current pedal by id \'' + id + '\'');
.catch(reject); }
});
async function getCurrentPedals() {
let currentPedals = cache.getCurrentPedals();
if (currentPedals !== undefined) {
return currentPedals;
}
return await parseCurrentPedalboard(await getCurrentPedalboard());
} }
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,82 +157,82 @@ 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);
} }
let json = ttl2jsonld(data.toString())['@graph']; resolve(data);
let id = 0;
let currentPedals = [];
for (let index = 0; index < json.length; index++) {
let tmp = json[index];
if (tmp['lv2:prototype'] === undefined) {
continue;
}
let name = tmp['@id'];
currentPedals.push({ id: id, name: name, controls: [] });
id++;
}
for (let index = 0; index < json.length; index++) {
let tmp = json[index];
let name = tmp['@id'];
let value = tmp['ingen:value'];
if (value === undefined) {
continue;
}
let pedal = undefined;
for (let pedalIndex = 0; pedalIndex < currentPedals.length; pedalIndex++) {
if (!name.startsWith(currentPedals[pedalIndex].name)) {
continue;
}
pedal = currentPedals[pedalIndex];
break;
}
if (pedal === undefined) {
continue;
}
id = pedal.controls.length;
name = name.replace(pedal.name + '/', '');
if (name !== constants.CONTROL_BYPASS) {
value = value['@value'];
}
let control = { id, name, value };
pedal.controls.push(control);
id++;
let midi = tmp['midi:binding'];
if (midi === undefined) {
continue;
}
control.midi = { channel: midi['midi:channel'], controller: midi['midi:controllerNumber'] }
}
logger.debug('parsing current pedalboard file \'' + file + '\' took ' + util.timeDiff(startTime) + 'ms')
resolve(currentPedals);
}); });
}); });
let json = ttl2jsonld(data.toString())['@graph'];
let id = 0;
for (let index = 0; index < json.length; index++) {
let tmp = json[index];
if (tmp['lv2:prototype'] === undefined) {
continue;
}
let name = tmp['@id'];
pedals.push({ id: id, name: name, controls: [] });
id++;
}
for (let index = 0; index < json.length; index++) {
let tmp = json[index];
let name = tmp['@id'];
let value = tmp['ingen:value'];
if (value === undefined) {
continue;
}
let pedal = undefined;
for (let pedalIndex = 0; pedalIndex < pedals.length; pedalIndex++) {
if (!name.startsWith(pedals[pedalIndex].name)) {
continue;
}
pedal = pedals[pedalIndex];
break;
}
if (pedal === undefined) {
continue;
}
id = pedal.controls.length;
name = name.replace(pedal.name + '/', '');
if (name !== constants.CONTROL_BYPASS) {
value = value['@value'];
}
let control = { id, name, value };
pedal.controls.push(control);
id++;
let midi = tmp['midi:binding'];
if (midi === undefined) {
continue;
}
control.midi = { channel: midi['midi:channel'], controller: midi['midi:controllerNumber'] }
}
logger.debug('parsing current pedalboard file \'' + file + '\' took ' + util.timeDiff(startTime) + 'ms')
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) {
let controlId = requestParams.get('id'); throw new Error('could not handle POST missing all parameters', 400);
if (controlId === undefined) { }
reject('could not handle POST - missing parameter \'id\'', 400); let controlId = requestParams.get('id');
} if (controlId === undefined || controlId === null) {
let value = parseInt(requestParams.get('value')); throw new Error('could not handle POST - missing parameter \'id\'', 400);
if (value === undefined) { }
reject('could not handle POST - missing parameter \'value\'', 400); if (isNaN(controlId)) {
} else if (isNaN(value)) { throw new Error('parameter \'id\' is not a number', 400);
reject('parameter \'value\' is not a number', 400); }
} let value = requestParams.get('value');
getPedalControlById(pedalId, controlId) if (value === undefined || value === null) {
.then(function (control) { throw new Error('could not handle POST - missing parameter \'value\'', 400);
resolve(setControl(control, value)); }
}) if (isNaN(value)) {
.catch(reject); 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'); }
} if (isNaN(pedalboardId)) {
getPedalboardById(pedalboardId) throw new Error('given pedalboard id \'' + pedalboardId + '\' is not a number');
.then(setPedalboard) }
.then(resolve) return await setPedalboard(await getPedalboardById(pedalboardId));
.catch(reject);
});
} }
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'); }
} if (pedalboard.id === await getCurrentPedalboard().id) {
getCurrentPedalboard() throw new Error('pedalboard with id \'' + currentPedalboard.id + '\' is already active');
.then(function (currentPedalboard) { }
if (pedalboard.id === currentPedalboard.id) { await reset();
return Promise.reject('pedalboard with id \'' + currentPedalboard.id + '\' is already active'); await util.httpPOST(global.config.modep.host, global.config.modep.port, '/pedalboard/load_bundle/?bundlepath=' + pedalboard.bundle);
} cache.setCurrentPedalboard(pedalboard);
}) return await parseCurrentPedalboard(pedalboard);
.then(function () {
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);
return 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 = [
global.config.osc.host, global.config.osc.port,
global.config.osc.address,
'm',
'00' + util.toHex(value) + '0' + util.toHex(controller) + 'b' + util.toHex(channel)
];
try { try {
await commands.execute(CMD, args); await commands.execute(CMD, [
global.config.osc.host, global.config.osc.port,
global.config.osc.address,
'm',
'00' + util.toHex(value) + '0' + util.toHex(controller) + 'b' + util.toHex(channel)
]);
} 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'); }
} return await realpath(file);
realpath(file)
.then(resolve)
.catch((err) => {
reject('resolving path \'' + file + '\' encountered an error >>> ' + err);
});
});
} }
module.exports = { module.exports = {
timeDiff, timeDiff,
clone, clone,