forked from pipobscure/NodeJS-AsteriskManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasterisk.js
230 lines (218 loc) · 7.28 KB
/
asterisk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
* NodeJS Asterisk Manager API
* (Based on https://github.com/mscdex/node-asterisk.git)
* But radically altered thereafter so as to constitute a new work.
*
* © 2011 by Philipp Dunkel
*
*/
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var readline = (function() {
var module={ exports:{} };
(function (exports, module) {
// experimental function that adds supports for lines using streams
// only works if the stream is encoded with either 'ascii' or 'utf8'
// adds a writeln function which is a shorthand for write(str + "\n")
// adds a 'line' event to readable streams which buffers any data
// until it encounters EOL
var _stream_writeln = function writeln(str) {
this.write(str + '\r\n');
};
// this function is called when a listener for 'line' has been added
// to the stream. it is not nested in the setup function to prevent
// any unnecessary closured data
function _setupLines(stream) {
this.writeln = _stream_writeln;
// we buffer incoming data until a full line is buffered
// then the line event is emitted with the content of the
// line (without the newline character)
var line_buffer = '';
stream.on('data', function(data) {
if(typeof(data) != 'string') {
line_buffer = '';
return;
}
var split = data.split(/\r?\n/);
// if the chunk contains more than one line
// we make sure that all the lines are emitted in the right order
// and that the end of the chunk is buffered
var end = split.pop();
while(split.length) {
line_buffer += split.shift();
this.emit('line', line_buffer);
line_buffer = '';
}
line_buffer += end;
});
function endlistener () {
// when the stream reaches its end, emit the last bit of buffered data
// FIXME: find a way to make sure that these data are emitted
// before any other 'end' listeners are called
if(line_buffer != '') this.emit('line', line_buffer);
}
stream.on('end', endlistener);
}
module.exports = function lines(stream) {
// we can start consuming incoming data when at least
// one listener is set. note that 'data' can still be listened to.
// however, if lines() is called after data have started being consumed
// the first lines of the message will be missing.
stream.on('newListener', function(type, listener) {
if(type === 'line') {
_setupLines(this);
}
});
stream.writeln = _stream_writeln;
};
}).call(module.exports, module.exports, module);
return module.exports;
})();
function makeVars(vars) {
var items=[];
var item;
for (item in vars) {
if (vars.hasOwnProperty(item)) {
items.push([item,vars[item]].join('='));
}
}
return items.join(',');
};
var Manager = function(port, host) {
if (this.constructor !== Manager) return new Manager(port, host);
EventEmitter.call(this);
host = host || '127.0.0.1';
port = port || 5038;
var connection = null;
var commands = {};
var authenticated = false;
this.__defineGetter__('authenticated', function() { return authenticated; });
this.isConnected = function(){
return connection ? true : false;
};
var credentials = {};
this.connect = function(username, password, reconn) {
credentials.username = username || credentials.username;
credentials.password = password || credentials.password;
reconnect = reconn || reconnect;
var that = this;
if (!connection || (connection.readyState === 'closed')) {
console.log("Connecting to "+host+":"+port);
connection = net.createConnection(port, host);
connection.on('connect', function() { reconnectDelay=100; that.emit('connect'); });
connection.on('close', function() { reconnectDelay*=2; if (connection) connection.destroy(); connection=null; that.emit('close'); });
connection.on('end', function() { reconnectDelay*=2; if (connection) connection.destroy(); connection=null; that.emit('close'); });
connection.on('error', function(err) { reconnectDelay*=2; if (connection) connection.destroy(); connection=null; that.emit('error', err); that.emit('close'); });
connection.setEncoding('utf8');
readline(connection);
var lines=[];
connection.on('line', function(line) {
if (line.substr(0, 21) === "Asterisk Call Manager") return; // Ignore Hello
if (line.length) {
lines.push(line);
} else {
var item = {};
while (lines.length) {
line = lines.shift().split(/\s*:\s*/);
item[line.shift().toLowerCase()] = line.join(':');
}
if (item.response && item.actionid) {
if (commands[item.actionid]) {
line = commands[item.actionid];
commands[item.actionid] = undefined;
if ("function" === typeof line.callback) {
line.response = item;
if (item.response.toLowerCase() === "error") {
line.callback.call(that, new Error(item.message), line);
} else {
line.callback.call(that, undefined, line);
}
} else {
that.emit('response', item);
}
} else {
that.emit('response', item);
}
} else if (item.event) {
item.event = String(item.event).toLowerCase();
that.emit('managerevent', item);
that.emit(item.event, item);
}
}
});
}
};
var reconnect = false;
Object.defineProperty(this, 'reconnect', { value:reconnect, writable:true });
this.disconnect = function() {
reconnect = false;
if (connection && connection.readyState === 'open') {
connection.end();
}
};
this.action = function(request, callback) {
if (!connection) {
if ("function" === typeof callback) callback.call(this, new Error('Not Connected'), undefined);
return undefined;
}
var actionid = (new Date()).getTime();
if ("object" === typeof request.variable) {
request.variable = makeVars(request.variable);
}
commands[actionid] = { request: request, callback: callback};
var msg = [
[ 'actionid', actionid ].join(': ')
];
for (var key in request) {
if (request.hasOwnProperty(key)) {
msg.push([ key, request[key] ].join(': '));
}
}
msg.push('');
msg.push('');
return connection.write(msg.join("\r\n"), 'utf-8');
};
var reconnectDelay = 100;
this.authenticate = function(username, password, events, callback) {
if (!callback && ("function" === typeof events)) {
callback = events;
events = 'on';
}
events = events || 'on';
if (!connection || !connection.readyState==='open') {
if ("function" === typeof callback) callback.call(this, new Error("Not Connected"), undefined);
return;
}
if (this.authenticated) {
if ("function" === typeof callback) callback.call(this, new Error("Already Authenticated"), undefined);
return;
}
var that = this;
this.action({
action:'login',
username:username,
secret:password,
events:events
}, function(err, val) {
if (err || !val) {
that.emit('error', err);
} else {
that.emit('authenticate', val);
}
if ("function" === typeof callback) callback.call(that, err, val);
});
};
this.on('close', function() {
if (reconnect) {
var that = this;
setTimeout(function() {
that.connect();
}, reconnectDelay);
}
});
this.on('connect', function() {
if (credentials.username) this.authenticate(credentials.username, credentials.password);
});
};
require('util').inherits(Manager, EventEmitter);
module.exports = Manager;