-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwatch.js
220 lines (192 loc) · 6.66 KB
/
watch.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
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
216
217
218
219
220
const chalk = require('chalk');
const columnify = require('columnify');
const { flags } = require('@oclif/command');
const { TwilioClientCommand } = require('@twilio/cli-core').baseCommands;
const { OutputFormats } = require('@twilio/cli-core').services.outputFormats;
const { capitalize } = require('@twilio/cli-core').services.namingConventions;
const { sleep } = require('@twilio/cli-core').services.JSUtils;
const moment = require('moment');
const querystring = require('querystring');
const STREAMING_DELAY_IN_SECONDS = 1;
const STREAMING_HISTORY_IN_MINUTES = 5;
const STREAMING_HISTORY_IN_MS = STREAMING_HISTORY_IN_MINUTES * 60 * 1000;
function headingTransform(heading) {
const capitalizeWords = ['Id', 'Sid', 'Iso', 'Sms', 'Url'];
heading = heading.replace(/([A-Z])/g, ' $1');
heading = capitalize(heading);
heading = heading
.split(' ')
.map(word => (capitalizeWords.indexOf(word) > -1 ? word.toUpperCase() : word))
.join(' ');
return chalk.bold(heading);
}
class Watch extends TwilioClientCommand {
constructor(argv, config, secureStorage) {
super(argv, config, secureStorage);
this.showHeaders = true;
this.latestLogEvents = {
debugger: [],
message: [],
call: []
};
}
async runCommand() {
const logger = this.logger;
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', () => {
process.emit('SIGINT');
});
}
process.on('SIGINT', () => {
// graceful shutdown
logger.info('And now my watch is ended.');
/* eslint-disable no-process-exit */
process.exit();
});
const props = this.parseProperties() || {};
logger.info('And now my watch begins. It shall not end until CTRL-C (SIGINT).');
// Get any historical data first so we know what's new
this.startDate = new Date(new Date() - STREAMING_HISTORY_IN_MS);
const logEvents = await this.getLogEvents();
if (props.showRecentHistory) {
this.outputLogEvents(logEvents);
}
// Then get streaming data.
/* eslint-disable no-await-in-loop, no-constant-condition */
while (true) {
this.startDate = new Date(new Date() - STREAMING_HISTORY_IN_MS);
const logEvents = await this.getLogEvents();
this.outputLogEvents(logEvents);
await sleep(STREAMING_DELAY_IN_SECONDS * 1000);
}
}
async getLogEvents() {
try {
const [logEvents, smsEvents, callEvents] = await Promise.all([
this.twilioClient.monitor.alerts.list({ startDate: this.startDate }),
this.twilioClient.messages.list({ dateSentAfter: this.startDate }),
this.twilioClient.calls.list({ startTimeAfter: this.startDate })
]);
return this.filterLogEvents(logEvents, 'debugger', e => e.sid)
.map(e => ({
date: this.formatDateTime(e.dateCreated),
type: e.logLevel,
code: e.errorCode,
text: this.formatAlertText(e.alertText),
raw: e
}))
.concat(
this.filterLogEvents(smsEvents, 'message', e => e.sid + e.status).map(e => ({
date: this.formatDateTime(e.dateUpdated),
type: `message[${this.directionInOrOut(e, 'in', 'out')}]`,
code: e.status,
text: this.flags['no-pii'] ? e.body.length + ' chars' : e.body,
raw: e
}))
)
.concat(
this.filterLogEvents(callEvents, 'call', e => e.sid + e.status).map(e => ({
date: this.formatDateTime(e.dateUpdated),
type: `call[${this.directionInOrOut(e, 'in', 'out')}]`,
code: e.status,
text: `FROM: ${this.redactPhone(e.from)}, TO: ${this.redactPhone(e.to)}`,
raw: e
}))
)
.sort((a, b) => {
if (a.date < b.date) {
return -1;
}
return a.date > b.date ? 1 : 0;
});
} catch (error) {
this.logger.error(error.message);
this.exit(error.code);
}
}
filterLogEvents(logEvents, eventType, keyFunc) {
const previousLogEvents = new Set(this.latestLogEvents[eventType]);
this.latestLogEvents[eventType] = new Set(logEvents.map(keyFunc));
// Filter out any events that we just saw, and then reverse them so they're
// in ascending order.
return logEvents.filter(event => !previousLogEvents.has(keyFunc(event))).reverse();
}
directionInOrOut(message, inboundText, outboundText) {
return message.direction.includes('out') ? outboundText : inboundText;
}
redactPhone(num) {
return this.flags['no-pii'] ? num.substring(0, 5) + num.substring(5).replace(/\d/g, '*') : num;
}
outputLogEvents(logEvents) {
const COL_1 = 20;
const COL_2 = 12;
const COL_3 = 12;
const COL_4 = process.stdout.columns - COL_1 - COL_2 - COL_3 - 3;
if (logEvents.length > 0) {
if (this.outputProcessor === OutputFormats.columns) {
process.stdout.write(
columnify(
logEvents.map(e => {
delete e.raw;
return e;
}),
{
truncate: true,
showHeaders: this.showHeaders,
config: {
date: { minWidth: COL_1, maxWidth: COL_1, headingTransform },
type: { minWidth: COL_2, maxWidth: COL_2, headingTransform },
code: { minWidth: COL_3, maxWidth: COL_3, headingTransform },
text: { minWidth: COL_4, maxWidth: COL_4, headingTransform }
}
}
) + '\n'
);
} else {
this.output(logEvents, this.flags.properties, { showHeaders: this.showHeaders });
}
this.showHeaders = false;
}
}
formatDateTime(dateTime) {
return moment(dateTime)
.utc()
.toISOString()
.replace('T', ' ')
.replace('.000Z', '');
}
formatAlertText(text) {
try {
const data = querystring.parse(text);
return data.parserMessage || data.Msg || text;
} catch (e) {
return text;
}
}
}
Watch.description = 'Keep an eye on incoming alerts, messages, and calls. Polls every 1 second.';
Watch.PropertyFlags = {
'show-recent-history': flags.boolean({
default: false,
description: 'show recent events that occurred prior to beginning my watch'
}),
'no-pii': flags.boolean({
default: false,
description: 'mask columns that may contain personally identifiable information (PII)'
})
};
Watch.flags = Object.assign(
{
properties: flags.string({
default: 'date, type, code, text',
description: 'event properties you would like to display'
})
},
Watch.PropertyFlags,
TwilioClientCommand.flags
);
module.exports = Watch;