88 lines
2.6 KiB
JavaScript
88 lines
2.6 KiB
JavaScript
'use strict';
|
|
|
|
const childProcess = require('child_process');
|
|
|
|
module.exports = class Util {
|
|
|
|
static isValidIPv4(str) {
|
|
const blocks = str.split('.');
|
|
if (blocks.length !== 4) return false;
|
|
|
|
for (let value of blocks) {
|
|
value = parseInt(value, 10);
|
|
if (Number.isNaN(value)) return false;
|
|
if (value < 0 || value > 255) return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
static isValidIPv6(str) {
|
|
// Regex source : https://stackoverflow.com/a/17871737
|
|
const regex = new RegExp('^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$');
|
|
const matches = str.match(regex);
|
|
return !!matches;
|
|
}
|
|
|
|
static promisify(fn) {
|
|
// eslint-disable-next-line func-names
|
|
return function(req, res) {
|
|
Promise.resolve().then(async () => fn(req, res))
|
|
.then((result) => {
|
|
if (res.headersSent) return;
|
|
|
|
if (typeof result === 'undefined') {
|
|
return res
|
|
.status(204)
|
|
.end();
|
|
}
|
|
|
|
return res
|
|
.status(200)
|
|
.json(result);
|
|
})
|
|
.catch((error) => {
|
|
if (typeof error === 'string') {
|
|
error = new Error(error);
|
|
}
|
|
|
|
// eslint-disable-next-line no-console
|
|
console.error(error);
|
|
|
|
return res
|
|
.status(error.statusCode || 500)
|
|
.json({
|
|
error: error.message || error.toString(),
|
|
stack: error.stack,
|
|
});
|
|
});
|
|
};
|
|
}
|
|
|
|
static async exec(cmd, {
|
|
log = true,
|
|
} = {}) {
|
|
if (typeof log === 'string') {
|
|
// eslint-disable-next-line no-console
|
|
console.log(`$ ${log}`);
|
|
} else if (log === true) {
|
|
// eslint-disable-next-line no-console
|
|
console.log(`$ ${cmd}`);
|
|
}
|
|
|
|
if (process.platform !== 'linux') {
|
|
return '';
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
childProcess.exec(cmd, {
|
|
shell: 'bash',
|
|
}, (err, stdout) => {
|
|
if (err) return reject(err);
|
|
return resolve(String(stdout).trim());
|
|
});
|
|
});
|
|
}
|
|
|
|
};
|