failed.js
3.03 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
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const logger = require('komodo-sdk/logger');
const mailparser = require('../mailparser-wrapper');
const config = require('../../config');
const eventType = 'FAILED';
const maxSecondsToRetry = 5 * 60;
module.exports = async (msgFilename) => {
const msg = await fs.promises.readFile(msgFilename);
if (!msg) {
logger.warn('Sent failed detected but we can not read message file', { eventType, msgFile: msgFilename });
return;
}
const parsedMsg = await mailparser(msg);
if (!parsedMsg || !parsedMsg.headers) {
logger.warn('Sent failed detected and we can not parsed message file', {
eventType,
msgFile: msgFilename,
msgFileContent: (msg || '').toString(),
});
return;
}
const to = parsedMsg.headers.get('to').text;
const modem = parsedMsg.headers.get('modem');
const imsi = parsedMsg.headers.get('imsi');
const imei = parsedMsg.headers.get('imei');
const failReason = parsedMsg.headers.get('fail_reason');
const failed = parsedMsg.headers.get('failed');
const { text } = parsedMsg;
const originalTsMatched = msgFilename.match(/komodo\.((\d+)_(\d+))/);
const originalTs = originalTsMatched && originalTsMatched[1];
const originalTsParsed = originalTs && moment(originalTs, 'YYYYMMDD_HHmmss');
const deltaTimeMs = originalTsParsed && Number(new Date() - originalTsParsed);
const retry = (deltaTimeMs && (deltaTimeMs < (maxSecondsToRetry * 1000)))
&& !config.smstools_disable_retry_on_failed;
logger.verbose('Sent failed detected', {
eventType,
msgFile: msgFilename,
to,
modem,
imsi,
imei,
failReason,
failed,
originalTsParsed,
deltaTimeMs,
maxSecondsToRetry,
configAllowRetry: config.smstools_disable_retry_on_failed,
retry,
text,
textLength: text.length,
});
if (!retry) {
return;
}
try {
await fs.promises.unlink(msgFilename);
} catch (e) {
logger.warn(`Can not unlink failed message for send retry. ${e.message || e.toString()}`, {
eventType,
msgFile: msgFilename,
to,
text,
});
return;
}
const newMessageContent = `
To: ${to}
${text}
`.trim();
const outboxDir = config.outbox_dir || '/var/spool/sms/outgoing';
const newFileName = `${outboxDir}/${path.basename(msgFilename)}`;
try {
fs.promises.writeFile(newFileName, newMessageContent, { mode: 0o660 });
} catch (e) {
logger.warn(`Can not create retry file. ${e.message || e.toString()}`, {
eventType,
msgFile: msgFilename,
newFileName,
to,
text,
});
return;
}
logger.info('Retry file written', {
eventType,
msgFile: msgFilename,
newFileName,
to,
text,
textLength: text.length,
});
};