tami
Version:
Typescript client for asterisk's AMI
76 lines (75 loc) • 2.54 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ami = void 0;
const events_1 = require("events");
const Connection_1 = require("./Connection");
const Login_1 = require("./actions/Login");
const Ping_1 = require("./actions/Ping");
const Parser_1 = require("./Parser");
class Ami extends events_1.EventEmitter {
constructor(authOpts, host, port) {
super();
this.user = authOpts.user;
this.secret = authOpts.secret;
this.conn = new Connection_1.Connection(host, port);
this.functions = {};
this.conn.on('data', this.handleData.bind(this));
}
connect() {
return new Promise((resolve) => {
this.conn.once('connected', resolve);
this.conn.on('disconnect', () => {
clearTimeout(this.keepAliveTimeoutRef);
});
this.conn.connect();
this.keepAlive();
this.sendAuth();
});
}
action(action) {
return new Promise((resolve, reject) => {
if (!action.ActionID) {
action.ActionID = (Math.random() * 1000).toString();
}
this.addResponseListener(action.ActionID, (response) => {
resolve(response);
});
const parsedAction = Parser_1.parseActionToString(action);
const isWriten = this.conn.write(parsedAction);
!isWriten && reject(new Error('action-not-sent'));
});
}
keepAlive() {
this.keepAliveTimeoutRef = setTimeout(() => {
const ping = new Ping_1.Ping();
this.conn.write(ping.getAction());
this.keepAlive();
}, 1000);
}
sendAuth() {
const login = new Login_1.Login(this.user, this.secret);
this.conn.write(login.getAction());
}
handleData(data) {
const response = Parser_1.parser(data);
if (!response.ActionID && !response.Event) {
return;
}
if (response.Event) {
this.emit('event', response);
return;
}
if (response.ActionID in this.listeners) {
this.functions[response.ActionID].forEach((func) => {
func(response);
});
delete this.functions[response.ActionID];
}
}
addResponseListener(actionId, callback) {
if (!this.functions[actionId])
this.functions[actionId] = [];
this.functions[actionId].push(callback);
}
}
exports.Ami = Ami;