-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathdualChannelHelper.ts
313 lines (260 loc) · 10.3 KB
/
dualChannelHelper.ts
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import { ConferenceParticipant, ITask, Manager, TaskHelper } from '@twilio/flex-ui';
import TaskRouterService from '../../../utils/serverless/TaskRouter/TaskRouterService';
import { FetchedRecording } from '../../../types/serverless/twilio-api';
import { getChannelToRecord, getExcludedAttributes, getExcludedQueues } from '../config';
import DualChannelService from './DualChannelService';
import logger from '../../../utils/logger';
const manager = Manager.getInstance();
export const canRecordTask = (task: ITask): boolean => {
if (getExcludedQueues().findIndex((queue) => queue === task.queueName || queue === task.queueSid) >= 0) {
return false;
}
for (const attribute of getExcludedAttributes()) {
if (task.attributes[attribute.key] === attribute.value) {
return false;
}
}
return true;
};
const addCallDataToTask = async (task: ITask, callSid: string | null, recording: FetchedRecording | null) => {
const { conference } = task;
let newAttributes = {} as any;
let shouldUpdateTaskAttributes = false;
if (TaskHelper.isOutboundCallTask(task)) {
shouldUpdateTaskAttributes = true;
// Last Reviewed: 2021/02/01 (YYYY/MM/DD)
// Outbound calls initiated from Flex (via StartOutboundCall Action)
// do not include call_sid and conference metadata in task attributes
newAttributes.conference = { sid: conference?.conferenceSid };
if (callSid) {
// callSid will be undefined if the outbound call was ended before
// the called party answered
newAttributes.call_sid = callSid;
}
}
if (recording) {
const { dateUpdated, sid: reservationSid } = task;
shouldUpdateTaskAttributes = true;
const state = manager.store.getState();
const flexState = state && state.flex;
const workerState = flexState && flexState.worker;
const accountSid = workerState && workerState.source?.accountSid;
const { sid: recordingSid } = recording;
const twilioApiBase = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}`;
const recordingUrl = `${twilioApiBase}/Recordings/${recordingSid}`;
// Using one second before task updated time to workaround a Flex Insights
// bug if the recording start time is after the reservation.accepted event
const recordingStartTime = new Date(dateUpdated).valueOf() - 1000;
// NOTE: This schema is applicable if recording the customer leg since there
// is a single recording for the entire call. If instead you're recording the
// worker leg, which could result in multiple recordings per call in the case
// of a transfer, then you'll want to use the reservation_attributes pattern:
// https://www.twilio.com/docs/flex/developer/insights/custom-media-attached-conversations#add-media-links
const mediaObj = {
url: recordingUrl,
type: 'VoiceRecording',
start_time: recordingStartTime,
channels: ['customer', 'others'],
};
switch (getChannelToRecord()) {
case 'worker':
newAttributes = {
...newAttributes,
reservation_attributes: {
[reservationSid]: {
media: [mediaObj],
},
},
};
break;
case 'customer':
newAttributes.conversations = {
media: [mediaObj],
};
break;
default:
break;
}
}
if (shouldUpdateTaskAttributes) {
try {
await TaskRouterService.updateTaskAttributes(task.taskSid, newAttributes);
} catch (error: any) {
logger.error('[dual-channel-recording] Error updating task attributes', error);
}
}
};
const isTaskActive = (task: ITask) => {
const { sid: reservationSid, taskStatus } = task;
if (taskStatus === 'canceled') {
return false;
}
return manager.workerClient?.reservations.has(reservationSid);
};
const getParticipantToRecord = (channel: 'worker' | 'customer', participants: ConferenceParticipant[]) => {
if (channel === 'worker') {
return participants.find((p) => p.participantType === 'worker' && p.isCurrentWorker && p.status === 'joined');
}
return participants.find((p) => p.participantType === 'customer');
};
const waitForConferenceParticipants = async (task: ITask): Promise<ConferenceParticipant[]> =>
new Promise((resolve) => {
const waitTimeMs = 100;
// For outbound calls, the customer participant doesn't join the conference
// until the called party answers. Need to allow enough time for that to happen.
const maxWaitTimeMs = 60000;
let waitForConferenceInterval: null | NodeJS.Timeout = setInterval(async () => {
const { conference } = task;
if (!isTaskActive(task)) {
logger.debug('[dual-channel-recording] Call canceled, clearing waitForConferenceInterval');
if (waitForConferenceInterval) {
clearInterval(waitForConferenceInterval);
waitForConferenceInterval = null;
}
return;
}
if (conference === undefined) {
return;
}
let { participants } = conference;
if (Array.isArray(participants) && participants.length < 2) {
return;
}
const participantToRecord = getParticipantToRecord(getChannelToRecord(), participants);
if (!participantToRecord) {
return;
}
if (!participantToRecord?.callSid) {
logger.debug('[dual-channel-recording] Looking for call SID');
// Flex sometimes does not provide callSid in task conference participants, check if it is in the Redux store instead
const storeConference = manager.store.getState().flex.conferences.states.get(task.taskSid);
if (!storeConference || !storeConference.source) {
return;
}
participants = storeConference.source.participants;
const storeParticipant = getParticipantToRecord(getChannelToRecord(), participants);
if (!storeParticipant?.callSid) {
logger.info(
`[dual-channel-recording] ${getChannelToRecord()} participants joined conference, waiting for call SID`,
);
return;
}
}
logger.debug(`[dual-channel-recording] ${getChannelToRecord()} participants joined conference`);
if (waitForConferenceInterval) {
clearInterval(waitForConferenceInterval);
waitForConferenceInterval = null;
}
resolve(participants);
}, waitTimeMs);
setTimeout(() => {
if (waitForConferenceInterval) {
logger.info(
`[dual-channel-recording] ${getChannelToRecord()} participant didn't show up within ${
maxWaitTimeMs / 1000
} seconds`,
);
if (waitForConferenceInterval) {
clearInterval(waitForConferenceInterval);
waitForConferenceInterval = null;
}
resolve([]);
}
}, maxWaitTimeMs);
});
const waitForActiveCall = async (task: ITask): Promise<string> =>
new Promise((resolve) => {
const waitTimeMs = 100;
// For internal calls, there is no conference, so we only have the active call to work with.
// Wait here for the call to establish.
const maxWaitTimeMs = 60000;
let waitForCallInterval: null | NodeJS.Timeout = setInterval(async () => {
if (!isTaskActive(task)) {
logger.debug('[dual-channel-recording] Call canceled, clearing waitForCallInterval');
if (waitForCallInterval) {
clearInterval(waitForCallInterval);
waitForCallInterval = null;
}
return;
}
const { activeCall } = manager.store.getState().flex.phone;
if (!activeCall) {
return;
}
if (waitForCallInterval) {
clearInterval(waitForCallInterval);
waitForCallInterval = null;
}
resolve(activeCall.parameters.CallSid);
}, waitTimeMs);
setTimeout(() => {
if (waitForCallInterval) {
logger.info(`[dual-channel-recording] Call didn't activate within ${maxWaitTimeMs / 1000} seconds`);
if (waitForCallInterval) {
clearInterval(waitForCallInterval);
waitForCallInterval = null;
}
resolve('');
}
}, maxWaitTimeMs);
});
export const addMissingCallDataIfNeeded = async (task: ITask) => {
if (!task) {
return;
}
const { attributes } = task;
const { conference } = attributes;
if (TaskHelper.isOutboundCallTask(task) && !conference) {
// Only worried about outbound calls since inbound calls automatically
// have the desired call and conference metadata
await addCallDataToTask(task, null, null);
}
};
const startRecording = async (task: ITask, callSid: string | undefined) => {
if (!callSid) {
logger.warn('[dual-channel-recording] Unable to determine call SID for recording');
return;
}
try {
const recording = await DualChannelService.startDualChannelRecording(callSid);
await addCallDataToTask(task, callSid, recording);
} catch (error: any) {
logger.error('[dual-channel-recording] Unable to start dual channel recording.', error);
}
};
export const recordInternalCall = async (task: ITask) => {
// internal call - always record based on call SID, as conference state is unknown by Flex
// Record only the outbound leg to prevent duplicate recordings
logger.debug('[dual-channel-recording] Waiting for internal call to begin');
const callSid = await waitForActiveCall(task);
logger.info(`[dual-channel-recording] Recorded internal call: ${callSid}`);
await startRecording(task, callSid);
};
export const recordExternalCall = async (task: ITask) => {
// We want to wait for all participants (customer and worker) to join the
// conference before we start the recording
logger.debug('[dual-channel-recording] Waiting for customer and worker to join the conference');
const participants = await waitForConferenceParticipants(task);
let participantLeg;
switch (getChannelToRecord()) {
case 'customer': {
participantLeg = participants.find((p) => p.participantType === 'customer');
break;
}
case 'worker': {
participantLeg = participants.find(
(p) => p.participantType === 'worker' && p.isCurrentWorker && p.status === 'joined',
);
break;
}
default:
break;
}
logger.info('[dual-channel-recording] Recorded Participant: ', participantLeg);
if (!participantLeg) {
logger.warn('[dual-channel-recording] No customer or worker participant. Not starting the call recording');
return;
}
const { callSid } = participantLeg;
await startRecording(task, callSid);
};