@vinzsocket/baileys 3.3.1 → 3.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2684 -1336
- package/WAProto/WAProto.proto +360 -916
- package/WAProto/fix-imports.js +22 -18
- package/WAProto/index.d.ts +14015 -0
- package/WAProto/index.js +47122 -81757
- package/engine-requirements.js +27 -0
- package/lib/Defaults/index.d.ts +15 -14
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +98 -109
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Signal/Group/group_cipher.js.map +1 -1
- package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
- package/lib/Signal/Group/keyhelper.js.map +1 -1
- package/lib/Signal/Group/sender-chain-key.js.map +1 -1
- package/lib/Signal/Group/sender-key-message.js.map +1 -1
- package/lib/Signal/Group/sender-message-key.js.map +1 -1
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +45 -17
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts +4 -0
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js +6 -0
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/business.d.ts +213 -532
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/business.js +358 -401
- package/lib/Socket/chats.d.ts +15 -2
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +247 -40
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +269 -641
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/dugong.d.ts +315 -127
- package/lib/Socket/dugong.js +653 -749
- package/lib/Socket/groups.d.ts +13 -2
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +21 -1
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +256 -631
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/index.js +9 -12
- package/lib/Socket/index.js.map +1 -1
- package/lib/Socket/messages-recv.d.ts +23 -58
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +645 -181
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +201 -575
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +1185 -1552
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/mex.d.ts.map +1 -1
- package/lib/Socket/mex.js +2 -8
- package/lib/Socket/mex.js.map +1 -1
- package/lib/Socket/newsletter.d.ts +11 -18
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +165 -440
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +6 -2
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +59 -25
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Bussines.d.ts +22 -34
- package/lib/Types/Call.d.ts +1 -1
- package/lib/Types/Call.d.ts.map +1 -1
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.d.ts.map +1 -1
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.d.ts.map +1 -1
- package/lib/Types/Events.d.ts +20 -1
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/GroupMetadata.d.ts +4 -1
- package/lib/Types/GroupMetadata.d.ts.map +1 -1
- package/lib/Types/Message.d.ts +294 -348
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/Mex.d.ts +141 -0
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/Mex.js +37 -0
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Signal.d.ts +12 -1
- package/lib/Types/Signal.d.ts.map +1 -1
- package/lib/Types/Socket.d.ts +126 -148
- package/lib/Types/Socket.d.ts.map +1 -1
- package/lib/Types/State.d.ts +58 -0
- package/lib/Types/State.d.ts.map +1 -1
- package/lib/Types/State.js +43 -0
- package/lib/Types/State.js.map +1 -1
- package/lib/Types/index.d.ts +52 -52
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +23 -30
- package/lib/Types/index.js.map +1 -1
- package/lib/Utils/auth-utils.d.ts +5 -0
- package/lib/Utils/auth-utils.d.ts.map +1 -1
- package/lib/Utils/auth-utils.js +12 -0
- package/lib/Utils/auth-utils.js.map +1 -1
- package/lib/Utils/browser-utils.js +1 -0
- package/lib/Utils/chat-utils.d.ts +34 -4
- package/lib/Utils/chat-utils.d.ts.map +1 -1
- package/lib/Utils/chat-utils.js +80 -20
- package/lib/Utils/chat-utils.js.map +1 -1
- package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/crypto.d.ts +12 -12
- package/lib/Utils/crypto.d.ts.map +1 -1
- package/lib/Utils/crypto.js.map +1 -1
- package/lib/Utils/decode-wa-message.d.ts +18 -0
- package/lib/Utils/decode-wa-message.d.ts.map +1 -1
- package/lib/Utils/decode-wa-message.js +34 -0
- package/lib/Utils/decode-wa-message.js.map +1 -1
- package/lib/Utils/event-buffer.d.ts +2 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -1
- package/lib/Utils/event-buffer.js +49 -1
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +2 -2
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +10 -1
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +2 -0
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +12 -9
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +7 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -1
- package/lib/Utils/identity-change-handler.js +1 -0
- package/lib/Utils/identity-change-handler.js.map +1 -1
- package/lib/Utils/index.d.ts +23 -23
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +4 -1
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/link-preview.js +2 -2
- package/lib/Utils/link-preview.js.map +1 -1
- package/lib/Utils/logger.d.ts +1 -2
- package/lib/Utils/logger.d.ts.map +1 -1
- package/lib/Utils/mention.d.ts +14 -0
- package/lib/Utils/mention.js +138 -0
- package/lib/Utils/message-retry-manager.d.ts +5 -0
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +40 -0
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +16 -13
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +85 -79
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +16 -1
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +1021 -1121
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/noise-handler.d.ts +1 -1
- package/lib/Utils/process-message.d.ts.map +1 -1
- package/lib/Utils/process-message.js +103 -1
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/signal.d.ts +13 -0
- package/lib/Utils/signal.d.ts.map +1 -1
- package/lib/Utils/signal.js +42 -0
- package/lib/Utils/signal.js.map +1 -1
- package/lib/Utils/story-card.js +107 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -1
- package/lib/Utils/sync-action-utils.js +1 -0
- package/lib/Utils/sync-action-utils.js.map +1 -1
- package/lib/Utils/tc-token-utils.d.ts +26 -1
- package/lib/Utils/tc-token-utils.d.ts.map +1 -1
- package/lib/Utils/tc-token-utils.js +151 -5
- package/lib/Utils/tc-token-utils.js.map +1 -1
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +12 -2
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/decode.d.ts +1 -1
- package/lib/WABinary/decode.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.d.ts +1 -3
- package/lib/WABinary/generic-utils.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.js +0 -78
- package/lib/WABinary/generic-utils.js.map +1 -1
- package/lib/WAM/encode.d.ts +1 -1
- package/lib/WAM/encode.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/index.js +1 -0
- package/lib/WAUSync/Protocols/index.js.map +1 -1
- package/lib/WAUSync/USyncQuery.d.ts +1 -0
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
- package/lib/WAUSync/USyncQuery.js +6 -2
- package/lib/WAUSync/USyncQuery.js.map +1 -1
- package/lib/WAUSync/USyncUser.d.ts +4 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -1
- package/lib/WAUSync/USyncUser.js +8 -0
- package/lib/WAUSync/USyncUser.js.map +1 -1
- package/lib/index.d.ts +0 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +0 -1
- package/lib/index.js.map +1 -1
- package/package.json +91 -24
- package/LICENSE +0 -21
- package/lib/Socket/dugong.d.ts.map +0 -1
- package/lib/Socket/dugong.js.map +0 -1
- package/lib/Types/Newsletter.d.ts.map +0 -1
- package/lib/Types/Newsletter.js.map +0 -1
- package/lib/Utils/rich-messages.d.ts.map +0 -1
- package/lib/Utils/rich-messages.js.map +0 -1
package/lib/Utils/messages.js
CHANGED
|
@@ -1,51 +1,29 @@
|
|
|
1
|
-
import { Boom } from
|
|
2
|
-
import { randomBytes } from
|
|
3
|
-
import { promises as fs } from
|
|
4
|
-
import {} from
|
|
5
|
-
import { proto } from
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
} from
|
|
13
|
-
import { WAMessageStatus, WAProto } from "../Types/index.js";
|
|
14
|
-
import {
|
|
15
|
-
isJidGroup,
|
|
16
|
-
isJidNewsletter,
|
|
17
|
-
isJidStatusBroadcast,
|
|
18
|
-
jidNormalizedUser,
|
|
19
|
-
} from "../WABinary/index.js";
|
|
20
|
-
import { sha256 } from "./crypto.js";
|
|
21
|
-
import {
|
|
22
|
-
generateMessageIDV2,
|
|
23
|
-
getKeyAuthor,
|
|
24
|
-
unixTimestampSeconds,
|
|
25
|
-
} from "./generics.js";
|
|
26
|
-
import {
|
|
27
|
-
downloadContentFromMessage,
|
|
28
|
-
encryptedStream,
|
|
29
|
-
generateThumbnail,
|
|
30
|
-
getAudioDuration,
|
|
31
|
-
getAudioWaveform,
|
|
32
|
-
getRawMediaUploadData,
|
|
33
|
-
} from "./messages-media.js";
|
|
34
|
-
import { shouldIncludeReportingToken } from "./reporting-utils.js";
|
|
1
|
+
import { Boom } from '@hapi/boom';
|
|
2
|
+
import { randomBytes } from 'crypto';
|
|
3
|
+
import { promises as fs } from 'fs';
|
|
4
|
+
import {} from 'stream';
|
|
5
|
+
import { proto } from '../../WAProto/index.js';
|
|
6
|
+
import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
7
|
+
import { WAMessageStatus, WAProto } from '../Types/index.js';
|
|
8
|
+
import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
|
|
9
|
+
import { sha256 } from './crypto.js';
|
|
10
|
+
import { generateMessageID, generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
|
|
11
|
+
import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
|
|
12
|
+
import { shouldIncludeReportingToken } from './reporting-utils.js';
|
|
35
13
|
const MIMETYPE_MAP = {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
14
|
+
image: 'image/jpeg',
|
|
15
|
+
video: 'video/mp4',
|
|
16
|
+
document: 'application/pdf',
|
|
17
|
+
audio: 'audio/ogg; codecs=opus',
|
|
18
|
+
sticker: 'image/webp',
|
|
19
|
+
'product-catalog-image': 'image/jpeg'
|
|
42
20
|
};
|
|
43
21
|
const MessageTypeProto = {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
22
|
+
image: WAProto.Message.ImageMessage,
|
|
23
|
+
video: WAProto.Message.VideoMessage,
|
|
24
|
+
audio: WAProto.Message.AudioMessage,
|
|
25
|
+
sticker: WAProto.Message.StickerMessage,
|
|
26
|
+
document: WAProto.Message.DocumentMessage
|
|
49
27
|
};
|
|
50
28
|
/**
|
|
51
29
|
* Uses a regex to test whether the string contains a URL, and returns the URL if it does.
|
|
@@ -53,310 +31,204 @@ const MessageTypeProto = {
|
|
|
53
31
|
* @returns the URL, eg. https://google.com
|
|
54
32
|
*/
|
|
55
33
|
export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
|
|
56
|
-
export const generateLinkPreviewIfRequired = async (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
logger?.warn({ trace: error.stack }, "url generation failed");
|
|
69
|
-
}
|
|
70
|
-
}
|
|
34
|
+
export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
|
|
35
|
+
const url = extractUrlFromText(text);
|
|
36
|
+
if (!!getUrlInfo && url) {
|
|
37
|
+
try {
|
|
38
|
+
const urlInfo = await getUrlInfo(url);
|
|
39
|
+
return urlInfo;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
// ignore if fails
|
|
43
|
+
logger?.warn({ trace: error.stack }, 'url generation failed');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
71
46
|
};
|
|
72
47
|
const assertColor = async (color) => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
48
|
+
let assertedColor;
|
|
49
|
+
if (typeof color === 'number') {
|
|
50
|
+
assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
let hex = color.trim().replace('#', '');
|
|
54
|
+
if (hex.length <= 6) {
|
|
55
|
+
hex = 'FF' + hex.padStart(6, '0');
|
|
56
|
+
}
|
|
57
|
+
assertedColor = parseInt(hex, 16);
|
|
58
|
+
return assertedColor;
|
|
59
|
+
}
|
|
84
60
|
};
|
|
85
61
|
export const prepareWAMessageMedia = async (message, options) => {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
mediaType
|
|
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
|
-
|
|
62
|
+
const logger = options.logger;
|
|
63
|
+
let mediaType;
|
|
64
|
+
for (const key of MEDIA_KEYS) {
|
|
65
|
+
if (key in message) {
|
|
66
|
+
mediaType = key;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (!mediaType) {
|
|
70
|
+
throw new Boom('Invalid media type', { statusCode: 400 });
|
|
71
|
+
}
|
|
72
|
+
const uploadData = {
|
|
73
|
+
...message,
|
|
74
|
+
media: message[mediaType]
|
|
75
|
+
};
|
|
76
|
+
delete uploadData[mediaType];
|
|
77
|
+
// check if cacheable + generate cache key
|
|
78
|
+
const cacheableKey = typeof uploadData.media === 'object' &&
|
|
79
|
+
'url' in uploadData.media &&
|
|
80
|
+
!!uploadData.media.url &&
|
|
81
|
+
!!options.mediaCache &&
|
|
82
|
+
mediaType + ':' + uploadData.media.url.toString();
|
|
83
|
+
if (mediaType === 'document' && !uploadData.fileName) {
|
|
84
|
+
uploadData.fileName = 'file';
|
|
85
|
+
}
|
|
86
|
+
if (!uploadData.mimetype) {
|
|
87
|
+
uploadData.mimetype = MIMETYPE_MAP[mediaType];
|
|
88
|
+
}
|
|
89
|
+
if (cacheableKey) {
|
|
90
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey);
|
|
91
|
+
if (mediaBuff) {
|
|
92
|
+
logger?.debug({ cacheableKey }, 'got media cache hit');
|
|
93
|
+
const obj = proto.Message.decode(mediaBuff);
|
|
94
|
+
const key = `${mediaType}Message`;
|
|
95
|
+
Object.assign(obj[key], { ...uploadData, media: undefined });
|
|
96
|
+
return obj;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
|
|
100
|
+
if (isNewsletter) {
|
|
101
|
+
logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
|
|
102
|
+
const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
|
|
103
|
+
const fileSha256B64 = fileSha256.toString('base64');
|
|
104
|
+
const { mediaUrl, directPath } = await options.upload(filePath, {
|
|
105
|
+
fileEncSha256B64: fileSha256B64,
|
|
106
|
+
mediaType: mediaType,
|
|
107
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
108
|
+
});
|
|
109
|
+
await fs.unlink(filePath);
|
|
110
|
+
const obj = WAProto.Message.fromObject({
|
|
111
|
+
// todo: add more support here
|
|
112
|
+
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
113
|
+
url: mediaUrl,
|
|
114
|
+
directPath,
|
|
115
|
+
fileSha256,
|
|
116
|
+
fileLength,
|
|
117
|
+
...uploadData,
|
|
118
|
+
media: undefined
|
|
119
|
+
})
|
|
120
|
+
});
|
|
121
|
+
if (uploadData.ptv) {
|
|
122
|
+
obj.ptvMessage = obj.videoMessage;
|
|
123
|
+
delete obj.videoMessage;
|
|
124
|
+
}
|
|
125
|
+
if (obj.stickerMessage) {
|
|
126
|
+
obj.stickerMessage.stickerSentTs = Date.now();
|
|
127
|
+
}
|
|
128
|
+
if (cacheableKey) {
|
|
129
|
+
logger?.debug({ cacheableKey }, 'set cache');
|
|
130
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
|
|
131
|
+
}
|
|
132
|
+
return obj;
|
|
133
|
+
}
|
|
134
|
+
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
|
|
135
|
+
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
|
|
136
|
+
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
|
|
137
|
+
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
|
|
138
|
+
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
|
|
139
|
+
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
|
|
140
|
+
logger,
|
|
141
|
+
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
|
|
142
|
+
opts: options.options
|
|
143
|
+
});
|
|
144
|
+
const fileEncSha256B64 = fileEncSha256.toString('base64');
|
|
145
|
+
const [{ mediaUrl, directPath }] = await Promise.all([
|
|
146
|
+
(async () => {
|
|
147
|
+
const result = await options.upload(encFilePath, {
|
|
148
|
+
fileEncSha256B64,
|
|
149
|
+
mediaType,
|
|
150
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
151
|
+
});
|
|
152
|
+
logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
|
|
153
|
+
return result;
|
|
154
|
+
})(),
|
|
155
|
+
(async () => {
|
|
156
|
+
try {
|
|
157
|
+
if (requiresThumbnailComputation) {
|
|
158
|
+
const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
|
|
159
|
+
uploadData.jpegThumbnail = thumbnail;
|
|
160
|
+
if (!uploadData.width && originalImageDimensions) {
|
|
161
|
+
uploadData.width = originalImageDimensions.width;
|
|
162
|
+
uploadData.height = originalImageDimensions.height;
|
|
163
|
+
logger?.debug('set dimensions');
|
|
164
|
+
}
|
|
165
|
+
logger?.debug('generated thumbnail');
|
|
166
|
+
}
|
|
167
|
+
if (requiresDurationComputation) {
|
|
168
|
+
uploadData.seconds = await getAudioDuration(originalFilePath);
|
|
169
|
+
logger?.debug('computed audio duration');
|
|
170
|
+
}
|
|
171
|
+
if (requiresWaveformProcessing) {
|
|
172
|
+
uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
|
|
173
|
+
logger?.debug('processed waveform');
|
|
174
|
+
}
|
|
175
|
+
if (requiresAudioBackground) {
|
|
176
|
+
uploadData.backgroundArgb = await assertColor(options.backgroundColor);
|
|
177
|
+
logger?.debug('computed backgroundColor audio status');
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
|
|
182
|
+
}
|
|
183
|
+
})()
|
|
184
|
+
]).finally(async () => {
|
|
185
|
+
try {
|
|
186
|
+
await fs.unlink(encFilePath);
|
|
187
|
+
if (originalFilePath) {
|
|
188
|
+
await fs.unlink(originalFilePath);
|
|
189
|
+
}
|
|
190
|
+
logger?.debug('removed tmp files');
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
logger?.warn('failed to remove tmp file');
|
|
157
194
|
}
|
|
158
|
-
logger?.debug("generated thumbnail");
|
|
159
|
-
}
|
|
160
|
-
if (requiresDurationComputation) {
|
|
161
|
-
uploadData.seconds = await getAudioDuration(filePath);
|
|
162
|
-
logger?.debug("computed audio duration");
|
|
163
|
-
}
|
|
164
|
-
if (requiresWaveformProcessing) {
|
|
165
|
-
uploadData.waveform = await getAudioWaveform(filePath, logger);
|
|
166
|
-
logger?.debug("processed waveform");
|
|
167
|
-
}
|
|
168
|
-
if (requiresAudioBackground) {
|
|
169
|
-
uploadData.backgroundArgb = await assertColor(options.backgroundColor);
|
|
170
|
-
logger?.debug("computed backgroundColor audio status");
|
|
171
|
-
}
|
|
172
|
-
} catch (error) {
|
|
173
|
-
logger?.warn({ trace: error.stack }, "failed to obtain extra info");
|
|
174
|
-
}
|
|
175
|
-
const fileSha256B64 = fileSha256.toString("base64");
|
|
176
|
-
const { mediaUrl, directPath } = await options.upload(filePath, {
|
|
177
|
-
fileEncSha256B64: fileSha256B64,
|
|
178
|
-
mediaType: mediaType,
|
|
179
|
-
newsletter: true,
|
|
180
|
-
timeoutMs: options.mediaUploadTimeoutMs,
|
|
181
195
|
});
|
|
182
|
-
await fs.unlink(filePath);
|
|
183
196
|
const obj = WAProto.Message.fromObject({
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
197
|
+
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
198
|
+
url: mediaUrl,
|
|
199
|
+
directPath,
|
|
200
|
+
mediaKey,
|
|
201
|
+
fileEncSha256,
|
|
202
|
+
fileSha256,
|
|
203
|
+
fileLength,
|
|
204
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
205
|
+
...uploadData,
|
|
206
|
+
media: undefined
|
|
207
|
+
})
|
|
193
208
|
});
|
|
194
209
|
if (uploadData.ptv) {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
if (obj.stickerMessage) {
|
|
199
|
-
obj.stickerMessage.stickerSentTs = Date.now();
|
|
210
|
+
obj.ptvMessage = obj.videoMessage;
|
|
211
|
+
delete obj.videoMessage;
|
|
200
212
|
}
|
|
201
213
|
if (cacheableKey) {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
cacheableKey,
|
|
205
|
-
WAProto.Message.encode(obj).finish(),
|
|
206
|
-
);
|
|
214
|
+
logger?.debug({ cacheableKey }, 'set cache');
|
|
215
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
|
|
207
216
|
}
|
|
208
217
|
return obj;
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
const requiresAudioBackground =
|
|
220
|
-
options.backgroundColor && mediaType === "audio" && uploadData.ptt === true;
|
|
221
|
-
const requiresOriginalForSomeProcessing =
|
|
222
|
-
requiresDurationComputation ||
|
|
223
|
-
requiresThumbnailComputation ||
|
|
224
|
-
requiresWaveformProcessing;
|
|
225
|
-
const {
|
|
226
|
-
mediaKey,
|
|
227
|
-
encWriteStream,
|
|
228
|
-
bodyPath,
|
|
229
|
-
fileEncSha256,
|
|
230
|
-
fileSha256,
|
|
231
|
-
fileLength,
|
|
232
|
-
didSaveToTmpPath,
|
|
233
|
-
} = await encryptedStream(
|
|
234
|
-
uploadData.media,
|
|
235
|
-
options.mediaTypeOverride || mediaType,
|
|
236
|
-
{
|
|
237
|
-
logger,
|
|
238
|
-
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
|
|
239
|
-
opts: options.options,
|
|
240
|
-
},
|
|
241
|
-
);
|
|
242
|
-
const fileEncSha256B64 = fileEncSha256.toString("base64");
|
|
243
|
-
const [{ mediaUrl, directPath }] = await Promise.all([
|
|
244
|
-
(async () => {
|
|
245
|
-
const result = await options.upload(encWriteStream, {
|
|
246
|
-
fileEncSha256B64,
|
|
247
|
-
mediaType,
|
|
248
|
-
timeoutMs: options.mediaUploadTimeoutMs,
|
|
249
|
-
});
|
|
250
|
-
logger?.debug({ mediaType, cacheableKey }, "uploaded media");
|
|
251
|
-
return result;
|
|
252
|
-
})(),
|
|
253
|
-
(async () => {
|
|
254
|
-
try {
|
|
255
|
-
if (requiresThumbnailComputation) {
|
|
256
|
-
const { thumbnail, originalImageDimensions } =
|
|
257
|
-
await generateThumbnail(bodyPath, mediaType, options);
|
|
258
|
-
uploadData.jpegThumbnail = thumbnail;
|
|
259
|
-
if (!uploadData.width && originalImageDimensions) {
|
|
260
|
-
uploadData.width = originalImageDimensions.width;
|
|
261
|
-
uploadData.height = originalImageDimensions.height;
|
|
262
|
-
logger?.debug("set dimensions");
|
|
263
|
-
}
|
|
264
|
-
logger?.debug("generated thumbnail");
|
|
265
|
-
}
|
|
266
|
-
if (requiresDurationComputation) {
|
|
267
|
-
try {
|
|
268
|
-
if (bodyPath) {
|
|
269
|
-
uploadData.seconds = await getAudioDuration(bodyPath);
|
|
218
|
+
};
|
|
219
|
+
export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
|
|
220
|
+
ephemeralExpiration = ephemeralExpiration || 0;
|
|
221
|
+
const content = {
|
|
222
|
+
ephemeralMessage: {
|
|
223
|
+
message: {
|
|
224
|
+
protocolMessage: {
|
|
225
|
+
type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
226
|
+
ephemeralExpiration
|
|
227
|
+
}
|
|
270
228
|
}
|
|
271
|
-
} catch (err) {
|
|
272
|
-
uploadData.seconds = 0;
|
|
273
|
-
}
|
|
274
|
-
if (
|
|
275
|
-
typeof uploadData.seconds !== "number" ||
|
|
276
|
-
isNaN(uploadData.seconds)
|
|
277
|
-
) {
|
|
278
|
-
uploadData.seconds = 0;
|
|
279
|
-
}
|
|
280
|
-
logger?.debug("computed audio duration");
|
|
281
|
-
}
|
|
282
|
-
if (requiresWaveformProcessing) {
|
|
283
|
-
try {
|
|
284
|
-
uploadData.waveform = await getAudioWaveform(bodyPath, logger);
|
|
285
|
-
} catch (err) {}
|
|
286
|
-
if (!uploadData.waveform) {
|
|
287
|
-
uploadData.waveform = new Uint8Array([
|
|
288
|
-
0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0,
|
|
289
|
-
99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99,
|
|
290
|
-
]);
|
|
291
|
-
}
|
|
292
|
-
logger?.debug("processed waveform");
|
|
293
229
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
options.backgroundColor,
|
|
297
|
-
);
|
|
298
|
-
logger?.debug("computed backgroundColor audio status");
|
|
299
|
-
}
|
|
300
|
-
} catch (error) {
|
|
301
|
-
logger?.warn({ trace: error.stack }, "failed to obtain extra info");
|
|
302
|
-
}
|
|
303
|
-
})(),
|
|
304
|
-
]).finally(async () => {
|
|
305
|
-
try {
|
|
306
|
-
if (!Buffer.isBuffer(encWriteStream)) {
|
|
307
|
-
encWriteStream.destroy?.();
|
|
308
|
-
}
|
|
309
|
-
if (didSaveToTmpPath && bodyPath) {
|
|
310
|
-
await fs.unlink(bodyPath).catch(() => {});
|
|
311
|
-
}
|
|
312
|
-
} catch (error) {
|
|
313
|
-
logger?.warn("failed to remove tmp file");
|
|
314
|
-
}
|
|
315
|
-
});
|
|
316
|
-
const obj = WAProto.Message.fromObject({
|
|
317
|
-
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
318
|
-
url: mediaUrl,
|
|
319
|
-
directPath,
|
|
320
|
-
mediaKey,
|
|
321
|
-
fileEncSha256,
|
|
322
|
-
fileSha256,
|
|
323
|
-
fileLength,
|
|
324
|
-
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
325
|
-
...uploadData,
|
|
326
|
-
media: undefined,
|
|
327
|
-
}),
|
|
328
|
-
});
|
|
329
|
-
if (uploadData.ptv) {
|
|
330
|
-
obj.ptvMessage = obj.videoMessage;
|
|
331
|
-
delete obj.videoMessage;
|
|
332
|
-
}
|
|
333
|
-
if (obj.stickerMessage) {
|
|
334
|
-
obj.stickerMessage.stickerSentTs = Date.now();
|
|
335
|
-
}
|
|
336
|
-
if (cacheableKey) {
|
|
337
|
-
logger?.debug({ cacheableKey }, "set cache");
|
|
338
|
-
await options.mediaCache.set(
|
|
339
|
-
cacheableKey,
|
|
340
|
-
WAProto.Message.encode(obj).finish(),
|
|
341
|
-
);
|
|
342
|
-
}
|
|
343
|
-
return obj;
|
|
344
|
-
};
|
|
345
|
-
export const prepareDisappearingMessageSettingContent = (
|
|
346
|
-
ephemeralExpiration,
|
|
347
|
-
) => {
|
|
348
|
-
ephemeralExpiration = ephemeralExpiration || 0;
|
|
349
|
-
const content = {
|
|
350
|
-
ephemeralMessage: {
|
|
351
|
-
message: {
|
|
352
|
-
protocolMessage: {
|
|
353
|
-
type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
354
|
-
ephemeralExpiration,
|
|
355
|
-
},
|
|
356
|
-
},
|
|
357
|
-
},
|
|
358
|
-
};
|
|
359
|
-
return WAProto.Message.fromObject(content);
|
|
230
|
+
};
|
|
231
|
+
return WAProto.Message.fromObject(content);
|
|
360
232
|
};
|
|
361
233
|
/**
|
|
362
234
|
* Generate forwarded message content like WA does
|
|
@@ -364,579 +236,645 @@ export const prepareDisappearingMessageSettingContent = (
|
|
|
364
236
|
* @param options.forceForward will show the message as forwarded even if it is from you
|
|
365
237
|
*/
|
|
366
238
|
export const generateForwardMessageContent = (message, forceForward) => {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
239
|
+
let content = message.message;
|
|
240
|
+
if (!content) {
|
|
241
|
+
throw new Boom('no content in message', { statusCode: 400 });
|
|
242
|
+
}
|
|
243
|
+
// hacky copy
|
|
244
|
+
content = normalizeMessageContent(content);
|
|
245
|
+
content = proto.Message.decode(proto.Message.encode(content).finish());
|
|
246
|
+
let key = Object.keys(content)[0];
|
|
247
|
+
let score = content?.[key]?.contextInfo?.forwardingScore || 0;
|
|
248
|
+
score += message.key.fromMe && !forceForward ? 0 : 1;
|
|
249
|
+
if (key === 'conversation') {
|
|
250
|
+
content.extendedTextMessage = { text: content[key] };
|
|
251
|
+
delete content.conversation;
|
|
252
|
+
key = 'extendedTextMessage';
|
|
253
|
+
}
|
|
254
|
+
const key_ = content?.[key];
|
|
255
|
+
if (score > 0) {
|
|
256
|
+
key_.contextInfo = { forwardingScore: score, isForwarded: true };
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
key_.contextInfo = {};
|
|
260
|
+
}
|
|
261
|
+
return content;
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Normalize a community-style `buttons` / `templateButtons` / `interactiveButtons` array
|
|
265
|
+
* into WhatsApp's modern native flow button shape: `{ name, buttonParamsJson }`.
|
|
266
|
+
*
|
|
267
|
+
* Accepts, per button:
|
|
268
|
+
* - Already-normalized native flow shape: { name, buttonParamsJson }
|
|
269
|
+
* - Legacy quick-reply shape: { buttonId, buttonText: { displayText } }
|
|
270
|
+
* - Simple shape: { id, text } or { id, displayText }
|
|
271
|
+
* - Legacy template button shapes: { urlButton: { displayText, url } },
|
|
272
|
+
* { callButton: { displayText, phoneNumber } }, { quickReplyButton: { displayText, id } }
|
|
273
|
+
*/
|
|
274
|
+
export const normalizeToNativeFlowButtons = (buttons) => {
|
|
275
|
+
if (!Array.isArray(buttons)) return [];
|
|
276
|
+
return buttons.map((b) => {
|
|
277
|
+
if (!b || typeof b !== 'object') return null;
|
|
278
|
+
// Already in native flow shape
|
|
279
|
+
if (typeof b.name === 'string' && typeof b.buttonParamsJson === 'string') {
|
|
280
|
+
return { name: b.name, buttonParamsJson: b.buttonParamsJson };
|
|
281
|
+
}
|
|
282
|
+
// Legacy template button wrapper shapes
|
|
283
|
+
if (b.urlButton) {
|
|
284
|
+
return {
|
|
285
|
+
name: 'cta_url',
|
|
286
|
+
buttonParamsJson: JSON.stringify({
|
|
287
|
+
display_text: b.urlButton.displayText,
|
|
288
|
+
url: b.urlButton.url
|
|
289
|
+
})
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
if (b.callButton) {
|
|
293
|
+
return {
|
|
294
|
+
name: 'cta_call',
|
|
295
|
+
buttonParamsJson: JSON.stringify({
|
|
296
|
+
display_text: b.callButton.displayText,
|
|
297
|
+
id: b.callButton.phoneNumber
|
|
298
|
+
})
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
if (b.quickReplyButton) {
|
|
302
|
+
return {
|
|
303
|
+
name: 'quick_reply',
|
|
304
|
+
buttonParamsJson: JSON.stringify({
|
|
305
|
+
display_text: b.quickReplyButton.displayText,
|
|
306
|
+
id: b.quickReplyButton.id
|
|
307
|
+
})
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
// Legacy `buttonId` + `buttonText.displayText` (classic buttonsMessage shape)
|
|
311
|
+
if (b.buttonId || b.buttonText) {
|
|
312
|
+
return {
|
|
313
|
+
name: 'quick_reply',
|
|
314
|
+
buttonParamsJson: JSON.stringify({
|
|
315
|
+
display_text: b.buttonText?.displayText || b.displayText || '',
|
|
316
|
+
id: b.buttonId || b.id || generateMessageID()
|
|
317
|
+
})
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
// Simple { id, text } or { id, displayText }
|
|
321
|
+
if (b.id && (b.text || b.displayText)) {
|
|
322
|
+
return {
|
|
323
|
+
name: 'quick_reply',
|
|
324
|
+
buttonParamsJson: JSON.stringify({
|
|
325
|
+
display_text: b.text || b.displayText,
|
|
326
|
+
id: b.id
|
|
327
|
+
})
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
return null;
|
|
331
|
+
}).filter(Boolean);
|
|
332
|
+
};
|
|
333
|
+
/**
|
|
334
|
+
* Wraps interactive/button/list/product messages in a viewOnceMessage with
|
|
335
|
+
* deviceListMetadataVersion set. This matches the convention used by most community
|
|
336
|
+
* Baileys forks (baileys-pro, FizzxyDev, indraazy, etc) and by this bot's own `simple.js`
|
|
337
|
+
* helpers (sendBut/sendList).
|
|
338
|
+
*
|
|
339
|
+
* NOTE: this wrapper alone is NOT sufficient for buttons to render — WhatsApp's server
|
|
340
|
+
* also needs the `<biz><interactive/></biz>` binary node hint, which is NOT part of the
|
|
341
|
+
* message content and must be passed separately via `additionalNodes` to relayMessage().
|
|
342
|
+
* See `buildInteractiveAdditionalNodes()` below, which messages-send.js's sendMessage()
|
|
343
|
+
* and Socket/dugong.js both call for this exact reason.
|
|
344
|
+
*
|
|
345
|
+
* Safe to call on any message content object `m`. No-ops if `m` is already wrapped,
|
|
346
|
+
* or doesn't need wrapping.
|
|
347
|
+
*/
|
|
348
|
+
export const patchInteractiveMessage = (m) => {
|
|
349
|
+
if (!m || typeof m !== 'object') return m;
|
|
350
|
+
const needsInteractivePatch = !m.viewOnceMessage && (
|
|
351
|
+
m.interactiveMessage ||
|
|
352
|
+
m.buttonsMessage ||
|
|
353
|
+
m.templateMessage ||
|
|
354
|
+
m.listMessage ||
|
|
355
|
+
m.productMessage
|
|
356
|
+
);
|
|
357
|
+
if (!needsInteractivePatch) return m;
|
|
358
|
+
const { messageContextInfo: existingContextInfo, ...rest } = m;
|
|
359
|
+
return {
|
|
360
|
+
viewOnceMessage: {
|
|
361
|
+
message: {
|
|
362
|
+
...rest,
|
|
363
|
+
messageContextInfo: {
|
|
364
|
+
deviceListMetadata: {},
|
|
365
|
+
deviceListMetadataVersion: 2,
|
|
366
|
+
...existingContextInfo
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
/**
|
|
373
|
+
* Build the `additionalNodes` required for interactive/button/list messages to actually
|
|
374
|
+
* render on the recipient's client. WhatsApp's server uses these binary node hints
|
|
375
|
+
* (<biz><interactive .../></biz> or <biz><list .../></biz>, plus <bot biz_bot="1"/> for
|
|
376
|
+
* 1:1 chats) to decide whether to treat the message as an interactive flow — without them
|
|
377
|
+
* the message still delivers, but renders empty/invisible on most clients.
|
|
378
|
+
*
|
|
379
|
+
* @param {string} jid - destination jid (used to detect group vs 1:1)
|
|
380
|
+
* @param {object} m - the message content object, e.g. { interactiveMessage: {...} } or
|
|
381
|
+
* one already unwrapped from a viewOnceMessage (pass the inner message).
|
|
382
|
+
* @returns {Array<object>} additionalNodes to pass into relayMessage()
|
|
383
|
+
*/
|
|
384
|
+
export const buildInteractiveAdditionalNodes = (jid, m) => {
|
|
385
|
+
if (!m || typeof m !== 'object') return [];
|
|
386
|
+
const inner = m.viewOnceMessage?.message || m.viewOnceMessageV2?.message || m;
|
|
387
|
+
const nodes = [];
|
|
388
|
+
const group = isJidGroup(jid);
|
|
389
|
+
if (inner.listMessage) {
|
|
390
|
+
nodes.push({
|
|
391
|
+
tag: 'biz',
|
|
392
|
+
attrs: {},
|
|
393
|
+
content: [{ tag: 'list', attrs: { type: 'product_list', v: '2' } }]
|
|
394
|
+
});
|
|
395
|
+
} else if (inner.interactiveMessage || inner.buttonsMessage || inner.templateMessage || inner.productMessage) {
|
|
396
|
+
const isCarousel = !!inner.interactiveMessage?.carouselMessage;
|
|
397
|
+
nodes.push({
|
|
398
|
+
tag: 'biz',
|
|
399
|
+
attrs: {},
|
|
400
|
+
content: [{
|
|
401
|
+
tag: 'interactive',
|
|
402
|
+
attrs: { type: 'native_flow', v: '1' },
|
|
403
|
+
content: [{ tag: 'native_flow', attrs: { name: isCarousel ? 'carousel' : 'mixed', v: '9' } }]
|
|
404
|
+
}]
|
|
405
|
+
});
|
|
406
|
+
} else if (inner.groupStatusMessageV2) {
|
|
407
|
+
if (group) nodes.push({ tag: 'meta', attrs: { is_vsn2: '1' } });
|
|
408
|
+
}
|
|
409
|
+
if (nodes.length > 0 && !group) {
|
|
410
|
+
nodes.push({ tag: 'bot', attrs: { biz_bot: '1' } });
|
|
411
|
+
}
|
|
412
|
+
return nodes;
|
|
389
413
|
};
|
|
390
414
|
export const hasNonNullishProperty = (message, key) => {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
message[key] !== undefined
|
|
397
|
-
);
|
|
415
|
+
return (typeof message === 'object' &&
|
|
416
|
+
message !== null &&
|
|
417
|
+
key in message &&
|
|
418
|
+
message[key] !== null &&
|
|
419
|
+
message[key] !== undefined);
|
|
398
420
|
};
|
|
399
421
|
function hasOptionalProperty(obj, key) {
|
|
400
|
-
|
|
401
|
-
typeof obj === "object" && obj !== null && key in obj && obj[key] !== null
|
|
402
|
-
);
|
|
422
|
+
return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
|
|
403
423
|
}
|
|
404
424
|
export const generateWAMessageContent = async (message, options) => {
|
|
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
|
-
message.
|
|
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
|
-
|
|
425
|
+
var _a, _b;
|
|
426
|
+
let m = {};
|
|
427
|
+
if (hasNonNullishProperty(message, 'text')) {
|
|
428
|
+
const extContent = { text: message.text };
|
|
429
|
+
let urlInfo = message.linkPreview;
|
|
430
|
+
if (typeof urlInfo === 'undefined') {
|
|
431
|
+
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
|
|
432
|
+
}
|
|
433
|
+
if (urlInfo) {
|
|
434
|
+
extContent.matchedText = urlInfo['matched-text'];
|
|
435
|
+
extContent.jpegThumbnail = urlInfo.jpegThumbnail;
|
|
436
|
+
extContent.description = urlInfo.description;
|
|
437
|
+
extContent.title = urlInfo.title;
|
|
438
|
+
extContent.previewType = 0;
|
|
439
|
+
const img = urlInfo.highQualityThumbnail;
|
|
440
|
+
if (img) {
|
|
441
|
+
extContent.thumbnailDirectPath = img.directPath;
|
|
442
|
+
extContent.mediaKey = img.mediaKey;
|
|
443
|
+
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
|
|
444
|
+
extContent.thumbnailWidth = img.width;
|
|
445
|
+
extContent.thumbnailHeight = img.height;
|
|
446
|
+
extContent.thumbnailSha256 = img.fileSha256;
|
|
447
|
+
extContent.thumbnailEncSha256 = img.fileEncSha256;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (options.backgroundColor) {
|
|
451
|
+
extContent.backgroundArgb = await assertColor(options.backgroundColor);
|
|
452
|
+
}
|
|
453
|
+
if (options.font) {
|
|
454
|
+
extContent.font = options.font;
|
|
455
|
+
}
|
|
456
|
+
m.extendedTextMessage = extContent;
|
|
457
|
+
}
|
|
458
|
+
else if (hasNonNullishProperty(message, 'contacts')) {
|
|
459
|
+
const contactLen = message.contacts.contacts.length;
|
|
460
|
+
if (!contactLen) {
|
|
461
|
+
throw new Boom('require atleast 1 contact', { statusCode: 400 });
|
|
462
|
+
}
|
|
463
|
+
if (contactLen === 1) {
|
|
464
|
+
m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
else if (hasNonNullishProperty(message, 'location')) {
|
|
471
|
+
m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
|
|
472
|
+
}
|
|
473
|
+
else if (hasNonNullishProperty(message, 'react')) {
|
|
474
|
+
if (!message.react.senderTimestampMs) {
|
|
475
|
+
message.react.senderTimestampMs = Date.now();
|
|
476
|
+
}
|
|
477
|
+
m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
|
|
478
|
+
}
|
|
479
|
+
else if (hasNonNullishProperty(message, 'delete')) {
|
|
480
|
+
m.protocolMessage = {
|
|
481
|
+
key: message.delete,
|
|
482
|
+
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
else if (hasNonNullishProperty(message, 'forward')) {
|
|
486
|
+
m = generateForwardMessageContent(message.forward, message.force);
|
|
487
|
+
}
|
|
488
|
+
else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
|
|
489
|
+
const exp = typeof message.disappearingMessagesInChat === 'boolean'
|
|
490
|
+
? message.disappearingMessagesInChat
|
|
491
|
+
? WA_DEFAULT_EPHEMERAL
|
|
492
|
+
: 0
|
|
493
|
+
: message.disappearingMessagesInChat;
|
|
494
|
+
m = prepareDisappearingMessageSettingContent(exp);
|
|
495
|
+
}
|
|
496
|
+
else if (hasNonNullishProperty(message, 'groupInvite')) {
|
|
497
|
+
m.groupInviteMessage = {};
|
|
498
|
+
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
|
|
499
|
+
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
|
|
500
|
+
m.groupInviteMessage.caption = message.groupInvite.text;
|
|
501
|
+
m.groupInviteMessage.groupJid = message.groupInvite.jid;
|
|
502
|
+
m.groupInviteMessage.groupName = message.groupInvite.subject;
|
|
503
|
+
//TODO: use built-in interface and get disappearing mode info etc.
|
|
504
|
+
//TODO: cache / use store!?
|
|
505
|
+
if (options.getProfilePicUrl) {
|
|
506
|
+
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
|
|
507
|
+
if (pfpUrl) {
|
|
508
|
+
const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
|
|
509
|
+
if (resp.ok) {
|
|
510
|
+
const buf = Buffer.from(await resp.arrayBuffer());
|
|
511
|
+
m.groupInviteMessage.jpegThumbnail = buf;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
else if (hasNonNullishProperty(message, 'pin')) {
|
|
517
|
+
m.pinInChatMessage = {};
|
|
518
|
+
m.messageContextInfo = {};
|
|
519
|
+
m.pinInChatMessage.key = message.pin;
|
|
520
|
+
m.pinInChatMessage.type = message.type;
|
|
521
|
+
m.pinInChatMessage.senderTimestampMs = Date.now();
|
|
522
|
+
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
|
|
523
|
+
}
|
|
524
|
+
else if (hasNonNullishProperty(message, 'buttonReply')) {
|
|
525
|
+
switch (message.type) {
|
|
526
|
+
case 'template':
|
|
527
|
+
m.templateButtonReplyMessage = {
|
|
528
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
529
|
+
selectedId: message.buttonReply.id,
|
|
530
|
+
selectedIndex: message.buttonReply.index
|
|
531
|
+
};
|
|
532
|
+
break;
|
|
533
|
+
case 'plain':
|
|
534
|
+
m.buttonsResponseMessage = {
|
|
535
|
+
selectedButtonId: message.buttonReply.id,
|
|
536
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
537
|
+
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
|
538
|
+
};
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
|
|
543
|
+
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
|
|
544
|
+
m.ptvMessage = videoMessage;
|
|
545
|
+
}
|
|
546
|
+
else if (hasNonNullishProperty(message, 'product')) {
|
|
547
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
|
|
548
|
+
m.productMessage = WAProto.Message.ProductMessage.create({
|
|
549
|
+
...message,
|
|
550
|
+
product: {
|
|
551
|
+
...message.product,
|
|
552
|
+
productImage: imageMessage
|
|
553
|
+
}
|
|
501
554
|
});
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
555
|
+
}
|
|
556
|
+
else if (hasNonNullishProperty(message, 'listReply')) {
|
|
557
|
+
m.listResponseMessage = { ...message.listReply };
|
|
558
|
+
}
|
|
559
|
+
else if (hasNonNullishProperty(message, 'event')) {
|
|
560
|
+
m.eventMessage = {};
|
|
561
|
+
const startTime = Math.floor(message.event.startDate.getTime() / 1000);
|
|
562
|
+
if (message.event.call && options.getCallLink) {
|
|
563
|
+
const token = await options.getCallLink(message.event.call, { startTime });
|
|
564
|
+
m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
|
|
505
565
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
m.pinInChatMessage = {};
|
|
510
|
-
m.messageContextInfo = {};
|
|
511
|
-
m.pinInChatMessage.key = message.pin;
|
|
512
|
-
m.pinInChatMessage.type = message.type;
|
|
513
|
-
m.pinInChatMessage.senderTimestampMs = Date.now();
|
|
514
|
-
m.messageContextInfo.messageAddOnDurationInSecs =
|
|
515
|
-
message.type === 1 ? message.time || 86400 : 0;
|
|
516
|
-
} else if (hasNonNullishProperty(message, "buttonReply")) {
|
|
517
|
-
switch (message.type) {
|
|
518
|
-
case "template":
|
|
519
|
-
m.templateButtonReplyMessage = {
|
|
520
|
-
selectedDisplayText: message.buttonReply.displayText,
|
|
521
|
-
selectedId: message.buttonReply.id,
|
|
522
|
-
selectedIndex: message.buttonReply.index,
|
|
566
|
+
m.messageContextInfo = {
|
|
567
|
+
// encKey
|
|
568
|
+
messageSecret: message.event.messageSecret || randomBytes(32)
|
|
523
569
|
};
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
m.
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
570
|
+
m.eventMessage.name = message.event.name;
|
|
571
|
+
m.eventMessage.description = message.event.description;
|
|
572
|
+
m.eventMessage.startTime = startTime;
|
|
573
|
+
m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
|
|
574
|
+
m.eventMessage.isCanceled = message.event.isCancelled ?? false;
|
|
575
|
+
m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
|
|
576
|
+
m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
|
|
577
|
+
m.eventMessage.location = message.event.location;
|
|
578
|
+
}
|
|
579
|
+
else if (hasNonNullishProperty(message, 'poll')) {
|
|
580
|
+
(_a = message.poll).selectableCount || (_a.selectableCount = 0);
|
|
581
|
+
(_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
|
|
582
|
+
if (!Array.isArray(message.poll.values)) {
|
|
583
|
+
throw new Boom('Invalid poll values', { statusCode: 400 });
|
|
584
|
+
}
|
|
585
|
+
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
|
586
|
+
throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
|
|
587
|
+
statusCode: 400
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
m.messageContextInfo = {
|
|
591
|
+
// encKey
|
|
592
|
+
messageSecret: message.poll.messageSecret || randomBytes(32)
|
|
530
593
|
};
|
|
531
|
-
|
|
594
|
+
const pollCreationMessage = {
|
|
595
|
+
name: message.poll.name,
|
|
596
|
+
selectableOptionsCount: message.poll.selectableCount,
|
|
597
|
+
options: message.poll.values.map(optionName => ({ optionName }))
|
|
598
|
+
};
|
|
599
|
+
if (message.poll.toAnnouncementGroup) {
|
|
600
|
+
// poll v2 is for community announcement groups (single select and multiple)
|
|
601
|
+
m.pollCreationMessageV2 = pollCreationMessage;
|
|
602
|
+
}
|
|
603
|
+
else {
|
|
604
|
+
if (message.poll.selectableCount === 1) {
|
|
605
|
+
//poll v3 is for single select polls
|
|
606
|
+
m.pollCreationMessageV3 = pollCreationMessage;
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
// poll for multiple choice polls
|
|
610
|
+
m.pollCreationMessage = pollCreationMessage;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
532
613
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
m.ptvMessage = videoMessage;
|
|
539
|
-
} else if (hasNonNullishProperty(message, "product")) {
|
|
540
|
-
const { imageMessage } = await prepareWAMessageMedia(
|
|
541
|
-
{ image: message.product.productImage },
|
|
542
|
-
options,
|
|
543
|
-
);
|
|
544
|
-
m.productMessage = WAProto.Message.ProductMessage.create({
|
|
545
|
-
...message,
|
|
546
|
-
product: {
|
|
547
|
-
...message.product,
|
|
548
|
-
productImage: imageMessage,
|
|
549
|
-
},
|
|
550
|
-
});
|
|
551
|
-
} else if (hasNonNullishProperty(message, "listReply")) {
|
|
552
|
-
m.listResponseMessage = { ...message.listReply };
|
|
553
|
-
} else if (hasNonNullishProperty(message, "event")) {
|
|
554
|
-
m.eventMessage = {};
|
|
555
|
-
const startTime = Math.floor(message.event.startDate.getTime() / 1000);
|
|
556
|
-
if (message.event.call && options.getCallLink) {
|
|
557
|
-
const token = await options.getCallLink(message.event.call, {
|
|
558
|
-
startTime,
|
|
559
|
-
});
|
|
560
|
-
m.eventMessage.joinLink =
|
|
561
|
-
(message.event.call === "audio"
|
|
562
|
-
? CALL_AUDIO_PREFIX
|
|
563
|
-
: CALL_VIDEO_PREFIX) + token;
|
|
564
|
-
}
|
|
565
|
-
m.messageContextInfo = {
|
|
566
|
-
// encKey
|
|
567
|
-
messageSecret: message.event.messageSecret || randomBytes(32),
|
|
568
|
-
};
|
|
569
|
-
m.eventMessage.name = message.event.name;
|
|
570
|
-
m.eventMessage.description = message.event.description;
|
|
571
|
-
m.eventMessage.startTime = startTime;
|
|
572
|
-
m.eventMessage.endTime = message.event.endDate
|
|
573
|
-
? message.event.endDate.getTime() / 1000
|
|
574
|
-
: undefined;
|
|
575
|
-
m.eventMessage.isCanceled = message.event.isCancelled ?? false;
|
|
576
|
-
m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
|
|
577
|
-
m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
|
|
578
|
-
m.eventMessage.location = message.event.location;
|
|
579
|
-
} else if (hasNonNullishProperty(message, "poll")) {
|
|
580
|
-
(_a = message.poll).selectableCount || (_a.selectableCount = 0);
|
|
581
|
-
(_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
|
|
582
|
-
if (!Array.isArray(message.poll.values)) {
|
|
583
|
-
throw new Boom("Invalid poll values", { statusCode: 400 });
|
|
614
|
+
else if (hasNonNullishProperty(message, 'album')) {
|
|
615
|
+
m.albumMessage = {
|
|
616
|
+
expectedImageCount: message.album.expectedImageCount,
|
|
617
|
+
expectedVideoCount: message.album.expectedVideoCount
|
|
618
|
+
};
|
|
584
619
|
}
|
|
585
|
-
if (
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
throw new Boom(
|
|
590
|
-
`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
|
|
591
|
-
{
|
|
592
|
-
statusCode: 400,
|
|
593
|
-
},
|
|
594
|
-
);
|
|
620
|
+
else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
|
|
621
|
+
m.protocolMessage = {
|
|
622
|
+
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
|
623
|
+
};
|
|
595
624
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
m
|
|
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
|
-
const isWebP = (buf) =>
|
|
651
|
-
buf.length >= 12 &&
|
|
652
|
-
buf[0] === 0x52 &&
|
|
653
|
-
buf[1] === 0x49 &&
|
|
654
|
-
buf[2] === 0x46 &&
|
|
655
|
-
buf[3] === 0x46 &&
|
|
656
|
-
buf[8] === 0x57 &&
|
|
657
|
-
buf[9] === 0x45 &&
|
|
658
|
-
buf[10] === 0x42 &&
|
|
659
|
-
buf[11] === 0x50;
|
|
660
|
-
const isAnimatedWebP = (buf) => {
|
|
661
|
-
if (!isWebP(buf)) return false;
|
|
662
|
-
let o = 12;
|
|
663
|
-
while (o < buf.length - 8) {
|
|
664
|
-
const tag = buf.toString("ascii", o, o + 4);
|
|
665
|
-
const sz = buf.readUInt32LE(o + 4);
|
|
666
|
-
if (tag === "VP8X" && buf[o + 8] & 0x02) return true;
|
|
667
|
-
if (tag === "ANIM" || tag === "ANMF") return true;
|
|
668
|
-
o += 8 + sz + (sz % 2);
|
|
669
|
-
}
|
|
670
|
-
return false;
|
|
671
|
-
};
|
|
672
|
-
const { Readable } = await import("stream");
|
|
673
|
-
const toReadable = (buf) => {
|
|
674
|
-
const r = new Readable({ read: () => {} });
|
|
675
|
-
r.push(buf);
|
|
676
|
-
r.push(null);
|
|
677
|
-
return r;
|
|
678
|
-
};
|
|
679
|
-
const toBuffer = async (stream) => {
|
|
680
|
-
const c = [];
|
|
681
|
-
for await (const ch of stream) c.push(ch);
|
|
682
|
-
return Buffer.concat(c);
|
|
683
|
-
};
|
|
684
|
-
const getStreamBuf = async (item) => {
|
|
685
|
-
if (Buffer.isBuffer(item)) return item;
|
|
686
|
-
if (item?.stream) return toBuffer(item.stream);
|
|
687
|
-
const u = item?.url?.toString?.() || item?.url;
|
|
688
|
-
if (u?.startsWith("data:")) return Buffer.from(u.split(",")[1], "base64");
|
|
689
|
-
const resp = await fetch(u);
|
|
690
|
-
return Buffer.from(await resp.arrayBuffer());
|
|
691
|
-
};
|
|
692
|
-
const zipData = {};
|
|
693
|
-
const stickerMeta = await Promise.all(
|
|
694
|
-
stickers.map(async (s, i) => {
|
|
695
|
-
const raw = await getStreamBuf(s.data || s.sticker);
|
|
696
|
-
let webp;
|
|
697
|
-
let animated = false;
|
|
698
|
-
if (isWebP(raw)) {
|
|
699
|
-
webp = raw;
|
|
700
|
-
animated = isAnimatedWebP(raw);
|
|
701
|
-
} else {
|
|
702
|
-
webp = await sharpLib(raw).webp().toBuffer();
|
|
625
|
+
else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
|
|
626
|
+
m.requestPhoneNumberMessage = {};
|
|
627
|
+
}
|
|
628
|
+
else if (hasNonNullishProperty(message, 'limitSharing')) {
|
|
629
|
+
m.protocolMessage = {
|
|
630
|
+
type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
|
|
631
|
+
limitSharing: {
|
|
632
|
+
sharingLimited: message.limitSharing === true,
|
|
633
|
+
trigger: 1,
|
|
634
|
+
limitSharingSettingTimestamp: Date.now(),
|
|
635
|
+
initiatedByMe: true
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
m = await prepareWAMessageMedia(message, options);
|
|
641
|
+
}
|
|
642
|
+
// Convenience layer: `buttons` / `templateButtons` / `interactiveButtons` (top-level shorthand,
|
|
643
|
+
// as used by most community Baileys forks) are converted into a modern `interactiveMessage`
|
|
644
|
+
// with `nativeFlowMessage` buttons. We intentionally do NOT emit legacy `buttonsMessage` /
|
|
645
|
+
// `templateMessage` (hydratedTemplate) — those were deprecated by WhatsApp and were the
|
|
646
|
+
// subject of a spoofing security advisory upstream; native flow is the only supported path.
|
|
647
|
+
if (hasNonNullishProperty(message, 'interactiveButtons') ||
|
|
648
|
+
hasNonNullishProperty(message, 'buttons') ||
|
|
649
|
+
hasNonNullishProperty(message, 'templateButtons')) {
|
|
650
|
+
const rawButtons = message.interactiveButtons || message.buttons || message.templateButtons;
|
|
651
|
+
const nativeButtons = normalizeToNativeFlowButtons(rawButtons);
|
|
652
|
+
const existingType = Object.keys(m)[0];
|
|
653
|
+
const existingContent = existingType ? m[existingType] : undefined;
|
|
654
|
+
const interactiveMessage = {
|
|
655
|
+
body: {
|
|
656
|
+
text: message.text || message.caption || ''
|
|
657
|
+
},
|
|
658
|
+
footer: {
|
|
659
|
+
text: message.footer || ''
|
|
660
|
+
},
|
|
661
|
+
nativeFlowMessage: {
|
|
662
|
+
buttons: nativeButtons
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
// If a media/caption type was generated above (image, video, document, etc.),
|
|
666
|
+
// attach it as the interactive header so the media still displays.
|
|
667
|
+
if (existingContent && existingType !== 'extendedTextMessage' && existingType !== 'conversation') {
|
|
668
|
+
interactiveMessage.header = {
|
|
669
|
+
title: message.title || '',
|
|
670
|
+
hasMediaAttachment: true,
|
|
671
|
+
...existingContent
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
else if (message.title) {
|
|
675
|
+
interactiveMessage.header = {
|
|
676
|
+
title: message.title,
|
|
677
|
+
hasMediaAttachment: false
|
|
678
|
+
};
|
|
703
679
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
680
|
+
m = { interactiveMessage };
|
|
681
|
+
}
|
|
682
|
+
else if (hasNonNullishProperty(message, 'sections')) {
|
|
683
|
+
// Convenience: top-level `sections` shorthand -> listMessage (single select list)
|
|
684
|
+
m = {
|
|
685
|
+
listMessage: {
|
|
686
|
+
sections: message.sections,
|
|
687
|
+
buttonText: message.buttonText,
|
|
688
|
+
title: message.title,
|
|
689
|
+
footerText: message.footer,
|
|
690
|
+
description: message.text || message.caption,
|
|
691
|
+
listType: proto.Message.ListMessage.ListType.SINGLE_SELECT
|
|
692
|
+
}
|
|
715
693
|
};
|
|
716
|
-
|
|
717
|
-
)
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
m = {
|
|
819
|
-
protocolMessage: {
|
|
820
|
-
key: message.edit,
|
|
821
|
-
editedMessage: m,
|
|
822
|
-
timestampMs: Date.now(),
|
|
823
|
-
type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
|
|
824
|
-
},
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
if (hasOptionalProperty(message, "contextInfo") && !!message.contextInfo) {
|
|
828
|
-
const messageType = Object.keys(m)[0];
|
|
829
|
-
const key = m[messageType];
|
|
830
|
-
if ("contextInfo" in key && !!key.contextInfo) {
|
|
831
|
-
key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
|
|
832
|
-
} else if (key) {
|
|
833
|
-
key.contextInfo = message.contextInfo;
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
if (shouldIncludeReportingToken(m)) {
|
|
837
|
-
m.messageContextInfo = m.messageContextInfo || {};
|
|
838
|
-
if (!m.messageContextInfo.messageSecret) {
|
|
839
|
-
m.messageContextInfo.messageSecret = randomBytes(32);
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
return WAProto.Message.create(m);
|
|
694
|
+
}
|
|
695
|
+
else if (hasNonNullishProperty(message, 'cards')) {
|
|
696
|
+
// Convenience: top-level `cards` shorthand -> interactiveMessage.carouselMessage
|
|
697
|
+
// (horizontal-scroll product/card carousel). Each entry in `cards` may contain:
|
|
698
|
+
// { image | video, title?, body?, footer?, buttons? }
|
|
699
|
+
// `buttons` per card accepts the same shapes as the top-level `buttons` shorthand.
|
|
700
|
+
if (!Array.isArray(message.cards) || !message.cards.length) {
|
|
701
|
+
throw new Boom('cards must be a non-empty array', { statusCode: 400 });
|
|
702
|
+
}
|
|
703
|
+
const cards = await Promise.all(message.cards.map(async (card) => {
|
|
704
|
+
const cardButtons = normalizeToNativeFlowButtons(card.interactiveButtons || card.buttons || card.templateButtons || []);
|
|
705
|
+
const cardInteractive = {
|
|
706
|
+
body: { text: card.text || card.body || card.caption || '' },
|
|
707
|
+
footer: { text: card.footer || '' },
|
|
708
|
+
nativeFlowMessage: { buttons: cardButtons }
|
|
709
|
+
};
|
|
710
|
+
if (card.image || card.video) {
|
|
711
|
+
const mediaContent = await prepareWAMessageMedia(card.image ? { image: card.image } : { video: card.video }, options);
|
|
712
|
+
const mediaType = Object.keys(mediaContent)[0];
|
|
713
|
+
cardInteractive.header = {
|
|
714
|
+
title: card.title || '',
|
|
715
|
+
hasMediaAttachment: true,
|
|
716
|
+
...mediaContent[mediaType]
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
else if (card.title) {
|
|
720
|
+
cardInteractive.header = { title: card.title, hasMediaAttachment: false };
|
|
721
|
+
}
|
|
722
|
+
return cardInteractive;
|
|
723
|
+
}));
|
|
724
|
+
m = {
|
|
725
|
+
interactiveMessage: {
|
|
726
|
+
body: { text: message.text || message.caption || '' },
|
|
727
|
+
footer: { text: message.footer || '' },
|
|
728
|
+
carouselMessage: {
|
|
729
|
+
cards,
|
|
730
|
+
messageVersion: 1,
|
|
731
|
+
carouselCardType: proto.Message.InteractiveMessage.CarouselMessage.CarouselCardType.HSCROLL_CARDS
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
|
737
|
+
m = { viewOnceMessage: { message: m } };
|
|
738
|
+
}
|
|
739
|
+
if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
|
|
740
|
+
(hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
|
|
741
|
+
const messageType = Object.keys(m)[0];
|
|
742
|
+
const key = m[messageType];
|
|
743
|
+
if (key && 'contextInfo' in key) {
|
|
744
|
+
key.contextInfo = key.contextInfo || {};
|
|
745
|
+
if (message.mentions?.length) {
|
|
746
|
+
key.contextInfo.mentionedJid = message.mentions;
|
|
747
|
+
}
|
|
748
|
+
if (message.mentionAll) {
|
|
749
|
+
key.contextInfo.nonJidMentions = 1;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
else if (key) {
|
|
753
|
+
key.contextInfo = {
|
|
754
|
+
mentionedJid: message.mentions,
|
|
755
|
+
nonJidMentions: message.mentionAll ? 1 : 0
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
if (hasOptionalProperty(message, 'edit')) {
|
|
760
|
+
m = {
|
|
761
|
+
protocolMessage: {
|
|
762
|
+
key: message.edit,
|
|
763
|
+
editedMessage: m,
|
|
764
|
+
timestampMs: Date.now(),
|
|
765
|
+
type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
|
|
770
|
+
const messageType = Object.keys(m)[0];
|
|
771
|
+
const key = m[messageType];
|
|
772
|
+
if ('contextInfo' in key && !!key.contextInfo) {
|
|
773
|
+
key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
|
|
774
|
+
}
|
|
775
|
+
else if (key) {
|
|
776
|
+
key.contextInfo = message.contextInfo;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
|
|
780
|
+
m.messageContextInfo = {
|
|
781
|
+
...m.messageContextInfo,
|
|
782
|
+
messageAssociation: {
|
|
783
|
+
associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
|
|
784
|
+
parentMessageKey: message.albumParentKey
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
if (shouldIncludeReportingToken(m)) {
|
|
789
|
+
m.messageContextInfo = m.messageContextInfo || {};
|
|
790
|
+
if (!m.messageContextInfo.messageSecret) {
|
|
791
|
+
m.messageContextInfo.messageSecret = randomBytes(32);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
m = patchInteractiveMessage(m);
|
|
795
|
+
return WAProto.Message.create(m);
|
|
843
796
|
};
|
|
844
797
|
export const generateWAMessageFromContent = (jid, message, options) => {
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
798
|
+
// set timestamp to now
|
|
799
|
+
// if not specified
|
|
800
|
+
if (!options.timestamp) {
|
|
801
|
+
options.timestamp = new Date();
|
|
802
|
+
}
|
|
803
|
+
const innerMessage = normalizeMessageContent(message);
|
|
804
|
+
const key = getContentType(innerMessage);
|
|
805
|
+
const timestamp = unixTimestampSeconds(options.timestamp);
|
|
806
|
+
const { quoted, userJid } = options;
|
|
807
|
+
if (quoted && !isJidNewsletter(jid)) {
|
|
808
|
+
const participant = quoted.key.fromMe
|
|
809
|
+
? userJid // TODO: Add support for LIDs
|
|
810
|
+
: quoted.participant || quoted.key.participant || quoted.key.remoteJid;
|
|
811
|
+
let quotedMsg = normalizeMessageContent(quoted.message);
|
|
812
|
+
const msgType = getContentType(quotedMsg);
|
|
813
|
+
// strip any redundant properties
|
|
814
|
+
quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
|
|
815
|
+
const quotedContent = quotedMsg[msgType];
|
|
816
|
+
if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
|
|
817
|
+
delete quotedContent.contextInfo;
|
|
818
|
+
}
|
|
819
|
+
const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
|
|
820
|
+
contextInfo.participant = jidNormalizedUser(participant);
|
|
821
|
+
contextInfo.stanzaId = quoted.key.id;
|
|
822
|
+
contextInfo.quotedMessage = quotedMsg;
|
|
823
|
+
// if a participant is quoted, then it must be a group
|
|
824
|
+
// hence, remoteJid of group must also be entered
|
|
825
|
+
if (jid !== quoted.key.remoteJid) {
|
|
826
|
+
contextInfo.remoteJid = quoted.key.remoteJid;
|
|
827
|
+
}
|
|
828
|
+
if (contextInfo && innerMessage[key]) {
|
|
829
|
+
/* @ts-ignore */
|
|
830
|
+
innerMessage[key].contextInfo = contextInfo;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
863
833
|
if (
|
|
864
|
-
typeof quotedContent === "object" &&
|
|
865
|
-
quotedContent &&
|
|
866
|
-
"contextInfo" in quotedContent
|
|
867
|
-
) {
|
|
868
|
-
delete quotedContent.contextInfo;
|
|
869
|
-
}
|
|
870
|
-
const contextInfo =
|
|
871
|
-
("contextInfo" in innerMessage[key] && innerMessage[key]?.contextInfo) ||
|
|
872
|
-
{};
|
|
873
|
-
contextInfo.participant = jidNormalizedUser(participant);
|
|
874
|
-
contextInfo.stanzaId = quoted.key.id;
|
|
875
|
-
contextInfo.quotedMessage = quotedMsg;
|
|
876
|
-
// if a participant is quoted, then it must be a group
|
|
877
|
-
// hence, remoteJid of group must also be entered
|
|
878
|
-
if (jid !== quoted.key.remoteJid) {
|
|
879
|
-
contextInfo.remoteJid = quoted.key.remoteJid;
|
|
880
|
-
}
|
|
881
|
-
if (contextInfo && innerMessage[key]) {
|
|
882
|
-
/* @ts-ignore */
|
|
883
|
-
innerMessage[key].contextInfo = contextInfo;
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
if (
|
|
887
834
|
// if we want to send a disappearing message
|
|
888
835
|
!!options?.ephemeralExpiration &&
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
836
|
+
// and it's not a protocol message -- delete, toggle disappear message
|
|
837
|
+
key !== 'protocolMessage' &&
|
|
838
|
+
// already not converted to disappearing message
|
|
839
|
+
key !== 'ephemeralMessage' &&
|
|
840
|
+
// newsletters don't support ephemeral messages
|
|
841
|
+
!isJidNewsletter(jid)) {
|
|
842
|
+
/* @ts-ignore */
|
|
843
|
+
innerMessage[key].contextInfo = {
|
|
844
|
+
...(innerMessage[key].contextInfo || {}),
|
|
845
|
+
expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
|
|
846
|
+
//ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
message = patchInteractiveMessage(message);
|
|
850
|
+
message = WAProto.Message.create(message);
|
|
851
|
+
const messageJSON = {
|
|
852
|
+
key: {
|
|
853
|
+
remoteJid: jid,
|
|
854
|
+
fromMe: true,
|
|
855
|
+
id: options?.messageId || generateMessageIDV2()
|
|
856
|
+
},
|
|
857
|
+
message: message,
|
|
858
|
+
messageTimestamp: timestamp,
|
|
859
|
+
messageStubParameters: [],
|
|
860
|
+
participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
|
|
861
|
+
status: WAMessageStatus.PENDING
|
|
901
862
|
};
|
|
902
|
-
|
|
903
|
-
message = WAProto.Message.create(message);
|
|
904
|
-
const messageJSON = {
|
|
905
|
-
key: {
|
|
906
|
-
remoteJid: jid,
|
|
907
|
-
fromMe: true,
|
|
908
|
-
id: options?.messageId || generateMessageIDV2(),
|
|
909
|
-
},
|
|
910
|
-
message: message,
|
|
911
|
-
messageTimestamp: timestamp,
|
|
912
|
-
messageStubParameters: [],
|
|
913
|
-
participant:
|
|
914
|
-
isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
|
|
915
|
-
status: WAMessageStatus.PENDING,
|
|
916
|
-
};
|
|
917
|
-
return WAProto.WebMessageInfo.fromObject(messageJSON);
|
|
863
|
+
return WAProto.WebMessageInfo.fromObject(messageJSON);
|
|
918
864
|
};
|
|
919
865
|
export const generateWAMessage = async (jid, content, options) => {
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
jid,
|
|
925
|
-
await generateWAMessageContent(content, { ...options, jid }),
|
|
926
|
-
options,
|
|
927
|
-
);
|
|
866
|
+
// ensure msg ID is with every log
|
|
867
|
+
options.logger = options?.logger?.child({ msgId: options.messageId });
|
|
868
|
+
// Pass jid in the options to generateWAMessageContent
|
|
869
|
+
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
|
|
928
870
|
};
|
|
929
871
|
/** Get the key to access the true type of content */
|
|
930
872
|
export const getContentType = (content) => {
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
k !== "senderKeyDistributionMessage",
|
|
937
|
-
);
|
|
938
|
-
return key;
|
|
939
|
-
}
|
|
873
|
+
if (content) {
|
|
874
|
+
const keys = Object.keys(content);
|
|
875
|
+
const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
|
|
876
|
+
return key;
|
|
877
|
+
}
|
|
940
878
|
};
|
|
941
879
|
/**
|
|
942
880
|
* Normalizes ephemeral, view once messages to regular message content
|
|
@@ -945,132 +883,115 @@ export const getContentType = (content) => {
|
|
|
945
883
|
* @returns
|
|
946
884
|
*/
|
|
947
885
|
export const normalizeMessageContent = (content) => {
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
message?.groupStatusMessage ||
|
|
972
|
-
message?.groupStatusMessageV2
|
|
973
|
-
);
|
|
974
|
-
}
|
|
886
|
+
if (!content) {
|
|
887
|
+
return undefined;
|
|
888
|
+
}
|
|
889
|
+
// set max iterations to prevent an infinite loop
|
|
890
|
+
for (let i = 0; i < 5; i++) {
|
|
891
|
+
const inner = getFutureProofMessage(content);
|
|
892
|
+
if (!inner) {
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
content = inner.message;
|
|
896
|
+
}
|
|
897
|
+
return content;
|
|
898
|
+
function getFutureProofMessage(message) {
|
|
899
|
+
return (message?.ephemeralMessage ||
|
|
900
|
+
message?.viewOnceMessage ||
|
|
901
|
+
message?.documentWithCaptionMessage ||
|
|
902
|
+
message?.viewOnceMessageV2 ||
|
|
903
|
+
message?.viewOnceMessageV2Extension ||
|
|
904
|
+
message?.editedMessage ||
|
|
905
|
+
message?.associatedChildMessage ||
|
|
906
|
+
message?.groupStatusMessage ||
|
|
907
|
+
message?.groupStatusMessageV2);
|
|
908
|
+
}
|
|
975
909
|
};
|
|
976
910
|
/**
|
|
977
911
|
* Extract the true message content from a message
|
|
978
912
|
* Eg. extracts the inner message from a disappearing message/view once message
|
|
979
913
|
*/
|
|
980
914
|
export const extractMessageContent = (content) => {
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
}
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
}
|
|
1015
|
-
if (content?.templateMessage?.fourRowTemplate) {
|
|
1016
|
-
return extractFromTemplateMessage(
|
|
1017
|
-
content?.templateMessage?.fourRowTemplate,
|
|
1018
|
-
);
|
|
1019
|
-
}
|
|
1020
|
-
return content;
|
|
915
|
+
const extractFromTemplateMessage = (msg) => {
|
|
916
|
+
if (msg.imageMessage) {
|
|
917
|
+
return { imageMessage: msg.imageMessage };
|
|
918
|
+
}
|
|
919
|
+
else if (msg.documentMessage) {
|
|
920
|
+
return { documentMessage: msg.documentMessage };
|
|
921
|
+
}
|
|
922
|
+
else if (msg.videoMessage) {
|
|
923
|
+
return { videoMessage: msg.videoMessage };
|
|
924
|
+
}
|
|
925
|
+
else if (msg.locationMessage) {
|
|
926
|
+
return { locationMessage: msg.locationMessage };
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
return {
|
|
930
|
+
conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
content = normalizeMessageContent(content);
|
|
935
|
+
if (content?.buttonsMessage) {
|
|
936
|
+
return extractFromTemplateMessage(content.buttonsMessage);
|
|
937
|
+
}
|
|
938
|
+
if (content?.templateMessage?.hydratedFourRowTemplate) {
|
|
939
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
|
|
940
|
+
}
|
|
941
|
+
if (content?.templateMessage?.hydratedTemplate) {
|
|
942
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
|
|
943
|
+
}
|
|
944
|
+
if (content?.templateMessage?.fourRowTemplate) {
|
|
945
|
+
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
|
|
946
|
+
}
|
|
947
|
+
return content;
|
|
1021
948
|
};
|
|
1022
949
|
/**
|
|
1023
950
|
* Returns the device predicted by message ID
|
|
1024
951
|
*/
|
|
1025
|
-
export const getDevice = (id) =>
|
|
1026
|
-
|
|
1027
|
-
? "ios"
|
|
952
|
+
export const getDevice = (id) => /^3A.{18}$/.test(id)
|
|
953
|
+
? 'ios'
|
|
1028
954
|
: /^3E.{20}$/.test(id)
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
955
|
+
? 'web'
|
|
956
|
+
: /^(.{21}|.{32})$/.test(id)
|
|
957
|
+
? 'android'
|
|
958
|
+
: /^(3F|.{18}$)/.test(id)
|
|
959
|
+
? 'desktop'
|
|
960
|
+
: 'unknown';
|
|
1035
961
|
/** Upserts a receipt in the message */
|
|
1036
962
|
export const updateMessageWithReceipt = (msg, receipt) => {
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
963
|
+
msg.userReceipt = msg.userReceipt || [];
|
|
964
|
+
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
|
|
965
|
+
if (recp) {
|
|
966
|
+
Object.assign(recp, receipt);
|
|
967
|
+
}
|
|
968
|
+
else {
|
|
969
|
+
msg.userReceipt.push(receipt);
|
|
970
|
+
}
|
|
1044
971
|
};
|
|
1045
972
|
/** Update the message with a new reaction */
|
|
1046
973
|
export const updateMessageWithReaction = (msg, reaction) => {
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
reactions.push(reaction);
|
|
1053
|
-
msg.reactions = reactions;
|
|
974
|
+
const authorID = getKeyAuthor(reaction.key);
|
|
975
|
+
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
|
|
976
|
+
reaction.text = reaction.text || '';
|
|
977
|
+
reactions.push(reaction);
|
|
978
|
+
msg.reactions = reactions;
|
|
1054
979
|
};
|
|
1055
980
|
/** Update the message with a new poll update */
|
|
1056
981
|
export const updateMessageWithPollUpdate = (msg, update) => {
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
reactions
|
|
1063
|
-
}
|
|
1064
|
-
msg.pollUpdates = reactions;
|
|
982
|
+
const authorID = getKeyAuthor(update.pollUpdateMessageKey);
|
|
983
|
+
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
|
|
984
|
+
if (update.vote?.selectedOptions?.length) {
|
|
985
|
+
reactions.push(update);
|
|
986
|
+
}
|
|
987
|
+
msg.pollUpdates = reactions;
|
|
1065
988
|
};
|
|
1066
989
|
/** Update the message with a new event response */
|
|
1067
990
|
export const updateMessageWithEventResponse = (msg, update) => {
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
(
|
|
1071
|
-
|
|
1072
|
-
responses.push(update);
|
|
1073
|
-
msg.eventResponses = responses;
|
|
991
|
+
const authorID = getKeyAuthor(update.eventResponseMessageKey);
|
|
992
|
+
const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
|
|
993
|
+
responses.push(update);
|
|
994
|
+
msg.eventResponses = responses;
|
|
1074
995
|
};
|
|
1075
996
|
/**
|
|
1076
997
|
* Aggregates all poll updates in a poll.
|
|
@@ -1079,40 +1000,37 @@ export const updateMessageWithEventResponse = (msg, update) => {
|
|
|
1079
1000
|
* @returns A list of options & their voters
|
|
1080
1001
|
*/
|
|
1081
1002
|
export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
voters: [],
|
|
1092
|
-
};
|
|
1093
|
-
return acc;
|
|
1094
|
-
}, {});
|
|
1095
|
-
for (const update of pollUpdates || []) {
|
|
1096
|
-
const { vote } = update;
|
|
1097
|
-
if (!vote) {
|
|
1098
|
-
continue;
|
|
1099
|
-
}
|
|
1100
|
-
for (const option of vote.selectedOptions || []) {
|
|
1101
|
-
const hash = option.toString();
|
|
1102
|
-
let data = voteHashMap[hash];
|
|
1103
|
-
if (!data) {
|
|
1104
|
-
voteHashMap[hash] = {
|
|
1105
|
-
name: "Unknown",
|
|
1106
|
-
voters: [],
|
|
1003
|
+
const opts = message?.pollCreationMessage?.options ||
|
|
1004
|
+
message?.pollCreationMessageV2?.options ||
|
|
1005
|
+
message?.pollCreationMessageV3?.options ||
|
|
1006
|
+
[];
|
|
1007
|
+
const voteHashMap = opts.reduce((acc, opt) => {
|
|
1008
|
+
const hash = sha256(Buffer.from(opt.optionName || '')).toString();
|
|
1009
|
+
acc[hash] = {
|
|
1010
|
+
name: opt.optionName || '',
|
|
1011
|
+
voters: []
|
|
1107
1012
|
};
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1013
|
+
return acc;
|
|
1014
|
+
}, {});
|
|
1015
|
+
for (const update of pollUpdates || []) {
|
|
1016
|
+
const { vote } = update;
|
|
1017
|
+
if (!vote) {
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
1020
|
+
for (const option of vote.selectedOptions || []) {
|
|
1021
|
+
const hash = option.toString();
|
|
1022
|
+
let data = voteHashMap[hash];
|
|
1023
|
+
if (!data) {
|
|
1024
|
+
voteHashMap[hash] = {
|
|
1025
|
+
name: 'Unknown',
|
|
1026
|
+
voters: []
|
|
1027
|
+
};
|
|
1028
|
+
data = voteHashMap[hash];
|
|
1029
|
+
}
|
|
1030
|
+
voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return Object.values(voteHashMap);
|
|
1116
1034
|
}
|
|
1117
1035
|
/**
|
|
1118
1036
|
* Aggregates all event responses in an event message.
|
|
@@ -1121,120 +1039,102 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
|
|
|
1121
1039
|
* @returns A list of response types & their responders
|
|
1122
1040
|
*/
|
|
1123
1041
|
export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
}
|
|
1140
|
-
return Object.values(responseMap);
|
|
1042
|
+
const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
|
|
1043
|
+
const responseMap = {};
|
|
1044
|
+
for (const type of responseTypes) {
|
|
1045
|
+
responseMap[type] = {
|
|
1046
|
+
response: type,
|
|
1047
|
+
responders: []
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
for (const update of eventResponses || []) {
|
|
1051
|
+
const responseType = update.eventResponse || 'UNKNOWN';
|
|
1052
|
+
if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
|
|
1053
|
+
responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
return Object.values(responseMap);
|
|
1141
1057
|
}
|
|
1142
1058
|
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
|
|
1143
1059
|
export const aggregateMessageKeysNotFromMe = (keys) => {
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1060
|
+
const keyMap = {};
|
|
1061
|
+
for (const { remoteJid, id, participant, fromMe } of keys) {
|
|
1062
|
+
if (!fromMe) {
|
|
1063
|
+
const uqKey = `${remoteJid}:${participant || ''}`;
|
|
1064
|
+
if (!keyMap[uqKey]) {
|
|
1065
|
+
keyMap[uqKey] = {
|
|
1066
|
+
jid: remoteJid,
|
|
1067
|
+
participant: participant,
|
|
1068
|
+
messageIds: []
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
keyMap[uqKey].messageIds.push(id);
|
|
1072
|
+
}
|
|
1156
1073
|
}
|
|
1157
|
-
|
|
1158
|
-
return Object.values(keyMap);
|
|
1074
|
+
return Object.values(keyMap);
|
|
1159
1075
|
};
|
|
1160
1076
|
const REUPLOAD_REQUIRED_STATUS = [410, 404];
|
|
1161
1077
|
/**
|
|
1162
1078
|
* Downloads the given message. Throws an error if it's not a media message
|
|
1163
1079
|
*/
|
|
1164
1080
|
export const downloadMediaMessage = async (message, type, options, ctx) => {
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
mediaType,
|
|
1211
|
-
options,
|
|
1212
|
-
);
|
|
1213
|
-
if (type === "buffer") {
|
|
1214
|
-
const bufferArray = [];
|
|
1215
|
-
for await (const chunk of stream) {
|
|
1216
|
-
bufferArray.push(chunk);
|
|
1217
|
-
}
|
|
1218
|
-
return Buffer.concat(bufferArray);
|
|
1219
|
-
}
|
|
1220
|
-
return stream;
|
|
1221
|
-
}
|
|
1081
|
+
const result = await downloadMsg().catch(async (error) => {
|
|
1082
|
+
if (ctx &&
|
|
1083
|
+
typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
|
|
1084
|
+
REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
|
|
1085
|
+
ctx.logger.info({ key: message.key }, 'sending reupload media request...');
|
|
1086
|
+
// request reupload
|
|
1087
|
+
message = await ctx.reuploadRequest(message);
|
|
1088
|
+
const result = await downloadMsg();
|
|
1089
|
+
return result;
|
|
1090
|
+
}
|
|
1091
|
+
throw error;
|
|
1092
|
+
});
|
|
1093
|
+
return result;
|
|
1094
|
+
async function downloadMsg() {
|
|
1095
|
+
const mContent = extractMessageContent(message.message);
|
|
1096
|
+
if (!mContent) {
|
|
1097
|
+
throw new Boom('No message present', { statusCode: 400, data: message });
|
|
1098
|
+
}
|
|
1099
|
+
const contentType = getContentType(mContent);
|
|
1100
|
+
let mediaType = contentType?.replace('Message', '');
|
|
1101
|
+
const media = mContent[contentType];
|
|
1102
|
+
if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
|
1103
|
+
throw new Boom(`"${contentType}" message is not a media message`);
|
|
1104
|
+
}
|
|
1105
|
+
let download;
|
|
1106
|
+
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
|
1107
|
+
download = {
|
|
1108
|
+
directPath: media.thumbnailDirectPath,
|
|
1109
|
+
mediaKey: media.mediaKey
|
|
1110
|
+
};
|
|
1111
|
+
mediaType = 'thumbnail-link';
|
|
1112
|
+
}
|
|
1113
|
+
else {
|
|
1114
|
+
download = media;
|
|
1115
|
+
}
|
|
1116
|
+
const stream = await downloadContentFromMessage(download, mediaType, options);
|
|
1117
|
+
if (type === 'buffer') {
|
|
1118
|
+
const bufferArray = [];
|
|
1119
|
+
for await (const chunk of stream) {
|
|
1120
|
+
bufferArray.push(chunk);
|
|
1121
|
+
}
|
|
1122
|
+
return Buffer.concat(bufferArray);
|
|
1123
|
+
}
|
|
1124
|
+
return stream;
|
|
1125
|
+
}
|
|
1222
1126
|
};
|
|
1223
1127
|
/** Checks whether the given message is a media message; if it is returns the inner content */
|
|
1224
1128
|
export const assertMediaContent = (content) => {
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
data: content,
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
return mediaContent;
|
|
1129
|
+
content = extractMessageContent(content);
|
|
1130
|
+
const mediaContent = content?.documentMessage ||
|
|
1131
|
+
content?.imageMessage ||
|
|
1132
|
+
content?.videoMessage ||
|
|
1133
|
+
content?.audioMessage ||
|
|
1134
|
+
content?.stickerMessage;
|
|
1135
|
+
if (!mediaContent) {
|
|
1136
|
+
throw new Boom('given message is not a media message', { statusCode: 400, data: content });
|
|
1137
|
+
}
|
|
1138
|
+
return mediaContent;
|
|
1239
1139
|
};
|
|
1240
|
-
//# sourceMappingURL=messages.js.map
|
|
1140
|
+
//# sourceMappingURL=messages.js.map
|