-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.channel.ts
660 lines (621 loc) · 21.1 KB
/
index.channel.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import crypto from 'crypto';
import { Stream } from 'stream';
import { HttpService } from '@nestjs/axios';
import { Injectable, RawBodyRequest } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { NextFunction, Request, Response } from 'express';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { AttachmentFile } from '@/attachment/types';
import { ChannelService } from '@/channel/channel.service';
import ChannelHandler from '@/channel/lib/Handler';
import { SubscriberCreateDto } from '@/chat/dto/subscriber.dto';
import { FileType } from '@/chat/schemas/types/attachment';
import { ButtonType, PostBackButton } from '@/chat/schemas/types/button';
import {
IncomingMessageType,
OutgoingMessageFormat,
StdEventType,
StdOutgoingAttachmentMessage,
StdOutgoingButtonsMessage,
StdOutgoingEnvelope,
StdOutgoingListMessage,
StdOutgoingQuickRepliesMessage,
StdOutgoingTextMessage,
} from '@/chat/schemas/types/message';
import { BlockOptions } from '@/chat/schemas/types/options';
import { LabelService } from '@/chat/services/label.service';
import { MessageService } from '@/chat/services/message.service';
import { SubscriberService } from '@/chat/services/subscriber.service';
import { Content } from '@/cms/schemas/content.schema';
import { MenuService } from '@/cms/services/menu.service';
import { I18nService } from '@/i18n/services/i18n.service';
import { LanguageService } from '@/i18n/services/language.service';
import { LoggerService } from '@/logger/logger.service';
import { Setting } from '@/setting/schemas/setting.schema';
import { SettingService } from '@/setting/services/setting.service';
import { GraphApi } from './lib/graph-api';
import { WHATSAPP_CHANNEL_NAME } from './settings';
import { WhatsApp } from './types';
import WhatsAppEventWrapper from './wrapper';
@Injectable()
export default class WhatsAppHandler extends ChannelHandler<
typeof WHATSAPP_CHANNEL_NAME
> {
protected api: GraphApi;
constructor(
settingService: SettingService,
channelService: ChannelService,
logger: LoggerService,
protected readonly eventEmitter: EventEmitter2,
protected readonly i18n: I18nService,
protected readonly languageService: LanguageService,
protected readonly subscriberService: SubscriberService,
public readonly attachmentService: AttachmentService,
protected readonly messageService: MessageService,
protected readonly menuService: MenuService,
protected readonly labelService: LabelService,
protected readonly httpService: HttpService,
protected readonly settingsService: SettingService,
) {
super(WHATSAPP_CHANNEL_NAME, settingService, channelService, logger);
}
getPath(): string {
return __dirname;
}
/**
* Logs a debug message indicating the initialization of the WhatsApp Channel Handler.
*/
async init(): Promise<void> {
this.logger.debug('WhatsApp Channel Handler: initialization ...');
const settings = await this.getSettings();
this.api = new GraphApi(
this.httpService,
settings ? settings.access_token : '',
);
}
/**
* Fetches a WhatsApp media
*
* @param event The message event received
*
* @returns Resolves the retrieved media as an attachment file.
*/
async getMessageAttachments(
event: WhatsAppEventWrapper,
): Promise<AttachmentFile[]> {
if (
event._adapter.eventType === StdEventType.message &&
event._adapter.messageType === IncomingMessageType.attachments
) {
const media =
event._adapter.raw.type in event._adapter.raw
? (event._adapter.raw[
event._adapter.raw.type
] as WhatsApp.Webhook.Media)
: null;
if (!media) {
return [];
}
const setttings = await this.getSettings();
const channelData = event.getChannelData();
const mediaMetadata = await this.api.mediaAPI.getMediaUrl(
media.id,
channelData.metadata.phone_number_id,
);
const response = await this.httpService.axiosRef.get<Stream>(
mediaMetadata.url,
{
responseType: 'stream',
headers: {
Authorization: `Bearer ${setttings.access_token}`,
},
},
);
// @TODO : perform sha256 check
return [
{
file: response.data,
size: mediaMetadata.file_size
? parseInt(mediaMetadata.file_size)
: parseInt(response.headers['content-length']),
type: mediaMetadata.mime_type || response.headers['content-type'],
},
];
}
return [];
}
/**
* @function subscribe
* @description Handles the subscription request for the WhatsApp channel.
* Validates the verification token and responds with appropriate HTTP status codes.
*
* @param {Request} req - The incoming HTTP request object.
* @param {Response} res - The outgoing HTTP response object.
*
* @returns {Promise<void>} Resolves with an HTTP response indicating the subscription status.
*
* @throws Will return a 500 status code with an error message if:
* - `verifyToken` is not configured.
* - The request does not include the required query parameters.
* - The validation tokens do not match.
*/
async subscribe(req: Request, res: Response) {
this.logger.debug('WhatsApp Channel Handler: Subscribing ...');
const data: any = req.query;
const settings = await this.getSettings();
const verifyToken = settings.verify_token;
if (!verifyToken) {
return res.status(500).json({
err: 'WhatsApp Channel Handler: You need to specify a verifyToken in your config.',
});
}
if (!data || !data['hub.mode'] || !data['hub.verify_token']) {
return res.status(500).json({
err: 'WhatsApp Channel Handler: Did not recieve any verification token.',
});
}
if (
data['hub.mode'] === 'subscribe' &&
data['hub.verify_token'] === verifyToken
) {
this.logger.log(
'WhatsApp Channel Handler: Subscription token has been verified successfully!',
);
return res.status(200).send(data['hub.challenge']);
} else {
this.logger.error(
'WhatsApp Channel Handler: Failed validation. Make sure the validation tokens match.',
);
return res.status(500).json({
err: 'WhatsApp Channel Handler: Failed validation. Make sure the validation tokens match.',
});
}
}
_validateMessage(req: Request, res: Response, next: () => void) {
const data: WhatsApp.Webhook.Notification = req.body;
if (data.object !== 'whatsapp_business_account') {
this.logger.warn(
'WhatsApp Channel Handler: Missing `whatsapp_business_account` attribute!',
data,
);
return res
.status(400)
.json({ err: 'The whatsapp_business_account parameter is missing!' });
}
return next();
}
async middleware(
req: RawBodyRequest<Request>,
_res: Response,
next: NextFunction,
) {
const signature: string = req.headers['x-hub-signature'] as string;
if (!signature) {
return next();
}
const settings = await this.getSettings();
const expectedHash = crypto
.createHmac('sha1', settings.app_secret)
.update(req.rawBody!)
.digest('hex');
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
req.whatsapp = { expectedHash };
next();
}
_verifySignature(req: Request, res: Response, next: () => void) {
const signature: string = req.headers['x-hub-signature'] as string;
const elements: string[] = signature.split('=');
const signatureHash = elements[1];
const expectedHash =
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
req.whatsapp
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
req.whatsapp.expectedHash
: '';
if (signatureHash !== expectedHash) {
this.logger.warn(
"WhatsApp Channel Handler: Couldn't match the request signature.",
signatureHash,
expectedHash,
);
return res
.status(500)
.json({ err: "Couldn't match the request signature." });
}
this.logger.debug(
'WhatsApp Channel Handler: Request signature has been validated.',
);
return next();
}
/**
* Main handler for processing incoming webhook requests from the WhatsApp channel.
*
* @param req - The incoming HTTP request object.
* @param res - The outgoing HTTP response object.
*
* @returns Resolves with an HTTP response indicating the processing status.
*
* @throws Will return a 500 status code with an error message if:
* - Signature verification fails.
* - Webhook data does not include an `entry` object.
* - An error occurs while handling events.
*/
async handle(req: Request, res: Response) {
const handler: WhatsAppHandler = this;
// Handle webhook subscribe notifications
if (req.method === 'GET') {
return await handler.subscribe(req, res);
}
return handler._verifySignature(req, res, () => {
return handler._validateMessage(req, res, () => {
const data = req.body as WhatsApp.Webhook.Notification;
this.logger.debug(
'WhatsApp Channel Handler: Webhook notification received.',
);
// Check notification
if (!('entry' in data)) {
this.logger.error(
'WhatsApp Channel Handler: Webhook received no entry data.',
);
return res.status(500).json({
err: 'WhatsApp Channel Handler: Webhook received no entry data.',
});
}
data.entry.forEach((entry) => {
entry.changes.forEach((change) => {
const messageEvents = (change.value.messages || []).map(
(message) => {
const contact = change.value.contacts?.find(
({ wa_id }) => wa_id === message.from,
);
return new WhatsAppEventWrapper(handler, message, {
metadata: change.value.metadata,
contact,
});
},
);
const statusEvents = (change.value.statuses || []).map((status) => {
return new WhatsAppEventWrapper(handler, status, {
metadata: change.value.metadata,
});
});
// Handle messages & statues
[...messageEvents, ...statusEvents].forEach((event) => {
try {
const type: StdEventType = event.getEventType();
if (type) {
this.eventEmitter.emit(`hook:chatbot:${type}`, event);
} else {
this.logger.debug(
'WhatsApp Channel Handler: Webhook received unknown event',
event,
);
}
} catch (err) {
this.logger.error(
'WhatsApp Channel Handler: Something went wrong while handling events',
err,
);
}
});
});
});
return res.status(200).json({ success: true });
});
});
}
/**
* Truncate text to a specified length, appending "..." if needed.
*
* @param text - The text to truncate.
* @param maxLength - The maximum length of the truncated text.
* @returns - The truncated text.
*/
private truncateText(text: string, maxLength: number) {
if (text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength - 3) + '...';
}
/**
* Formats an outgoing message based on its specified format type.
*
* @param envelope - The envelope containing the message and its format.
* @param options - Optional configurations for message customization.
*
* @returns The formatted message.
*/
async _formatMessage(
envelope: StdOutgoingEnvelope,
options: BlockOptions,
): Promise<WhatsApp.Messages.AnyMessage> {
switch (envelope.format) {
case OutgoingMessageFormat.buttons:
return this._buttonsFormat(envelope.message, options);
case OutgoingMessageFormat.carousel:
return this._carouselFormat(envelope.message, options);
case OutgoingMessageFormat.list:
return this._listFormat(envelope.message, options);
case OutgoingMessageFormat.quickReplies:
return this._quickRepliesFormat(envelope.message, options);
case OutgoingMessageFormat.text:
return this._textFormat(envelope.message, options);
case OutgoingMessageFormat.attachment:
return await this._attachmentFormat(envelope.message, options);
default:
throw new Error('Unknown message format');
}
}
/**
* Formats an attachment message for the WhatsApp API.
*
* @param message - The outgoing attachment message details.
* @param _options - Optional configuration for message customization.
*
* @returns The formatted attachment message object.
*/
async _attachmentFormat(
message: StdOutgoingAttachmentMessage,
_options?: BlockOptions,
): Promise<WhatsApp.Messages.AnyMediaMessage> {
const link = await this.getPublicUrl(message.attachment.payload);
const media: WhatsApp.Messages.Media = {
link,
// caption: attachment.name,
// filename: attachment.name,
};
switch (message.attachment.type) {
case FileType.image:
return {
type: WhatsApp.Messages.MediaType.Image,
image: media,
};
case FileType.audio:
return {
type: WhatsApp.Messages.MediaType.Audio,
audio: media,
};
case FileType.video:
return {
type: WhatsApp.Messages.MediaType.Video,
video: media,
};
case FileType.file:
return {
type: WhatsApp.Messages.MediaType.Document,
document: media,
};
default:
throw new Error('Unknown file type!');
}
}
/**
* Formats a list-based interactive message for the WhatsApp API.
*
* @param message - The outgoing list message details.
* @param options - Optional configuration for message customization.
*
* @returns The formatted interactive list message object.
*/
_listFormat(
message: StdOutgoingListMessage,
options: BlockOptions,
): WhatsApp.Messages.InteractiveMessage {
const fields = options.content?.fields;
const rows: WhatsApp.Messages.Row[] = message.elements.map((item) => {
const postback = Content.getPayload(item);
return {
id: postback,
title: fields ? item[fields.title] : item.title,
description:
fields?.subtitle && item[fields.subtitle]
? this.truncateText(item[fields.subtitle], 72)
: undefined, // Optional: Include if available
};
});
const btnText = message.options.buttons[0].title;
return {
type: 'interactive',
interactive: {
type: WhatsApp.Messages.InteractiveType.List,
body: {
text: this.i18n.t('Click on "{btnText}" to display the list:', {
args: { btnText },
}),
},
action: {
sections: [
{
title: 'Section',
rows,
},
],
button: btnText,
},
},
};
}
/**
* Carousel format is not supported in WhatsApp, so we will be using
* List format instead.
*
* @param message - The outgoing list message details.
* @param options - Optional configuration for message customization.
*
* @returns The formatted interactive list message object.
*/
_carouselFormat(message: StdOutgoingListMessage, options: BlockOptions) {
return this._listFormat(message, options);
}
/**
* Formats a text message for the WhatsApp API.
*
* @param message - The outgoing text message details.
* @param _options - Optional configuration for message customization.
*
* @returns The formatted message object.
*/
_textFormat(
message: StdOutgoingTextMessage,
_options?: BlockOptions,
): WhatsApp.Messages.TextMessage {
return {
type: 'text',
text: {
body: message.text,
},
};
}
/**
* Formats a quick-replies interactive message for the WhatsApp API.
*
* @param message - The outgoing quick-replies message details.
* @param _options - Optional configuration for message customization.
*
* @returns The formatted interactive message object with quick replies.
*/
_quickRepliesFormat(
message: StdOutgoingQuickRepliesMessage,
_options?: BlockOptions,
): WhatsApp.Messages.InteractiveMessage {
const buttons: WhatsApp.Messages.ReplyButton[] = message.quickReplies.map(
({ payload, title }) => ({
type: 'reply',
reply: {
id: payload,
title,
},
}),
);
return {
type: 'interactive',
interactive: {
type: WhatsApp.Messages.InteractiveType.Button,
body: {
text: message.text,
},
action: {
buttons,
},
},
};
}
/**
* Formats a button-based interactive message for the WhatsApp API.
*
* @param message - The outgoing buttons message details.
* @param _options - Optional configuration for message customization.
*
* @returns The formatted interactive message object.
*/
_buttonsFormat(
message: StdOutgoingButtonsMessage,
_options?: BlockOptions,
): WhatsApp.Messages.InteractiveMessage {
const buttons: WhatsApp.Messages.ReplyButton[] = message.buttons
.filter(({ type }) => type == ButtonType.postback)
.map((btn: PostBackButton) => ({
type: 'reply',
reply: {
id: btn.payload,
title: btn.title,
},
}));
return {
//note: URL button is not supported in whatsapp interactive message
type: 'interactive',
interactive: {
type: WhatsApp.Messages.InteractiveType.Button,
body: {
text: message.text,
},
action: {
buttons,
},
},
};
}
/**
* Sends a message via the WhatsApp API to the recipient specified in the event.
* Formats the message based on the provided envelope and options, and returns the message ID of the sent message.
*
* @param event - The event wrapper containing details about the message sender and context.
* @param envelope - The envelope containing the outgoing message details.
* @param options - Options for message customization (e.g., templates, formatting).
* @param _context - Optional additional context for the message (default: `undefined`).
*
* @returns Resolves with an object containing the message ID (`mid`) of the sent message.
*/
async sendMessage(
event: WhatsAppEventWrapper,
envelope: StdOutgoingEnvelope,
options: BlockOptions,
_context?: any,
): Promise<{ mid: string }> {
const message = await this._formatMessage(envelope, options);
const channelData = event.getChannelData();
try {
const res = await this.api.sendMessage(
{
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: event.getSenderForeignId(),
...message,
},
channelData.metadata.phone_number_id,
);
return { mid: res.messages[0].id };
} catch (err) {
this.logger.error(err.response?.data);
throw err;
}
}
/**
* Retrieves user data based on a WhatsApp event.
*
* @param event - The WhatsApp event wrapper containing the event details.
*
* @returns A promise that resolves with the constructed `SubscriberCreateDto` object.
*/
async getSubscriberData(
event: WhatsAppEventWrapper,
): Promise<SubscriberCreateDto> {
const defautLanguage = await this.languageService.getDefaultLanguage();
const channelData = event.getChannelData();
const userName = channelData.contact?.profile?.name;
const [firstName, ...rest] = userName
? userName.split(' ')
: ['Anonymous', 'Subscriber'];
const lastName = rest.join(' ');
// @TODO: Check if there is a way to retrieve the avatar
return {
foreign_id: event.getSenderForeignId(),
first_name: firstName,
last_name: lastName,
gender: 'unknown',
channel: channelData,
assignedAt: null,
assignedTo: null,
labels: [],
locale: 'en',
language: defautLanguage.code,
country: '',
lastvisit: new Date(),
retainedFrom: new Date(),
};
}
@OnEvent('hook:whatsapp_channel:access_token')
async onAccessTokenUpdate(setting: Setting): Promise<void> {
this.api = new GraphApi(this.httpService, setting.value);
}
}