-
Notifications
You must be signed in to change notification settings - Fork 0
/
sms.js
90 lines (79 loc) · 2.77 KB
/
sms.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
const axios = require('axios')
const printer = require('./printer');
const text = require('./text');
const cli = require('./cli');
const logger = require('./logger');
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const args = cli.args;
const auth = {
auth: {
username: args.smsuser,
password: args.smspassword
}
}
async function pollForSMS() {
logger.trace(`Polling for new SMSs...`)
try {
const pollResponse = await axios.get(`${args.sms}/getSMS/PENDING`, auth)
if(pollResponse.status === 200) {
logger.trace(`Got ${pollResponse.data.length} messages to process`)
if(pollResponse.data.length === 0) {
//just keep it awake
//printer.keepAwake(args.devicename, args.timeout, 1000)
}
pollResponse.data.forEach(async (sms) => {
let success = false;
try {
const formattedSMS = formatSMSToPrint(sms, true)
logger.trace(`Printing: ${formattedSMS}`)
await printer.connect(args.devicename, args.timeout)
const toPrint = await text.processText(formattedSMS, args.font, args.fontsize)
await printer.print(toPrint, 'text', true)
success = true
} catch (e) {
logger.error(e)
}
await updateSMSRecord(sms,success)
})
}
else {
throw `Failed to poll for SMSs, code ${pollResponse.code}`
}
}
catch(e) {
logger.error(e)
process.exit(1);
}
}
function formatSMSToPrint(sms, mask) {
let fromNumber = sms.from;
if(mask) {
const ccode = fromNumber.substring(0,4);
const endtwo = fromNumber.substring(fromNumber.length-2, fromNumber.length);
const padding = ''.padEnd(fromNumber.length-6, '*')
fromNumber = `${ccode}${padding}${endtwo}`
}
let toCCode
if(sms.to) {
const parsed = phoneUtil.parse(sms.to)
toCCode = phoneUtil.getRegionCodeForNumber(parsed)
}
return `${toCCode ? `To: ${toCCode} \n` : ''}From: ${fromNumber} \n Msg: ${sms.msg}`
}
async function updateSMSRecord(record, success) {
const updateResponse = await axios.post(`${args.sms}/updateSMSStatus/${record._id}`,{status: success ? 'COMPLETE' : 'ERROR'}, auth)
if (updateResponse.status !== 200) {
throw `Failed to update SMS record, code: ${updateResponse.code}`
}
}
module.exports = {
/**
* Poll the printkitty-sms-service for SMS to process
* @return {void}
*/
poll: async function(freq) {
const loop = setInterval(async () => {
await pollForSMS()
}, freq*1000);
}
}