Commit 6962e9c5 authored by sergey's avatar sergey

используем линтер для красоты кода ))

parent 508c005f
{
"extends": [
"google"
],
"env": {
"node": true
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
"new-cap": ["error", { "properties": true }]
}
}
\ No newline at end of file
language: node_js language: node_js
node_js: node_js:
- "7"
- "8" - "8"
- "10" - "10"
\ No newline at end of file - "11"
- "12"
\ No newline at end of file
module.exports = function(grunt){
grunt.initConfig({
mocha_istanbul: {
coverage: {
src: 'test',
options: {
'ui': 'tdd',
'recursive': true,
'reporter': 'mocha-istanbul'
}
}
}
});
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.registerTask('coverage', ['mocha_istanbul:coverage']);
};
\ No newline at end of file
var AGIServer = require('./../lib/index'); const AGIServer = require('./../lib/index');
var handler = function (context) { const handler = function(context) {
context.onEvent('variables') context.onEvent('variables')
.then(function (vars) { .then(function(vars) {
console.log('vars', vars); console.log('vars', vars);
return context.streamFile('beep'); return context.streamFile('beep');
}) })
.then(function (result) { .then(function(result) {
return context.setVariable('RECOGNITION_RESULT', 'I\'m your father, Luc'); return context.setVariable(
}) 'RECOGNITION_RESULT', 'I\'m your father, Luc');
.then(function (result) { })
return context.end(); .then(function(result) {
}) return context.end();
.fail(console.log); })
.fail(console.log);
}; };
var agi = new AGIServer(handler, {debug: true}); const agi = new AGIServer(handler, {debug: true});
agi.start(3007); agi.start(3007);
\ No newline at end of file
This diff is collapsed.
var commands = require('./command');
console.log(commands);
var q = {};
commands.map(function (command) {
q[command.name] = function () {
var args = [].slice.call(arguments, 0, command.params);
return command.command + " " + args.join(" ");
};
});
console.log(q.databaseDel("1", "2", "3", "4"));
console.log(q.databaseDelTree("1", "2", "3", "4"));
console.log(commands.length)
\ No newline at end of file
var Readable = require('readable-stream'); const Readable = require('readable-stream');
var EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
var state = require('./state'); const state = require('./state');
var commands = require('./command'); const commands = require('./command');
//base context // base context
var Context = function (stream, loggerOptions = {}) { const Context = function(stream, loggerOptions = {}) {
EventEmitter.call(this); EventEmitter.call(this);
function consoleDecorator(arrow, data){ const consoleDecorator = function(arrow, data) {
return console.log(arrow, JSON.stringify (data)); return console.log(arrow, JSON.stringify(data));
} };
this.log = (loggerOptions.logger) ? this.log = (loggerOptions.logger) ?
loggerOptions.logger : loggerOptions.logger :
consoleDecorator; consoleDecorator;
this.debug = loggerOptions.debug this.debug = loggerOptions.debug;
this.stream = new Readable(); this.stream = new Readable();
this.stream.setEncoding('utf8'); this.stream.setEncoding('utf8');
this.stream.wrap(stream); this.stream.wrap(stream);
this.state = state.init; this.state = state.init;
this.msg = ""; this.msg = '';
this.variables = {}; this.variables = {};
this.pending = null; this.pending = null;
var self = this; const self = this;
this.stream.on('readable', function () { this.stream.on('readable', function() {
//always keep the 'leftover' part of the message // always keep the 'leftover' part of the message
self.msg = self.read(); self.msg = self.read();
}); });
this.stream.on('error', this.emit.bind(this, 'error')); this.stream.on('error', this.emit.bind(this, 'error'));
this.stream.on('close', this.emit.bind(this, 'close')); this.stream.on('close', this.emit.bind(this, 'close'));
}; };
require('util').inherits(Context, EventEmitter); require('util').inherits(Context, EventEmitter);
Context.prototype.read = function () { Context.prototype.read = function() {
var buffer = this.stream.read(); const buffer = this.stream.read();
if (!buffer) return this.msg; if (!buffer) return this.msg;
this.msg += buffer; this.msg += buffer;
if (this.state === state.init) { if (this.state === state.init) {
if (this.msg.indexOf('\n\n') < 0) return this.msg; //we don't have whole message // we don't have whole message
if (this.msg.indexOf('\n\n') < 0) return this.msg;
this.readVariables(this.msg); this.readVariables(this.msg);
} else if (this.state === state.waiting) { } else if (this.state === state.waiting) {
if (this.msg.indexOf('\n') < 0) return this.msg; //we don't have whole message // we don't have whole message
if (this.msg.indexOf('\n') < 0) return this.msg;
this.readResponse(this.msg); this.readResponse(this.msg);
} }
return ''; return '';
}; };
Context.prototype.readVariables = function (msg) { Context.prototype.readVariables = function(msg) {
var lines = msg.split('\n'); const lines = msg.split('\n');
lines.map(function (line) { lines.map(function(line) {
var split = line.split(':'); const split = line.split(':');
var name = split[0]; const name = split[0];
var value = split[1]; const value = split[1];
this.variables[name] = (value || '').trim(); this.variables[name] = (value || '').trim();
}, this); }, this);
...@@ -69,26 +71,26 @@ Context.prototype.readVariables = function (msg) { ...@@ -69,26 +71,26 @@ Context.prototype.readVariables = function (msg) {
this.setState(state.waiting); this.setState(state.waiting);
}; };
Context.prototype.readResponse = function (msg) { Context.prototype.readResponse = function(msg) {
var lines = msg.split('\n'); const lines = msg.split('\n');
lines.map(function (line) { lines.map(function(line) {
this.readResponseLine(line); this.readResponseLine(line);
}, this); }, this);
}; };
Context.prototype.readResponseLine = function (line) { Context.prototype.readResponseLine = function(line) {
if (!line) return; if (!line) return;
//var parsed = /^(\d{3})(?: result=)(.*)/.exec(line); // var parsed = /^(\d{3})(?: result=)(.*)/.exec(line);
var parsed = /^(\d{3})(?: result=)([^(]*)(?:\((.*)\))?/.exec(line); const parsed = /^(\d{3})(?: result=)([^(]*)(?:\((.*)\))?/.exec(line);
if (!parsed) { if (!parsed) {
return this.emit('hangup'); return this.emit('hangup');
} }
var response = { const response = {
code: parseInt(parsed[1]), code: parseInt(parsed[1]),
result: parsed[2].trim(), result: parsed[2].trim(),
}; };
...@@ -96,63 +98,62 @@ Context.prototype.readResponseLine = function (line) { ...@@ -96,63 +98,62 @@ Context.prototype.readResponseLine = function (line) {
response.value = parsed[3]; response.value = parsed[3];
} }
//our last command had a pending callback // our last command had a pending callback
if (this.pending) { if (this.pending) {
var pending = this.pending; const pending = this.pending;
this.pending = null; this.pending = null;
pending(null, response); pending(null, response);
} }
this.emit('response', response); this.emit('response', response);
} };
Context.prototype.setState = function (state) { Context.prototype.setState = function(state) {
this.state = state; this.state = state;
}; };
Context.prototype.send = function (msg, cb) { Context.prototype.send = function(msg, cb) {
this.pending = cb; this.pending = cb;
this.stream.write(msg); this.stream.write(msg);
}; };
Context.prototype.end = function () { Context.prototype.end = function() {
this.stream.end(); this.stream.end();
return Promise.resolve(); return Promise.resolve();
}; };
Context.prototype.sendCommand = function (command) { Context.prototype.sendCommand = function(command) {
if (this.debug) this.log('------->', { command: command }); if (this.debug) this.log('------->', {command: command});
var self = this; const self = this;
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
self.send(command + '\n', function (err, result) { self.send(command + '\n', function(err, result) {
if (self.debug) self.log('<-------', { err: err, result: result }); if (self.debug) self.log('<-------', {err: err, result: result});
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
resolve(result); resolve(result);
} }
}); });
}) });
}; };
Context.prototype.onEvent = function (event) { Context.prototype.onEvent = function(event) {
var self = this const self = this;
return new Promise(function (resolve) { return new Promise(function(resolve) {
self.on(event, function (data) { self.on(event, function(data) {
resolve(data); resolve(data);
}) });
}) });
}; };
//additional agi commands // additional agi commands
commands.forEach(function (command) { commands.forEach(function(command) {
var str = ''; let str = '';
Context.prototype[command.name] = function () { Context.prototype[command.name] = function(...args) {
if (command.params > 0) { if (command.params > 0) {
var args = [].slice.call(arguments, 0, command.params); // const args = [].slice.call(arguments, 0, command.params);
str = command.command + " " + prepareArgs(args, command.paramRules, command.params).join(" "); str = command.command + ' ' +
prepareArgs(args, command.paramRules, command.params).join(' ');
} else { } else {
str = command.command; str = command.command;
} }
...@@ -160,22 +161,28 @@ commands.forEach(function (command) { ...@@ -160,22 +161,28 @@ commands.forEach(function (command) {
}; };
}); });
var prepareArgs = function (args, argsRules, count) { const prepareArgs = function(args, argsRules, count) {
if (!argsRules || !count) { if (!argsRules || !count) {
return args; return args;
} }
return Array.apply(null, new Array(count)) // old node.js versions don't support Array.fill() return (new Array(count)).fill(null)
.map(function (arg, i) { .map(function(arg, i) {
arg = args[i] !== undefined && args[i] !== null ? args[i] : argsRules[i] && argsRules[i].default || ''; arg = args[i] !== undefined && args[i] !== null ?
var prepare = argsRules[i] && argsRules[i].prepare || function (x) { return x; }; args[i] :
return prepare(String(arg)); argsRules[i] && argsRules[i].default || '';
}); const prepare = argsRules[i] && argsRules[i].prepare ||
function(x) {
return x;
};
return prepare(String(arg));
});
}; };
//sugar commands // sugar commands
Context.prototype.dial = function (target, timeout, params) { Context.prototype.dial = function(target, timeout, params) {
return this.exec('Dial', target + ',' + timeout + ',' + params); return this.exec('Dial', target + ',' + timeout + ',' + params);
}; };
......
var Context = require('./context'); const Context = require('./context');
var agi = function (handler, optionsIn) { const agi = function(handler, optionsIn) {
const options = optionsIn || {};
var server;
var options = optionsIn || {};
var settings = { const settings = {
port: options.port || 3000, port: options.port || 3000,
debug: options.debug || false, debug: options.debug || false,
logger: options.logger || false, logger: options.logger || false,
host: options.host, host: options.host,
}; };
var handle = function (stream) { const handle = function(stream) {
var context = new Context(stream, { debug: settings.debug, logger: options.logger}); const context = new Context(stream, {
debug: settings.debug,
logger: options.logger,
});
handler(context); handler(context);
}; };
var start = function (portIn, hostIn) { const start = function(portIn, hostIn) {
var port = portIn || settings.port; const port = portIn || settings.port;
var host = hostIn || settings.host; const host = hostIn || settings.host;
return require('net').createServer(handle).listen(port, host); return require('net').createServer(handle).listen(port, host);
}; };
return { return {
start: start start: start,
}; };
}; };
......
//states for context // states for context
var state = { const state = {
init: 0, init: 0,
waiting: 2 waiting: 2,
}; };
module.exports = state; module.exports = state;
...@@ -9,21 +9,17 @@ ...@@ -9,21 +9,17 @@
}, },
"main": "lib/", "main": "lib/",
"scripts": { "scripts": {
"test": "mocha -R tap --exit" "test": "mocha -R tap --exit",
}, "lint-fix": "eslint --fix ."
"engines": {
"node": ">=6"
}, },
"dependencies": { "dependencies": {
"expect.js": "^0.3.1",
"readable-stream": "^2.3.0" "readable-stream": "^2.3.0"
}, },
"devDependencies": { "devDependencies": {
"expect.js": "*", "eslint": "^5.16.0",
"grunt": "^0.4.5", "eslint-config-google": "^0.12.0",
"grunt-mocha-istanbul": "^2.2.0",
"istanbul": "^0.3.5",
"memorystream": "^0.3.0", "memorystream": "^0.3.0",
"mocha": "*", "mocha": "6.1.4"
"mocha-istanbul": "^0.2.0"
} }
} }
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment