forked from techinems/dialert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
215 lines (193 loc) · 5.83 KB
/
server.js
File metadata and controls
215 lines (193 loc) · 5.83 KB
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
//node packages
const cron = require("node-cron");
const nodemailer = require("nodemailer");
require("dotenv").config();
//globals
const FREEPBX_API_URL = process.env.FREEPBX_API_URL;
const FREEPBX_GQL_URL = process.env.FREEPBX_GQL_URL;
const FREEPBX_CLIENT_ID = process.env.FREEPBX_CLIENT_ID;
const FREEPBX_CLIENT_SECRET = process.env.FREEPBX_CLIENT_SECRET;
const FREEPBX_SCOPE = process.env.FREEPBX_SCOPE;
const RG1 = process.env.RG1;
const RG2 = process.env.RG2;
const RG3 = process.env.RG3;
const PBX_CID = process.env.PBX_CID;
const CRON_STRING = process.env.CRON_STRING;
const SCHEDULE_URL = process.env.SCHEDULE_URL;
const SCHEDULE_TOKEN = process.env.SCHEDULE_TOKEN;
const TZ = process.env.TZ;
const ERROR_EMAIL_ADDRESS = process.env.ERROR_EMAIL_ADDRESS;
const SMTP_SERVER = process.env.SMTP_SERVER;
const SMTP_PORT = process.env.SMTP_PORT;
const SMTP_USER = process.env.SMTP_USER;
const SMTP_PASS = process.env.SMTP_PASS;
const ringgroups = [RG1, RG2, RG3];
let currentRecipients = {};
let hash;
//oauth config
const config = {
client: {
id: FREEPBX_CLIENT_ID,
secret: FREEPBX_CLIENT_SECRET,
},
auth: {
tokenHost: FREEPBX_API_URL,
tokenPath: "token"
},
http: {
json: "strict",
redirects: true
}
};
const { ClientCredentials } = require("simple-oauth2");
const client = new ClientCredentials(config);
const tokenParams = {
scope: FREEPBX_SCOPE.split(" "),
};
//mailer config
const transporter = nodemailer.createTransport({
host: SMTP_SERVER,
port: SMTP_PORT,
secure: SMTP_PORT == 465, // Use true for port 465, false for port 587
auth: {
user: SMTP_USER,
pass: SMTP_PASS,
},
});
//helper functions
const handleError = async (msg) => {
const info = await transporter.sendMail({
from: '"DiALERT Error" <noreply@wemsapp.com>',
to: ERROR_EMAIL_ADDRESS,
subject: "DiALERT Error Notification",
text: `An error occurred: ${msg}\n\n\nCurrent time: ${new Date().toString()}`,
html: `<b>An error occurred:</b> ${msg}\n<br/><br/><b>Current time:</b> ${new Date().toString()}`,
});
console.error("Error email sent: ", msg);
return console.error("Message ID: ", info.messageId);
}
const getCurrentSchedule = async () => {
const res = await fetch(SCHEDULE_URL, {
method: "GET",
headers: {
"x-api-key": SCHEDULE_TOKEN,
},
});
if (!res.ok) {
return handleError(`Failed to fetch schedule: ${res.status} ${res.statusText}\nSchedule URL: ${SCHEDULE_URL}`);
}
const body = await res.json();
if (body.error) {
console.error("Schedule API error: ", body.error);
return;
}
return {hash: body.hash, recipients: body.recipients};
}
const updatePbx = async (recipients) => {
let accessToken;
try {
accessToken = await client.getToken(tokenParams);
} catch (error) {
console.log("Access token error: ", error.message);
}
let statuses = [];
for (let x = 0; x < recipients.length; x++) {
console.log(`Updating ring group ${ringgroups[x]} with recipient ${recipients[x].number}...`);
const scheduledCount = recipients.length;
let ringTime;
let postAnswer = null;
if (scheduledCount === 2) {
if (x === 0) postAnswer = `ext-group,${ringgroups[1]},1`;
else if (x === 1) postAnswer = `app-blackhole,busy,1`;
} else if (scheduledCount === 3) {
if (x === 0) postAnswer = `ext-group,${ringgroups[1]},1`;
else if (x === 1) postAnswer = `ext-group,${ringgroups[2]},1`;
else if (x === 2) postAnswer = `app-blackhole,busy,1`;
}
switch (scheduledCount) {
case 1:
ringTime = 60;
postAnswer = `app-blackhole,busy,1`;
break;
case 2:
ringTime = 30;
if (x === 0) postAnswer = `ext-group,${ringgroups[1]},1`;
else if (x === 1) postAnswer = `app-blackhole,busy,1`;
break;
case 3:
ringTime = 30;
if (x === 0 || x === 1) postAnswer = `ext-group,${ringgroups[x+1]},1`;
else if (x === 2) postAnswer = `app-blackhole,busy,1`;
break;
}
console.debug(`ringTime for ringgroup ${ringgroups[x]}: ${ringTime}`);
console.debug(`postAnswer for ringgroup ${ringgroups[x]}: ${postAnswer}`);
const res = await fetch(FREEPBX_GQL_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${accessToken.token.access_token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
query: `mutation{
updateRingGroup(input:{
groupNumber: "${ringgroups[x]}"
description: "DiALERT Medcon ${x+1}"
extensionList: "${recipients[x].number}#"
strategy: "ringall"
ringTime: "${ringTime}"
${postAnswer ? `postAnswer: "${postAnswer}"` : ""}
changecid: "fixed"
fixedcid: "${PBX_CID}"
}) {
message status
}
}`
})
});
statuses.push(res.status);
}
console.log("Reloading PBX configuration...");
const reloadRes = await fetch(FREEPBX_GQL_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken.token.access_token}`
},
body: JSON.stringify({
query: `mutation{
doreload(input:{}) {
message
status
transaction_id
}
}`,
}),
});
return {
main: statuses,
reload: reloadRes.status,
};
};
const run = async () => {
const res = await getCurrentSchedule();
if (res.hash === hash) {
console.log(`No changes in schedule at ${new Date().toString()}...`);
return;
}
hash = res.hash;
console.log(`Schedule change detected at ${new Date().toString()}, updating PBX...`);
const updateRes = await updatePbx(res.recipients);
console.debug(`PBX update statuses: ${JSON.stringify(updateRes)}`);
};
//cron scheduling
cron.schedule(
CRON_STRING,
() => {
run();
},
{ timezone: TZ }
);
(async () => {
run();
})();