2* @description MeshCentral SMS gateway communication module
3* @author Ylian Saint-Hilaire
4* @copyright Intel Corporation 2018-2022
10/*xjslint plusplus: true */
11/*xjslint maxlen: 256 */
13/*jshint strict: false */
14/*jshint esversion: 6 */
18// For Twilio, add this in config.json
23 "from": "+15555555555"
26// For Plivo, add this in config.json
34// For Telnyx, add this in config.json
41// For URL, add this in config.json
44 "url": "https://sample.com/?phone={{phone}}&msg={{message}}"
48// Construct a SMS server object
49module.exports.CreateMeshSMS = function (parent) {
54 // SMS gateway provider setup
55 switch (parent.config.sms.provider) {
57 // Validate Twilio configuration values
58 if (typeof parent.config.sms.sid != 'string') { console.log('Invalid or missing SMS gateway provider sid.'); return null; }
59 if (typeof parent.config.sms.auth != 'string') { console.log('Invalid or missing SMS gateway provider auth.'); return null; }
60 if (typeof parent.config.sms.from != 'string') { console.log('Invalid or missing SMS gateway provider from.'); return null; }
63 var Twilio = require('twilio');
64 obj.provider = new Twilio(parent.config.sms.sid, parent.config.sms.auth);
68 // Validate Plivo configuration values
69 if (typeof parent.config.sms.id != 'string') { console.log('Invalid or missing SMS gateway provider id.'); return null; }
70 if (typeof parent.config.sms.token != 'string') { console.log('Invalid or missing SMS gateway provider token.'); return null; }
71 if (typeof parent.config.sms.from != 'string') { console.log('Invalid or missing SMS gateway provider from.'); return null; }
74 var plivo = require('plivo');
75 obj.provider = new plivo.Client(parent.config.sms.id, parent.config.sms.token);
79 // Validate Telnyx configuration values
80 if (typeof parent.config.sms.apikey != 'string') { console.log('Invalid or missing SMS gateway provider apikey.'); return null; }
81 if (typeof parent.config.sms.from != 'string') { console.log('Invalid or missing SMS gateway provider from.'); return null; }
84 obj.provider = require('telnyx')(parent.config.sms.apikey);
88 // Validate URL configuration values
89 if (parent.config.sms.url != 'console') {
90 if (typeof parent.config.sms.url != 'string') { console.log('Invalid or missing SMS gateway URL value.'); return null; }
91 if (!parent.config.sms.url.toLowerCase().startsWith('http://') && !parent.config.sms.url.toLowerCase().startsWith('https://')) { console.log('Invalid or missing SMS gateway, URL must start with http:// or https://.'); return null; }
92 if (parent.config.sms.url.indexOf('{{message}}') == -1) { console.log('Invalid or missing SMS gateway, URL must include {{message}}.'); return null; }
93 if (parent.config.sms.url.indexOf('{{phone}}') == -1) { console.log('Invalid or missing SMS gateway, URL must include {{phone}}.'); return null; }
98 // Unknown SMS gateway provider
99 console.log('Unknown SMS gateway provider: ' + parent.config.sms.provider);
104 // Send an SMS message
105 obj.sendSMS = function (to, msg, func) {
106 parent.debug('email', 'Sending SMS to: ' + to + ': ' + msg);
107 if (parent.config.sms.provider == 'twilio') { // Twilio
108 obj.provider.messages.create({
109 from: parent.config.sms.from,
112 }, function (err, result) {
113 if (err != null) { parent.debug('email', 'SMS error: ' + err.message); } else { parent.debug('email', 'SMS result: ' + JSON.stringify(result)); }
114 if (func != null) { func((err == null) && (result.status == 'queued'), err ? err.message : null, result); }
116 } else if (parent.config.sms.provider == 'plivo') { // Plivo
117 if (to.split('-').join('').split(' ').join('').split('+').join('').length == 10) { to = '1' + to; } // If we only have 10 digits, add a 1 in front.
118 obj.provider.messages.create(
119 parent.config.sms.from,
122 ).then(function (result) {
123 parent.debug('email', 'SMS result: ' + JSON.stringify(result));
124 if (func != null) { func((result != null) && (result.messageUuid != null), null, result); }
126 ).catch(function (err) {
128 if ((err != null) && err.message) { msg = JSON.parse(err.message).error; }
129 parent.debug('email', 'SMS error: ' + msg);
130 if (func != null) { func(false, msg, null); }
133 } else if (parent.config.sms.provider == 'telnyx') { // Telnyx
134 obj.provider.messages.create({
135 from: parent.config.sms.from,
138 }, function (err, result) {
139 if (err != null) { parent.debug('email', 'SMS error: ' + err.type); } else { parent.debug('email', 'SMS result: ' + JSON.stringify(result)); }
140 if (func != null) { func((err == null), err ? err.type : null, result); }
142 } else if (parent.config.sms.provider == 'url') { // URL
143 if (parent.config.sms.url == 'console') {
144 // This is for debugging, just display the SMS to the console
145 console.log('SMS (' + to + '): ' + msg);
146 if (func != null) { func(true, null, null); }
148 var sms = parent.config.sms.url.split('{{phone}}').join(encodeURIComponent(to)).split('{{message}}').join(encodeURIComponent(msg));
149 parent.debug('email', 'SMS URL: ' + sms);
150 sms = require('url').parse(sms);
151 if (sms.protocol == 'https:') {
153 const options = { hostname: sms.hostname, port: sms.port ? sms.port : 443, path: sms.path, method: 'GET', rejectUnauthorized: false };
154 const request = require('https').request(options, function (res) { parent.debug('email', 'SMS result: ' + res.statusCode); if (func != null) { func(res.statusCode == 200, (res.statusCode == 200) ? null : res.statusCode, null); } res.on('data', function (d) { }); });
155 request.on('error', function (err) { parent.debug('email', 'SMS error: ' + err); if (func != null) { func(false, err, null); } });
159 const options = { hostname: sms.hostname, port: sms.port ? sms.port : 80, path: sms.path, method: 'GET' };
160 const request = require('http').request(options, function (res) { parent.debug('email', 'SMS result: ' + res.statusCode); if (func != null) { func(res.statusCode == 200, (res.statusCode == 200) ? null : res.statusCode, null); } res.on('data', function (d) { }); });
161 request.on('error', function (err) { parent.debug('email', 'SMS error: ' + err); if (func != null) { func(false, err, null); } });
168 // Get the correct SMS template
169 function getTemplate(templateNumber, domain, lang) {
170 parent.debug('email', 'Getting SMS template #' + templateNumber + ', lang: ' + lang);
171 if (Array.isArray(lang)) { lang = lang[0]; } // TODO: For now, we only use the first language given.
172 if (lang != null) { lang = lang.split('-')[0]; } // Take the first part of the language, "xx-xx"
174 var r = {}, emailsPath = null;
175 if ((domain != null) && (domain.webemailspath != null)) { emailsPath = domain.webemailspath; }
176 else if (obj.parent.webEmailsOverridePath != null) { emailsPath = obj.parent.webEmailsOverridePath; }
177 else if (obj.parent.webEmailsPath != null) { emailsPath = obj.parent.webEmailsPath; }
178 if ((emailsPath == null) || (obj.parent.fs.existsSync(emailsPath) == false)) { return null }
180 // Get the non-english email if needed
182 if ((lang != null) && (lang != 'en')) {
183 var translationsPath = obj.parent.path.join(emailsPath, 'translations');
184 var translationsPathTxt = obj.parent.path.join(emailsPath, 'translations', 'sms-messages_' + lang + '.txt');
185 if (obj.parent.fs.existsSync(translationsPath) && obj.parent.fs.existsSync(translationsPathTxt)) {
186 txtfile = obj.parent.fs.readFileSync(translationsPathTxt).toString();
190 // Get the english email
191 if (txtfile == null) {
192 var pathTxt = obj.parent.path.join(emailsPath, 'sms-messages.txt');
193 if (obj.parent.fs.existsSync(pathTxt)) {
194 txtfile = obj.parent.fs.readFileSync(pathTxt).toString();
198 // If no english sms and a non-english language is requested, try to get the default translated sms
199 if (txtfile == null && (lang != null) && (lang != 'en')) {
200 var translationsPath = obj.parent.path.join(obj.parent.webEmailsPath, 'translations');
201 var translationsPathTxt = obj.parent.path.join(obj.parent.webEmailsPath, 'translations', 'sms-messages_' + lang + '.txt');
202 if (obj.parent.fs.existsSync(translationsPath) && obj.parent.fs.existsSync(translationsPathTxt)) {
203 txtfile = obj.parent.fs.readFileSync(translationsPathTxt).toString();
207 // If no default translated sms, try to get the default english sms
208 if (txtfile == null) {
209 var pathTxt = obj.parent.path.join(obj.parent.webEmailsPath, 'sms-messages.txt');
210 if (obj.parent.fs.existsSync(pathTxt)) {
211 txtfile = obj.parent.fs.readFileSync(pathTxt).toString();
215 // No email templates
216 if (txtfile == null) { return null; }
218 // Decode the TXT file
219 var lines = txtfile.split('\r\n').join('\n').split('\n')
220 if (lines.length <= templateNumber) return null;
222 return lines[templateNumber];
225 // Send phone number verification SMS
226 obj.sendPhoneCheck = function (domain, phoneNumber, verificationCode, language, func) {
227 parent.debug('email', "Sending verification SMS to " + phoneNumber);
229 var sms = getTemplate(0, domain, language);
230 if (sms == null) { parent.debug('email', "Error: Failed to get SMS template"); return; } // No SMS template found
232 // Setup the template
233 sms = sms.split('[[0]]').join(domain.title ? domain.title : 'MeshCentral');
234 sms = sms.split('[[1]]').join(verificationCode);
237 obj.sendSMS(phoneNumber, sms, func);
240 // Send phone number verification SMS
241 obj.sendToken = function (domain, phoneNumber, verificationCode, language, func) {
242 parent.debug('email', "Sending login token SMS to " + phoneNumber);
244 var sms = getTemplate(1, domain, language);
245 if (sms == null) { parent.debug('email', "Error: Failed to get SMS template"); return; } // No SMS template found
247 // Setup the template
248 sms = sms.split('[[0]]').join(domain.title ? domain.title : 'MeshCentral');
249 sms = sms.split('[[1]]').join(verificationCode);
252 obj.sendSMS(phoneNumber, sms, func);