Coder Social home page Coder Social logo

asterisk-ami-client's Introduction

Asterisk AMI Client for NodeJS (ES2015)

Build Status Coverage Status Code Climate npm version

Full functionality client for Asterisk's AMI. Support any data packages (action/event/response/custom responses) from AMI; With this client you can select you'r own case of programming interactions with Asterisk AMI.

If you like events & handlers - you can use it!
If you like promises - you can use it!
If you like co & sync-style of code - you can use it!

  1. Install
  2. Usage
  3. More examples
  4. Docs & internal details
  5. Tests
  6. License

Install

$ npm i asterisk-ami-client

NodeJS versions

support >=4.0.0

Usage

It is only some usage cases.

Example 1:

Listening all events on instance of client;

const AmiClient = require('asterisk-ami-client');
let client = new AmiClient();

client.connect('user', 'secret', {host: 'localhost', port: 5038})
 .then(amiConnection => {

     client
         .on('connect', () => console.log('connect'))
         .on('event', event => console.log(event))
         .on('data', chunk => console.log(chunk))
         .on('response', response => console.log(response))
         .on('disconnect', () => console.log('disconnect'))
         .on('reconnection', () => console.log('reconnection'))
         .on('internalError', error => console.log(error))
         .action({
             Action: 'Ping'
         });

     setTimeout(() => {
         client.disconnect();
     }, 5000);

 })
 .catch(error => console.log(error));

Example 2:

Receive Asterisk's AMI responses with promise-chunk.

const AmiClient = require('asterisk-ami-client');
let client = new AmiClient({reconnect: true});

client.connect('username', 'secret', {host: '127.0.0.1', port: 5038})
    .then(() => { // any action after connection
        return client.action({Action: 'Ping'}, true);
    })
    .then(response1 => { // response of first action
        console.log(response1);
    })
    .then(() => { // any second action
        return client.action({Action: 'Ping'}, true);
    })
    .then(response2 => { // response of second action
        console.log(response2)
    })
    .catch(error => error)
    .then(error => {
        client.disconnect(); // disconnect
        if(error instanceof Error){ throw error; }
    });

or with co-library for sync-style of code

Example 3:

Receive Asterisk's AMI responses with co.

const AmiClient = require('asterisk-ami-client');
const co = require('co');

let client = new AmiClient({reconnect: true});

co(function* (){
    yield client.connect('username', 'secret', {host: '127.0.0.1', port: 5038});

    let response1 = yield client.action({Action: 'Ping'}, true);
    console.log(response1);

    let response2 = yield client.action({Action: 'Ping'}, true);
    console.log(response2);

    client.disconnect();
}).catch(error => console.log(error));

Example 4:

Listening event and response events on instance of client.

const AmiClient = require('asterisk-ami-client');

let client = new AmiClient({
    reconnect: true,
    keepAlive: true
});

client.connect('user', 'secret', {host: 'localhost', port: 5038})
    .then(() => {
        client
            .on('event', event => console.log(event))
            .on('response', response => {
                console.log(response);
                client.disconnect();
            })
            .on('internalError', error => console.log(error));

        client.action({Action: 'Ping'});
    })
    .catch(error => console.log(error));

Example 5:

