-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
260 lines (228 loc) · 11 KB
/
index.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//initialize with the channel and the ari you pull from node-ari
module.exports = (channel, ari) => {
//the reader returns an async function for us to reuse
return async (props) => {
const {
soundFiles,
digitsInResponse = 0,
attempts = 3,
timeout = 10,
responseValidCallback = false,
debug = false
} = props;
//promise keeps the loop running until we finish it.
const value = await new Promise(async (resolve, reject) => {
//validate soundFiles
if(!Array.isArray(soundFiles)|| soundFiles.length<1){
reject('Must call with atleast one soundFiles');
}
//TODO validate further variables
let state = {
soundFileIndex: 0, //which file we are reading
dontPlayNextFile: false, //tell the reader to stop reading
isFinished: false, //read is finished
isPlaying: false, //we are in the middle of a read
playback: ari.Playback(), //playback channel
timeout: false, //idle timeout
playbackFinishedListener: false, //the function that runs when playback is done
};
const endCall = (rejectReason) => {
readIsFinished();
ari.removeListener('PlaybackFinished', runPlayFinishListener);
channel.removeListener('StasisEnd', handleHangupDuringRead);
channel.hangup();
reject(rejectReason);
};
const done = (returnVal = false) => {
readIsFinished();
ari.removeListener('PlaybackFinished', runPlayFinishListener);
channel.removeListener('StasisEnd', handleHangupDuringRead);
resolve(returnVal);
};
const hangupForTooManyAttempts = async () => {
//wait 1 seconds
await new Promise(res => setTimeout(() => res(), 100));
//after all the attempts we have no selection
const attemptLimitFinished = () => {
debug && console.log('running attemptLimitFinished');
endCall('attempt limit');
};
setPlayFinishListener(attemptLimitFinished);
channel.play({ media: 'sound:goodbye' }, state.playback, function (err) { });
};
/******************************
* IDLE HANDLER WHEN THEY STOP PAYING ATTENTION
*******************************/
const waitForInactivity = () => {
clearTimeout(state.timeout);
state.timeout = null;
state.timeout = setTimeout(
() => {
if (state.isFinished) return;
debug && console.log('Channel %s stopped paying attention...', text);
const timeoutReadLimit = () => {
//removeFinishListener();
endCall('timeout limit');
};
setPlayFinishListener(timeoutReadLimit);
channel.play({ media: 'sound:goodbye' }, state.playback, function (err) { });
}, (timeout || 10) * 1000
);
};
const disableInactivity = () => {
clearTimeout(state.timeout);
state.timeout = null;
};
//if hangup happens during the read function.
const handleHangupDuringRead = (event, incoming) => {
//if this has already
if (!state.isFinished) {
state.isPlaying = false;
ari.removeListener('PlaybackFinished', runPlayFinishListener);
readIsFinished();
}
};
channel.on('StasisEnd', handleHangupDuringRead);
//each time a file playback completes it needs to call this function to do the next actin.
const setPlayFinishListener = (listener) => {
state.playbackFinishedListener = listener;
};
const runPlayFinishListener = () => {
if (state.playbackFinishedListener !== false) {
state.playbackFinishedListener();
}
};
state.playback.on('PlaybackFinished', runPlayFinishListener);
//read is completed
const readIsFinished = () => {
state.isFinished = true;
//stop the timer
disableInactivity();
//stop the playback from looping
state.dontPlayNextFile = true;
if (state.playback && state.isPlaying) {
state.playback.stop({ playbackId: state.playback.id }, function (err) {
//ignore the error
state.isPlaying = false;
});
}
};
/**************************************************
* PLAY FILES FROM BEGINNING TO END
*************************************************/
const playNextFile = () => {
if (state.dontPlayNextFile) return;
//get filename, remove the extension as asterisk doesnt need that.
const filename_no_ext = soundFiles[state.soundFileIndex] && soundFiles[state.soundFileIndex].split('.').length > 1 ?
soundFiles[state.soundFileIndex].split('.').slice(0, -1).join('.') :
soundFiles[state.soundFileIndex];
state.soundFileIndex++;
const playComplete = async () => {
if (!state.isFinished) {
state.isPlaying = false;
//LAST FILE
if (state.soundFileIndex >= soundFiles.length) {
if (digitsInResponse == 0) {
done();
}
else {
state.dontPlayNextFile = true;
waitForInactivity();
}
}
//GO TO NEXT FILE
else {
await new Promise(res => setTimeout(() => res(), 20));
playNextFile();
}
}
};
setPlayFinishListener(playComplete);
channel.play({ media: `sound:${filename_no_ext}` }, state.playback, function (err) {/*ignore errors*/ });
state.isPlaying = true;
};
/******************************************
* GET A SPECIFIC NUMBER OF DIGITS
***************************************/
const waitForNDigits = async (numDigits) => {
let selection = await new Promise((resolveSelection) => {
const digitsPressed = [];
const digitHandler = (event, channel) => {
// special for '#' response
if (event.digit === '#') {
readIsFinished();
channel.removeListener('ChannelDtmfReceived', digitHandler);
return resolveSelection('#');
}
//ADD TO LIST OF DIGIS
digitsPressed.push(event.digit);
waitForInactivity();
//IF WE HAVE ENOUGH DIGITS
if (digitsPressed.length >= numDigits) {
const numSelected = digitsPressed.join('');
readIsFinished();
channel.removeListener('ChannelDtmfReceived', digitHandler);
return resolveSelection(numSelected);
}
};
channel.on('ChannelDtmfReceived', digitHandler);
});
return selection;
};
/*****************************************************************************
* GET A SPECIFIC NUMBER OF VALID DIGITS BY THE ATTEMPT LIMIT
******************************************************************************/
const getDigitsToRespond = async (attempts, digitsInResponse) => {
let attemptCount = 0;
let digitsToReturn = false;
let ret = await new Promise(async (resolveSelection, rejectSelection) => {
while (attemptCount <= attempts && digitsToReturn === false) {
//start playing files
playNextFile();
//listen for the selection.
let selection = await waitForNDigits(digitsInResponse);
//no valid checker
if (typeof responseValidCallback !== 'function') return resolveSelection(selection);
//check the selection is valid.
if (responseValidCallback(selection)) return resolveSelection(selection);
//too many tries, return false
if (attemptCount++ > attempts) return resolveSelection(false);
//lets try again.
debug && console.log(`attempt ${attemptCount} of ${attempts} hit ...`);
//wait 0.1 seconds so the other file finishes.
await new Promise(res => setTimeout(() => res(), 100));
//move the read index to the beginning
state.soundFileIndex = 0;
//reset the finished flags
state.dontPlayNextFile = false;
state.isFinished = false;
//the first thing to read is "this option is invalid"
if (soundFiles[0] != 'option-is-invalid') {
soundFiles.unshift('option-is-invalid');
}
//now it will start playing again at top of while loop
}
return resolveSelection(false);
});
return ret;
};
/**************************
* ACTUAL READ
**************************/
if (digitsInResponse > 0) {
let digitsToReturn = await getDigitsToRespond(attempts, digitsInResponse);
if (digitsToReturn === false) {
await hangupForTooManyAttempts();
}
else {
done(digitsToReturn);
}
}
else {
playNextFile();
}
});
//now once the promise resolves we return it.
return value;
};
};