forked from RocketChat/Apps.Dialogflow
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpayloadAction.ts
More file actions
225 lines (214 loc) · 8.19 KB
/
payloadAction.ts
File metadata and controls
225 lines (214 loc) · 8.19 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
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
import { IHttp, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { IApp } from '@rocket.chat/apps-engine/definition/IApp';
import { ILivechatRoom } from '@rocket.chat/apps-engine/definition/livechat';
import { AppSetting } from '../config/Settings';
import { ActionIds } from '../enum/ActionIds';
import {
DialogflowRequestType,
IDialogflowAction,
IDialogflowCustomFields,
IDialogflowImageCard,
IDialogflowMessage,
IDialogflowPayload,
IDialogflowQuickReplies,
IRoomCustomField,
LanguageCode,
} from '../enum/Dialogflow';
import { Logs } from '../enum/Logs';
import { JobName } from '../enum/Scheduler';
import { getError } from '../lib/Helper';
import {
getRoomAssoc,
retrieveDataByAssociation,
setIsProcessingMessage,
setIsQueueWindowActive,
setQueuedMessage,
updatePersistentData,
} from '../lib/Persistence';
import { closeChat, performHandover, updateRoomCustomFields } from '../lib/Room';
import { Dialogflow } from './Dialogflow';
import { createDialogflowMessage, createMessage } from './Message';
import { getLivechatAgentConfig } from './Settings';
export const WELCOME_EVENT_NAME = 'Welcome';
export const handlePayloadActions = async (
app: IApp,
read: IRead,
modify: IModify,
http: IHttp,
persistence: IPersistence,
rid: string,
visitorToken: string,
dialogflowMessage: IDialogflowMessage,
) => {
const { messages = [] } = dialogflowMessage;
for (const message of messages) {
const { action = null } = message as IDialogflowPayload;
if (action) {
const { name: actionName, params } = action as IDialogflowAction;
const targetDepartment: string = await getLivechatAgentConfig(read, rid, AppSetting.FallbackTargetDepartment);
if (actionName) {
if (actionName === ActionIds.PERFORM_HANDOVER) {
if (!targetDepartment) {
console.error(Logs.EMPTY_HANDOVER_DEPARTMENT);
}
if (!params) {
return;
}
const customFields = {} as IRoomCustomField;
if (params.salesforceButtonId) {
customFields.reqButtonId = params.salesforceButtonId;
}
if (params.salesforceId) {
customFields.salesforceId = params.salesforceId;
}
if (params.customDetail) {
customFields.customDetail = params.customDetail;
}
if (params.prechatDetails) {
customFields.prechatDetails = params.prechatDetails;
}
if (Object.keys(customFields).length > 0) {
await updateRoomCustomFields(rid, customFields, read, modify);
}
await performHandover(app, modify, read, rid, visitorToken, targetDepartment);
} else if (actionName === ActionIds.CLOSE_CHAT) {
const livechatRoom = (await read.getRoomReader().getById(rid)) as ILivechatRoom;
if (livechatRoom && livechatRoom.isOpen) {
await closeChat(modify, read, rid);
}
} else if (actionName === ActionIds.NEW_WELCOME_EVENT) {
const livechatRoom = (await read.getRoomReader().getById(rid)) as ILivechatRoom;
if (!livechatRoom) {
throw new Error(Logs.INVALID_ROOM_ID);
}
const {
visitor: { livechatData },
} = livechatRoom;
await sendWelcomeEventToDialogFlow(app, read, modify, persistence, http, rid, visitorToken, livechatData);
} else if (actionName === ActionIds.SET_TIMEOUT) {
if (!params) {
return;
}
const task = {
id: JobName.EVENT_SCHEDULER,
when: new Date(new Date().getTime() + Number(params.time) * 1000),
data: {
eventName: params.eventName,
rid,
sessionId: rid,
jobName: JobName.EVENT_SCHEDULER,
},
};
try {
console.log(`{ roomID: ${rid} } The DF App is scheduling a Job with data ${JSON.stringify(task)}}`);
await modify.getScheduler().scheduleOnce(task);
// Start blackout window
if (params.continue_blackout) {
await setIsProcessingMessage(read, persistence, rid, true);
}
} catch (error) {
console.error(error);
const serviceUnavailable: string = await getLivechatAgentConfig(read, rid, AppSetting.DialogflowServiceUnavailableMessage);
await createMessage(rid, read, modify, { text: serviceUnavailable }, app);
return;
}
} else if (actionName === ActionIds.CHANGE_LANGUAGE_CODE) {
if (!params) {
return;
}
const assoc = getRoomAssoc(rid);
const data = await retrieveDataByAssociation(read, assoc);
if (data.custom_languageCode !== params.newLanguageCode) {
await updatePersistentData(read, persistence, assoc, { custom_languageCode: params.newLanguageCode });
sendChangeLanguageEvent(app, read, modify, rid, http, params.newLanguageCode as string);
}
} else if (actionName === ActionIds.DROP_QUEUE) {
await setIsQueueWindowActive(read, persistence, rid, false);
await setQueuedMessage(read, persistence, rid, '');
console.debug({ rid }, 'Queue Window dropped');
} else if (actionName === ActionIds.DISPLAY_OKTA) {
/* add/update display_okta custom field */
const livechatRoom = (await read.getRoomReader().getById(rid)) as ILivechatRoom;
if (!livechatRoom) {
throw new Error(Logs.INVALID_ROOM_ID);
}
const { creator } = livechatRoom;
const modifier = await modify.getUpdater().room(rid, creator);
const builder = await modifier.addCustomField('display_okta', { display_okta: true });
await modify.getUpdater().finish(builder);
}
}
}
}
};
const sendChangeLanguageEvent = async (app: IApp, read: IRead, modify: IModify, rid: string, http: IHttp, languageCode: string) => {
try {
const event = { name: 'ChangeLanguage', languageCode, parameters: {} };
const response: IDialogflowMessage = await Dialogflow.sendRequest(http, read, modify, rid, event, DialogflowRequestType.EVENT);
await createDialogflowMessage(rid, read, modify, response, app);
} catch (error) {
console.error(`${Logs.DIALOGFLOW_REST_API_ERROR}: { roomID: ${rid} } ${getError(error)}`);
const serviceUnavailable: string = await getLivechatAgentConfig(read, rid, AppSetting.DialogflowServiceUnavailableMessage);
await createMessage(rid, read, modify, { text: serviceUnavailable }, app);
return;
}
};
export const handleResponse = async (
app: IApp,
read: IRead,
modify: IModify,
http: IHttp,
persistence: IPersistence,
rid: string,
visitorToken: string,
dialogflowMessage: IDialogflowMessage,
) => {
const { messages = [], isFallback = false } = dialogflowMessage;
for (const message of messages) {
const { action = null } = message as IDialogflowPayload;
const textMessages: Array<string | IDialogflowQuickReplies | IDialogflowPayload | IDialogflowImageCard> = [];
textMessages.push(message);
const messagesToProcess: IDialogflowMessage = {
messages: textMessages,
isFallback,
};
if (action) {
await handlePayloadActions(app, read, modify, http, persistence, rid, visitorToken, messagesToProcess);
} else {
await createDialogflowMessage(rid, read, modify, messagesToProcess, app);
}
}
};
export const sendWelcomeEventToDialogFlow = async (
app: IApp,
read: IRead,
modify: IModify,
persistence: IPersistence,
http: IHttp,
rid: string,
visitorToken: string,
livechatData,
) => {
try {
const data = await retrieveDataByAssociation(read, getRoomAssoc(rid));
const defaultLanguageCode = await getLivechatAgentConfig(read, rid, AppSetting.DialogflowAgentDefaultLanguage);
const event = {
name: WELCOME_EVENT_NAME,
languageCode: data.custom_languageCode || defaultLanguageCode || LanguageCode.EN,
parameters: { ...(livechatData || {}), roomId: rid, visitorToken } || {},
};
const disableInput: IDialogflowCustomFields = {
disableInput: true,
disableInputMessage: 'Starting chat...',
displayTyping: true,
};
await createMessage(rid, read, modify, { customFields: disableInput }, app);
const response: IDialogflowMessage = await Dialogflow.sendRequest(http, read, modify, rid, event, DialogflowRequestType.EVENT);
await handleResponse(app, read, modify, http, persistence, rid, visitorToken, response);
} catch (error) {
console.error(`${Logs.DIALOGFLOW_REST_API_ERROR}: { roomID: ${rid} } ${getError(error)}`);
const serviceUnavailable: string = await getLivechatAgentConfig(read, rid, AppSetting.DialogflowServiceUnavailableMessage);
await createMessage(rid, read, modify, { text: serviceUnavailable }, app);
return;
}
};