2019-03-27 07:48:13 +00:00
|
|
|
const soap = require('soap');
|
|
|
|
const xmlParser = require('xml2js').parseString;
|
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethodCtx('send', {
|
|
|
|
description: 'Sends SMS to a destination phone',
|
|
|
|
accepts: [{
|
2019-04-16 05:59:12 +00:00
|
|
|
arg: 'destinationFk',
|
2019-03-27 07:48:13 +00:00
|
|
|
type: 'Integer'
|
|
|
|
},
|
|
|
|
{
|
2019-04-16 05:59:12 +00:00
|
|
|
arg: 'destination',
|
2019-03-27 07:48:13 +00:00
|
|
|
type: 'String',
|
|
|
|
required: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
arg: 'message',
|
|
|
|
type: 'String',
|
|
|
|
required: true,
|
|
|
|
}],
|
|
|
|
returns: {
|
2019-04-16 05:59:12 +00:00
|
|
|
type: 'Object',
|
2019-03-27 07:48:13 +00:00
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/send`,
|
|
|
|
verb: 'POST'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2019-04-16 05:59:12 +00:00
|
|
|
Self.send = async(ctx, destinationFk, destination, message) => {
|
2019-03-27 07:48:13 +00:00
|
|
|
const userId = ctx.req.accessToken.userId;
|
|
|
|
const smsConfig = await Self.app.models.SmsConfig.findOne();
|
|
|
|
const soapClient = await soap.createClientAsync(smsConfig.uri);
|
|
|
|
const params = {
|
|
|
|
user: smsConfig.user,
|
|
|
|
pass: smsConfig.password,
|
|
|
|
src: smsConfig.title,
|
2019-04-16 05:59:12 +00:00
|
|
|
dst: destination,
|
2019-03-27 07:48:13 +00:00
|
|
|
msg: message
|
|
|
|
};
|
|
|
|
|
|
|
|
let xmlResponse;
|
|
|
|
let xmlResult;
|
|
|
|
let xmlParsed;
|
|
|
|
let status;
|
|
|
|
|
|
|
|
try {
|
|
|
|
[xmlResponse] = await soapClient.sendSMSAsync(params);
|
|
|
|
xmlResult = xmlResponse.result.$value;
|
|
|
|
xmlParsed = await new Promise((resolve, reject) => {
|
|
|
|
xmlParser(xmlResult, (err, result) => {
|
|
|
|
if (err)
|
|
|
|
reject(err);
|
|
|
|
resolve(result);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
[status] = xmlParsed['xtratelecom-sms-response'].sms;
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
}
|
|
|
|
|
2019-04-16 05:59:12 +00:00
|
|
|
const statusCode = status.codigo[0];
|
|
|
|
const statusDescription = status.descripcion[0];
|
|
|
|
|
2019-03-27 07:48:13 +00:00
|
|
|
const newSms = {
|
|
|
|
senderFk: userId,
|
2019-04-16 05:59:12 +00:00
|
|
|
destinationFk: destinationFk || null,
|
|
|
|
destination: destination,
|
2019-03-27 07:48:13 +00:00
|
|
|
message: message,
|
2019-04-16 05:59:12 +00:00
|
|
|
statusCode: statusCode,
|
|
|
|
status: statusDescription
|
2019-03-27 07:48:13 +00:00
|
|
|
};
|
|
|
|
|
2019-04-16 05:59:12 +00:00
|
|
|
const sms = await Self.create(newSms);
|
2019-03-27 07:48:13 +00:00
|
|
|
|
2019-04-16 05:59:12 +00:00
|
|
|
if (statusCode != 200)
|
2019-03-27 07:48:13 +00:00
|
|
|
throw new UserError(`We weren't able to send this SMS`);
|
|
|
|
|
|
|
|
return sms;
|
|
|
|
};
|
|
|
|
};
|