Emit events by names and emit of response by resp_${ActionID} (if ActionID is set in action's data package).

const AmiClient = require('asterisk-ami-client');

let client = new AmiClient({
    reconnect: true,
    keepAlive: true,
    emitEventsByTypes: true,
    emitResponsesById: true
});

client.connect('user', 'secret', {host: 'localhost', port: 5038})
    .then(() => {
        client
            .on('Dial', event => console.log(event))
            .on('Hangup', event => console.log(event))
            .on('Hold', event => console.log(event))
            .on('Bridge', event => console.log(event))
            .on('resp_123', response => {
                console.log(response);
                client.disconnect();
            })
            .on('internalError', error => console.log(error));

        client.action({
            Action: 'Ping',
            ActionID: 123
        });
    })
    .catch(error => console.log(error));

More examples

For more examples, please, see ./examples/*.

Docs & internal details

Events

  • connect - emits when client was connected;
  • event - emits when was received a new event of Asterisk;
  • data - emits when was received a new chunk of data form the Asterisk's socket;
  • response - emits when was received a new response of Asterisk;
  • disconnect - emits when client was disconnected;
  • reconnection - emits when client tries reconnect to Asterisk;
  • internalError - emit when happens something very bad. Like a disconnection from Asterisk and etc;
  • ${eventName} - emits when was received event with name eventName of Asterisk and parameter emitEventsByTypes was set to true. See example 5;
  • ${resp_ActionID} - emits when was received response with ActionID of Asterisk and parameter emitResponsesById was set to true. See example 5.

Client's parameters

Default values:

{
    reconnect: false,
    maxAttemptsCount: 30,
    attemptsDelay: 1000,
    keepAlive: false,
    keepAliveDelay: 1000,
    emitEventsByTypes: true,
    eventTypeToLowerCase: false,
    emitResponsesById: true,
    dontDeleteSpecActionId: false,
    addTime: false,
    eventFilter: null  // filter disabled
}
  • reconnect - auto reconnection;
  • maxAttemptsCount - max count of attempts when client tries to reconnect to Asterisk;
  • attemptsDelay - delay (ms) between attempts of reconnection;
  • keepAlive - when is true, client send Action: Ping to Asterisk automatic every minute;
  • keepAliveDelay - delay (ms) between keep-alive actions, when parameter keepAlive was set to true;
  • emitEventsByTypes - when is true, client will emit events by names. See example 5;
  • eventTypeToLowerCase - when is true, client will emit events by names in lower case. Uses with emitEventsByTypes;
  • emitResponsesById - when is true and data package of action has ActionID field, client will emit responses by resp_ActionID. See example 5;
  • dontDeleteSpecActionId - when is true, client will not hide generated ActionID field in responses;
  • addTime - when is true, client will be add into events and responses field $time with value equal to ms-timestamp;
  • eventFilter - object, array or Set with names of events, which will be ignored by client.

Methods

  • .connect(username, secret[, options]) - connect to Asterisk. See examples;
  • .disconnect() - disconnect from Asterisk;
  • .action(message) - send new action to Asterisk;
  • .write(message) - alias of action method;
  • .send(message) - alias of action method;
  • .option(name[, value]) - get or set option of client;
  • .options([newOptions]) - get or set all options of client.

Properties

Getters

  • lastEvent - last event, which was receive from Asterisk;
  • lastResponse - last response which was receive from Asterisk;
  • isConnected - status of current connection to Asterisk;
  • lastAction - last action data which was transmitted to Asterisk;
  • connection - get current amiConnection.

Tests

Tests require Mocha.

mocha ./tests

or with npm

npm test 

Test coverage with Istanbul

npm run coverage

License

Licensed under the MIT License

asterisk-ami-client's People

Contributors

belirafon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

asterisk-ami-client's Issues

Feature Requests.

First off thanks for this project, very nice.

Is there a way that is could be modified to allow connnecting to multiple AMI's? and adding connection option like time that can be used to define the AMIHOST that the event is coming from?

disconnect event is emitted twice when calling .disconnect()

The "disconnect" event is emitted twice when you manually disconnect using AmiClient.disconnect() :

This could be avoided by removing the first one but then the event would never trigger if it was never connected. I think a better solution would be to add a if(!this._userDisconnect) before the second one

Have a nice day

Full example using async/await :)

Busy teaching myself Node.js and thought I'd do an example in async/await. Not sure if its perfect but it works ;)

const queueState = async () => {
    const actID = cuid();                                  //using the npmjs cuid module
    const eventResponse = [];
    await client.connect(AMIConfig.username, AMIConfig.secret, AMIConfig.server)
    const results = new Promise((resolve, reject) => {
        client
            .on('event', (data) => {
                if (data.ActionID == actID) {
                    eventResponse.push(data);
                }
                if (data.Event == 'QueueStatusComplete' && data.ActionID == actID) {
                    client.disconnect();
                    resolve(eventResponse)
                }
            })
            .on('response', (data) => {
                if (data.Response == 'Error') {
                    client.disconnect();
                    reject(data)
                }
            })
            .on('internalError', error => {
                client.disconnect();
                reject(error);
            });
    })
    await client.action({ Action: 'QueueStatus', queue: '8001', ActionID: actID }, true)
await results    
return results
}

Class extends value undefined is not a constructor or null using library in Angular 7

Hi,
I'm trying to use the library into my Angular 7 project.

I created a service like this:

import {Injectable} from '@angular/core';
const AmiClient = require('asterisk-ami-client');

@Injectable()
export class AsteriskPbxService {
  client = new AmiClient();

  constructor() {
  }

  start(){
    this.client.connect('manager', 'xxxxxxx', {host: 'localhost', port: 5038})
        .then(amiConnection => {

          this.client
              .on('connect', () => console.log('connect'))
              .on('event', event => console.log(event))
              .on('data', chunk => console.log(chunk))
              .on('response', response => console.log(response))
              .on('disconnect', () => console.log('disconnect'))
              .on('reconnection', () => console.log('reconnection'))
              .on('internalError', error => console.log(error))
              .action({
                Action: 'Ping'
              });

          setTimeout(() => {
            this.client.disconnect();
          }, 5000);

        })
        .catch(error => console.log(error));
  }

  
  destroy() {
  if(this.client){
     this.client.disconnect();
   }
  }
}

I added it to my providers. Unfortunately when the project starts I've this error:

AmiEventsStream.js:16 Uncaught TypeError: Class extends value undefined is not a constructor or null
    at Object../node_modules/asterisk-ami-events-stream/lib/AmiEventsStream.js (AmiEventsStream.js:16)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/asterisk-ami-connector/lib/AmiConnection.js (AmiConnection.js:10)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/asterisk-ami-connector/lib/index.js (index.js:11)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/asterisk-ami-client/lib/AmiClient.js (AmiClient.js:10)
    at __webpack_require__ (bootstrap:83)
    at Module../src/app/_service/pbx/asteriskPbx.service.ts (asteriskPbx.service.ts:2)
    at __webpack_require__ (bootstrap:83)

Am I doing something wrong? Do I need something to make the library work in Angular 7?
Thanks

response SIPshowpeer

{
Response: 'Success',
ActionID: 'c095b2c5-6145-41db-a21a-4e6e9e7e25f7',
Channeltype: 'SIP',
ObjectName: 'TRUNK',
ChanObjectType: 'peer',
SecretExist: 'Y',
RemoteSecretExist: 'N',
MD5SecretExist: 'N',
Context: 'default',
Language: 'pt_BR',
ToneZone: '',
AMAflags: 'Unknown',
'CID-CallingPres': 'Presentation Allowed, Not Screene
Callgroup: '',
Pickupgroup: '',
'$content': 'Named Callgroup: \r\nNamed Pickupgroup: \r\nMOHSuggest: \r\nVoiceMailbox: \r\nTransferMode: closed\r\nLastMsgsSent: 0\r\nMaxforwards: 0\r\nCall-limit: 0\r\nBusy-level: 0\r\nMaxCallBR: 384 kbps\r\nDynamic: N\r\nCallerid: "" <>\r\nRegExpire: -1 seconds\r\nSIP-AuthInsecure: port,invite\r\nSIP-Forcerport: Y\r\nSIP-Comedia: N\r\nACL: N\r\nSIP-CanReinvite: Y\r\nSIP-DirectMedia: Y\r\nSIP-PromiscRedir: N\r\nSIP-UserPhone: N\r\nSIP-VideoSupport: N\r\nSIP-TextSupport: N\r\nSIP-T.38Support: N\r\nSIP-T.38EC: Unknown\r\nSIP-T.38MaxDtgrm: 4294967295\r\nSIP-Sess-Timers: Accept\r\nSIP-Sess-Refresh: uas\r\nSIP-Sess-Expires: 1800\r\nSIP-Sess-Min: 90\r\nSIP-RTP-Engine: asterisk\r\nSIP-Encryption: N\r\nSIP-RTCP-Mux: N\r\nSIP-DTMFmode: rfc2833\r\nToHost: \r\nAddress-IP: \r\nAddress-Port: 5060\r\nDefault-addr-IP: (null)\r\nDefault-addr-port: 0\r\nDefault-Username: sigamesgt\r\nCodecs: (g729|alaw|ulaw|gsm|ilbc)\r\nStatus: UNREACHABLE\r\nSIP-Useragent: \r\nReg-Contact: \r\nQualifyFreq: 60000 ms\r\nParkinglot: \r\nSIP-Use-Reason-Header: N\r\nDescription: ' }

in the example above, should '$content' be a continuation of the object?

How I can send a param in the command

Hi I using the ami-client and I have an ask:
How I can send a param in the command for instance, I want to send the command 'QueueStatus 9494', where the 9494 is the queue, this is my code
client.action({ action: 'Command', actionID: '123', command : 'QueueStatus', },false);
Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.