-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (72 loc) · 2.56 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
import { CallsApi, Configuration, Bxml } from 'bandwidth-sdk';
import express from 'express';
const BW_ACCOUNT_ID = process.env.BW_ACCOUNT_ID;
const BW_VOICE_APPLICATION_ID = process.env.BW_VOICE_APPLICATION_ID;
const BW_NUMBER = process.env.BW_NUMBER;
const BW_USERNAME = process.env.BW_USERNAME;
const BW_PASSWORD = process.env.BW_PASSWORD;
const LOCAL_PORT = process.env.LOCAL_PORT;
const BASE_CALLBACK_URL = process.env.BASE_CALLBACK_URL;
if([
BW_ACCOUNT_ID,
BW_VOICE_APPLICATION_ID,
BW_NUMBER,
BW_USERNAME,
BW_PASSWORD,
LOCAL_PORT,
BASE_CALLBACK_URL
].some(item => item === undefined)) {
throw new Error('Please set the environment variables defined in the README');
}
const config = new Configuration({
username: BW_USERNAME,
password: BW_PASSWORD
});
const app = express();
app.use(express.json());
const activeCalls = new Set();
app.post('/callbacks/inboundCall', async (req, res) => {
const callback = req.body;
if (callback.eventType === 'initiate') { activeCalls.add(callback.callId); }
const response = new Bxml.Response();
if (callback.eventType === 'initiate' || callback.eventType === 'redirect') {
const speakSentence = new Bxml.SpeakSentence('Hello, this call will be updated in 10 seconds.');
const ring = new Bxml.Ring({ duration: 30 });
const redirect = new Bxml.Redirect({ redirectUrl: '/callbacks/inboundCall' });
response.addVerbs([speakSentence, ring, redirect]);
}
res.status(200).send(response.toBxml());
});
app.post('/callbacks/callEnded', async (req, res) => {
const callback = req.body;
const response = new Bxml.Response();
if (callback.eventType === 'redirect') {
const speakSentence = new Bxml.SpeakSentence('The call has been ended. Goodbye');
response.addVerbs(speakSentence);
}
res.status(200).send(response.toBxml());
});
app.delete('/calls/:callId', async (req, res) => {
const callId = req.params.callId;
const callsApi = new CallsApi(config);
if (!activeCalls.has(callId)) {
res.sendStatus(404);
} else {
try {
const { status } = await callsApi.updateCall(
BW_ACCOUNT_ID,
callId,
{
redirectUrl: `${BASE_CALLBACK_URL}/callbacks/callEnded`
}
);
res.status(status).send();
} catch(e) {
res.status(500).send(e.message);
}
}
});
app.get('/calls', async (req, res) => {
res.status(200).send([...activeCalls]);
});
app.listen(LOCAL_PORT);