@vinzsocket/baileys 3.3.2 → 3.3.13

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.
Files changed (212) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1337 -2685
  3. package/WAProto/WAProto.proto +916 -360
  4. package/WAProto/fix-imports.js +18 -22
  5. package/WAProto/index.d.ts +0 -14015
  6. package/WAProto/index.js +80576 -45941
  7. package/lib/Defaults/index.d.ts +14 -15
  8. package/lib/Defaults/index.d.ts.map +1 -1
  9. package/lib/Defaults/index.js +109 -98
  10. package/lib/Defaults/index.js.map +1 -1
  11. package/lib/Signal/Group/group_cipher.js.map +1 -1
  12. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  13. package/lib/Signal/Group/keyhelper.js.map +1 -1
  14. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  15. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  16. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  17. package/lib/Signal/libsignal.d.ts.map +1 -1
  18. package/lib/Signal/libsignal.js +17 -45
  19. package/lib/Signal/libsignal.js.map +1 -1
  20. package/lib/Signal/lid-mapping.d.ts +0 -4
  21. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  22. package/lib/Signal/lid-mapping.js +0 -6
  23. package/lib/Signal/lid-mapping.js.map +1 -1
  24. package/lib/Socket/business.d.ts +532 -213
  25. package/lib/Socket/business.d.ts.map +1 -1
  26. package/lib/Socket/business.js +401 -358
  27. package/lib/Socket/chats.d.ts +2 -15
  28. package/lib/Socket/chats.d.ts.map +1 -1
  29. package/lib/Socket/chats.js +40 -247
  30. package/lib/Socket/chats.js.map +1 -1
  31. package/lib/Socket/communities.d.ts +641 -269
  32. package/lib/Socket/communities.d.ts.map +1 -1
  33. package/lib/Socket/dugong.d.ts +127 -315
  34. package/lib/Socket/dugong.d.ts.map +1 -0
  35. package/lib/Socket/dugong.js +749 -653
  36. package/lib/Socket/dugong.js.map +1 -0
  37. package/lib/Socket/groups.d.ts +2 -13
  38. package/lib/Socket/groups.d.ts.map +1 -1
  39. package/lib/Socket/groups.js +1 -21
  40. package/lib/Socket/groups.js.map +1 -1
  41. package/lib/Socket/index.d.ts +631 -256
  42. package/lib/Socket/index.d.ts.map +1 -1
  43. package/lib/Socket/index.js +12 -9
  44. package/lib/Socket/index.js.map +1 -1
  45. package/lib/Socket/messages-recv.d.ts +58 -23
  46. package/lib/Socket/messages-recv.d.ts.map +1 -1
  47. package/lib/Socket/messages-recv.js +181 -645
  48. package/lib/Socket/messages-recv.js.map +1 -1
  49. package/lib/Socket/messages-send.d.ts +575 -201
  50. package/lib/Socket/messages-send.d.ts.map +1 -1
  51. package/lib/Socket/messages-send.js +1552 -1185
  52. package/lib/Socket/messages-send.js.map +1 -1
  53. package/lib/Socket/mex.d.ts.map +1 -1
  54. package/lib/Socket/mex.js +8 -2
  55. package/lib/Socket/mex.js.map +1 -1
  56. package/lib/Socket/newsletter.d.ts +18 -11
  57. package/lib/Socket/newsletter.d.ts.map +1 -1
  58. package/lib/Socket/newsletter.js +440 -165
  59. package/lib/Socket/newsletter.js.map +1 -1
  60. package/lib/Socket/socket.d.ts +2 -6
  61. package/lib/Socket/socket.d.ts.map +1 -1
  62. package/lib/Socket/socket.js +25 -59
  63. package/lib/Socket/socket.js.map +1 -1
  64. package/lib/Types/Auth.d.ts +0 -1
  65. package/lib/Types/Auth.d.ts.map +1 -1
  66. package/lib/Types/Bussines.d.ts +34 -22
  67. package/lib/Types/Call.d.ts +1 -1
  68. package/lib/Types/Call.d.ts.map +1 -1
  69. package/lib/Types/Chat.d.ts +0 -1
  70. package/lib/Types/Chat.d.ts.map +1 -1
  71. package/lib/Types/Contact.d.ts +0 -2
  72. package/lib/Types/Contact.d.ts.map +1 -1
  73. package/lib/Types/Events.d.ts +1 -20
  74. package/lib/Types/Events.d.ts.map +1 -1
  75. package/lib/Types/GroupMetadata.d.ts +1 -4
  76. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  77. package/lib/Types/Message.d.ts +348 -294
  78. package/lib/Types/Message.d.ts.map +1 -1
  79. package/lib/Types/Message.js.map +1 -1
  80. package/lib/Types/Newsletter.d.ts.map +1 -0
  81. package/lib/Types/Newsletter.js.map +1 -0
  82. package/lib/Types/Signal.d.ts +1 -12
  83. package/lib/Types/Signal.d.ts.map +1 -1
  84. package/lib/Types/Socket.d.ts +148 -126
  85. package/lib/Types/Socket.d.ts.map +1 -1
  86. package/lib/Types/State.d.ts +0 -58
  87. package/lib/Types/State.d.ts.map +1 -1
  88. package/lib/Types/State.js +0 -43
  89. package/lib/Types/State.js.map +1 -1
  90. package/lib/Types/index.d.ts +52 -52
  91. package/lib/Types/index.d.ts.map +1 -1
  92. package/lib/Types/index.js +30 -23
  93. package/lib/Types/index.js.map +1 -1
  94. package/lib/Utils/auth-utils.d.ts +0 -5
  95. package/lib/Utils/auth-utils.d.ts.map +1 -1
  96. package/lib/Utils/auth-utils.js +0 -12
  97. package/lib/Utils/auth-utils.js.map +1 -1
  98. package/lib/Utils/browser-utils.js +0 -1
  99. package/lib/Utils/chat-utils.d.ts +4 -34
  100. package/lib/Utils/chat-utils.d.ts.map +1 -1
  101. package/lib/Utils/chat-utils.js +20 -80
  102. package/lib/Utils/chat-utils.js.map +1 -1
  103. package/lib/Utils/crypto.d.ts +12 -12
  104. package/lib/Utils/crypto.d.ts.map +1 -1
  105. package/lib/Utils/crypto.js.map +1 -1
  106. package/lib/Utils/decode-wa-message.d.ts +0 -18
  107. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  108. package/lib/Utils/decode-wa-message.js +0 -34
  109. package/lib/Utils/decode-wa-message.js.map +1 -1
  110. package/lib/Utils/event-buffer.d.ts +0 -2
  111. package/lib/Utils/event-buffer.d.ts.map +1 -1
  112. package/lib/Utils/event-buffer.js +1 -49
  113. package/lib/Utils/event-buffer.js.map +1 -1
  114. package/lib/Utils/generics.d.ts +2 -2
  115. package/lib/Utils/generics.d.ts.map +1 -1
  116. package/lib/Utils/generics.js +1 -10
  117. package/lib/Utils/generics.js.map +1 -1
  118. package/lib/Utils/history.d.ts +0 -2
  119. package/lib/Utils/history.d.ts.map +1 -1
  120. package/lib/Utils/history.js +9 -12
  121. package/lib/Utils/history.js.map +1 -1
  122. package/lib/Utils/identity-change-handler.d.ts +0 -7
  123. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  124. package/lib/Utils/identity-change-handler.js +0 -1
  125. package/lib/Utils/identity-change-handler.js.map +1 -1
  126. package/lib/Utils/index.d.ts +23 -23
  127. package/lib/Utils/index.d.ts.map +1 -1
  128. package/lib/Utils/index.js +1 -4
  129. package/lib/Utils/index.js.map +1 -1
  130. package/lib/Utils/link-preview.js +2 -2
  131. package/lib/Utils/link-preview.js.map +1 -1
  132. package/lib/Utils/logger.d.ts +2 -1
  133. package/lib/Utils/logger.d.ts.map +1 -1
  134. package/lib/Utils/message-retry-manager.d.ts +0 -5
  135. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  136. package/lib/Utils/message-retry-manager.js +0 -40
  137. package/lib/Utils/message-retry-manager.js.map +1 -1
  138. package/lib/Utils/messages-media.d.ts +13 -16
  139. package/lib/Utils/messages-media.d.ts.map +1 -1
  140. package/lib/Utils/messages-media.js +79 -85
  141. package/lib/Utils/messages-media.js.map +1 -1
  142. package/lib/Utils/messages.d.ts +6 -16
  143. package/lib/Utils/messages.d.ts.map +1 -1
  144. package/lib/Utils/messages.js +1160 -1021
  145. package/lib/Utils/messages.js.map +1 -1
  146. package/lib/Utils/noise-handler.d.ts +1 -1
  147. package/lib/Utils/process-message.d.ts.map +1 -1
  148. package/lib/Utils/process-message.js +1 -103
  149. package/lib/Utils/process-message.js.map +1 -1
  150. package/lib/Utils/rich-messages.d.ts.map +1 -0
  151. package/lib/Utils/rich-messages.js.map +1 -0
  152. package/lib/Utils/signal.d.ts +0 -13
  153. package/lib/Utils/signal.d.ts.map +1 -1
  154. package/lib/Utils/signal.js +0 -42
  155. package/lib/Utils/signal.js.map +1 -1
  156. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  157. package/lib/Utils/sync-action-utils.js +0 -1
  158. package/lib/Utils/sync-action-utils.js.map +1 -1
  159. package/lib/Utils/tc-token-utils.d.ts +1 -26
  160. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  161. package/lib/Utils/tc-token-utils.js +5 -151
  162. package/lib/Utils/tc-token-utils.js.map +1 -1
  163. package/lib/Utils/validate-connection.d.ts.map +1 -1
  164. package/lib/Utils/validate-connection.js +2 -12
  165. package/lib/Utils/validate-connection.js.map +1 -1
  166. package/lib/VoIP/audio-feeder.js +8 -0
  167. package/lib/VoIP/relay-transport.js +15 -1
  168. package/lib/VoIP/worker-bootstrap.js +14 -2
  169. package/lib/WABinary/decode.d.ts +1 -1
  170. package/lib/WABinary/decode.d.ts.map +1 -1
  171. package/lib/WABinary/generic-utils.d.ts +3 -1
  172. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  173. package/lib/WABinary/generic-utils.js +78 -0
  174. package/lib/WABinary/generic-utils.js.map +1 -1
  175. package/lib/WAM/encode.d.ts +1 -1
  176. package/lib/WAM/encode.d.ts.map +1 -1
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  180. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  181. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  182. package/lib/WAUSync/Protocols/index.js +0 -1
  183. package/lib/WAUSync/Protocols/index.js.map +1 -1
  184. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  185. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  186. package/lib/WAUSync/USyncQuery.js +2 -6
  187. package/lib/WAUSync/USyncQuery.js.map +1 -1
  188. package/lib/WAUSync/USyncUser.d.ts +0 -4
  189. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  190. package/lib/WAUSync/USyncUser.js +0 -8
  191. package/lib/WAUSync/USyncUser.js.map +1 -1
  192. package/lib/index.d.ts +1 -0
  193. package/lib/index.d.ts.map +1 -1
  194. package/lib/index.js +1 -0
  195. package/lib/index.js.map +1 -1
  196. package/package.json +24 -91
  197. package/engine-requirements.js +0 -27
  198. package/lib/Types/Mex.d.ts +0 -141
  199. package/lib/Types/Mex.d.ts.map +0 -1
  200. package/lib/Types/Mex.js +0 -37
  201. package/lib/Types/Mex.js.map +0 -1
  202. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  203. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  204. package/lib/Utils/companion-reg-client-utils.js +0 -35
  205. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  206. package/lib/Utils/mention.d.ts +0 -14
  207. package/lib/Utils/mention.js +0 -138
  208. package/lib/Utils/story-card.js +0 -107
  209. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  210. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  211. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  212. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
@@ -1,29 +1,51 @@
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';
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 {
7
+ CALL_AUDIO_PREFIX,
8
+ CALL_VIDEO_PREFIX,
9
+ MEDIA_KEYS,
10
+ URL_REGEX,
11
+ WA_DEFAULT_EPHEMERAL,
12
+ } from "../Defaults/index.js";
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";
13
35
  const MIMETYPE_MAP = {
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'
36
+ image: "image/jpeg",
37
+ video: "video/mp4",
38
+ document: "application/pdf",
39
+ audio: "audio/ogg; codecs=opus",
40
+ sticker: "image/webp",
41
+ "product-catalog-image": "image/jpeg",
20
42
  };
21
43
  const MessageTypeProto = {
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
44
+ image: WAProto.Message.ImageMessage,
45
+ video: WAProto.Message.VideoMessage,
46
+ audio: WAProto.Message.AudioMessage,
47
+ sticker: WAProto.Message.StickerMessage,
48
+ document: WAProto.Message.DocumentMessage,
27
49
  };
28
50
  /**
29
51
  * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
@@ -31,204 +53,310 @@ const MessageTypeProto = {
31
53
  * @returns the URL, eg. https://google.com
32
54
  */
33
55
  export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
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
- }
56
+ export const generateLinkPreviewIfRequired = async (
57
+ text,
58
+ getUrlInfo,
59
+ logger,
60
+ ) => {
61
+ const url = extractUrlFromText(text);
62
+ if (!!getUrlInfo && url) {
63
+ try {
64
+ const urlInfo = await getUrlInfo(url);
65
+ return urlInfo;
66
+ } catch (error) {
67
+ // ignore if fails
68
+ logger?.warn({ trace: error.stack }, "url generation failed");
69
+ }
70
+ }
46
71
  };
47
72
  const assertColor = async (color) => {
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
- }
73
+ let assertedColor;
74
+ if (typeof color === "number") {
75
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
76
+ } else {
77
+ let hex = color.trim().replace("#", "");
78
+ if (hex.length <= 6) {
79
+ hex = "FF" + hex.padStart(6, "0");
80
+ }
81
+ assertedColor = parseInt(hex, 16);
82
+ return assertedColor;
83
+ }
60
84
  };
61
85
  export const prepareWAMessageMedia = async (message, options) => {
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');
86
+ const logger = options.logger;
87
+ let mediaType;
88
+ for (const key of MEDIA_KEYS) {
89
+ if (key in message) {
90
+ mediaType = key;
91
+ }
92
+ }
93
+ if (!mediaType) {
94
+ throw new Boom("Invalid media type", { statusCode: 400 });
95
+ }
96
+ const uploadData = {
97
+ ...message,
98
+ media: message[mediaType],
99
+ };
100
+ delete uploadData[mediaType];
101
+ // check if cacheable + generate cache key
102
+ const cacheableKey =
103
+ typeof uploadData.media === "object" &&
104
+ "url" in uploadData.media &&
105
+ !!uploadData.media.url &&
106
+ !!options.mediaCache &&
107
+ mediaType + ":" + uploadData.media.url.toString();
108
+ if (mediaType === "document" && !uploadData.fileName) {
109
+ uploadData.fileName = "file";
110
+ }
111
+ if (!uploadData.mimetype) {
112
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
113
+ }
114
+ if (cacheableKey) {
115
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
116
+ if (mediaBuff) {
117
+ logger?.debug({ cacheableKey }, "got media cache hit");
118
+ const obj = proto.Message.decode(mediaBuff);
119
+ const key = `${mediaType}Message`;
120
+ Object.assign(obj[key], { ...uploadData, media: undefined });
121
+ return obj;
122
+ }
123
+ }
124
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
125
+ if (isNewsletter) {
126
+ logger?.info({ key: cacheableKey }, "Preparing raw media for newsletter");
127
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(
128
+ uploadData.media,
129
+ options.mediaTypeOverride || mediaType,
130
+ logger,
131
+ );
132
+ const requiresDurationComputation =
133
+ mediaType === "audio" && typeof uploadData.seconds === "undefined";
134
+ const requiresThumbnailComputation =
135
+ (mediaType === "image" || mediaType === "video") &&
136
+ typeof uploadData["jpegThumbnail"] === "undefined";
137
+ const requiresWaveformProcessing =
138
+ mediaType === "audio" &&
139
+ uploadData.ptt === true &&
140
+ typeof uploadData.waveform === "undefined";
141
+ const requiresAudioBackground =
142
+ options.backgroundColor &&
143
+ mediaType === "audio" &&
144
+ uploadData.ptt === true;
145
+ try {
146
+ if (requiresThumbnailComputation) {
147
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(
148
+ filePath,
149
+ mediaType,
150
+ options,
151
+ );
152
+ uploadData.jpegThumbnail = thumbnail;
153
+ if (!uploadData.width && originalImageDimensions) {
154
+ uploadData.width = originalImageDimensions.width;
155
+ uploadData.height = originalImageDimensions.height;
156
+ logger?.debug("set dimensions");
194
157
  }
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,
195
181
  });
182
+ await fs.unlink(filePath);
196
183
  const obj = WAProto.Message.fromObject({
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
- })
184
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
185
+ url: mediaUrl,
186
+ directPath,
187
+ fileSha256,
188
+ fileLength,
189
+ mediaKeyTimestamp: unixTimestampSeconds(),
190
+ ...uploadData,
191
+ media: undefined,
192
+ }),
208
193
  });
209
194
  if (uploadData.ptv) {
210
- obj.ptvMessage = obj.videoMessage;
211
- delete obj.videoMessage;
195
+ obj.ptvMessage = obj.videoMessage;
196
+ delete obj.videoMessage;
197
+ }
198
+ if (obj.stickerMessage) {
199
+ obj.stickerMessage.stickerSentTs = Date.now();
212
200
  }
213
201
  if (cacheableKey) {
214
- logger?.debug({ cacheableKey }, 'set cache');
215
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
202
+ logger?.debug({ cacheableKey }, "set cache");
203
+ await options.mediaCache.set(
204
+ cacheableKey,
205
+ WAProto.Message.encode(obj).finish(),
206
+ );
216
207
  }
217
208
  return obj;
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
- }
209
+ }
210
+ const requiresDurationComputation =
211
+ mediaType === "audio" && typeof uploadData.seconds === "undefined";
212
+ const requiresThumbnailComputation =
213
+ (mediaType === "image" || mediaType === "video") &&
214
+ typeof uploadData["jpegThumbnail"] === "undefined";
215
+ const requiresWaveformProcessing =
216
+ mediaType === "audio" &&
217
+ uploadData.ptt === true &&
218
+ typeof uploadData.waveform === "undefined";
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);
228
270
  }
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");
229
281
  }
230
- };
231
- return WAProto.Message.fromObject(content);
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
+ }
294
+ if (requiresAudioBackground) {
295
+ uploadData.backgroundArgb = await assertColor(
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);
232
360
  };
233
361
  /**
234
362
  * Generate forwarded message content like WA does
@@ -236,645 +364,579 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) =>
236
364
  * @param options.forceForward will show the message as forwarded even if it is from you
237
365
  */
238
366
  export const generateForwardMessageContent = (message, forceForward) => {
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;
367
+ let content = message.message;
368
+ if (!content) {
369
+ throw new Boom("no content in message", { statusCode: 400 });
370
+ }
371
+ // hacky copy
372
+ content = normalizeMessageContent(content);
373
+ content = proto.Message.decode(proto.Message.encode(content).finish());
374
+ let key = Object.keys(content)[0];
375
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
376
+ score += message.key.fromMe && !forceForward ? 0 : 1;
377
+ if (key === "conversation") {
378
+ content.extendedTextMessage = { text: content[key] };
379
+ delete content.conversation;
380
+ key = "extendedTextMessage";
381
+ }
382
+ const key_ = content?.[key];
383
+ if (score > 0) {
384
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
385
+ } else {
386
+ key_.contextInfo = {};
387
+ }
388
+ return content;
413
389
  };
414
390
  export const hasNonNullishProperty = (message, key) => {
415
- return (typeof message === 'object' &&
416
- message !== null &&
417
- key in message &&
418
- message[key] !== null &&
419
- message[key] !== undefined);
391
+ return (
392
+ typeof message === "object" &&
393
+ message !== null &&
394
+ key in message &&
395
+ message[key] !== null &&
396
+ message[key] !== undefined
397
+ );
420
398
  };
421
399
  function hasOptionalProperty(obj, key) {
422
- return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
400
+ return (
401
+ typeof obj === "object" && obj !== null && key in obj && obj[key] !== null
402
+ );
423
403
  }
424
404
  export const generateWAMessageContent = async (message, options) => {
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
- }
405
+ var _a, _b;
406
+ let m = {};
407
+ if (hasNonNullishProperty(message, "text")) {
408
+ const extContent = { text: message.text };
409
+ let urlInfo = message.linkPreview;
410
+ if (typeof urlInfo === "undefined") {
411
+ urlInfo = await generateLinkPreviewIfRequired(
412
+ message.text,
413
+ options.getUrlInfo,
414
+ options.logger,
415
+ );
416
+ }
417
+ if (urlInfo) {
418
+ extContent.matchedText = urlInfo["matched-text"];
419
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
420
+ extContent.description = urlInfo.description;
421
+ extContent.title = urlInfo.title;
422
+ extContent.previewType = 0;
423
+ const img = urlInfo.highQualityThumbnail;
424
+ if (img) {
425
+ extContent.thumbnailDirectPath = img.directPath;
426
+ extContent.mediaKey = img.mediaKey;
427
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
428
+ extContent.thumbnailWidth = img.width;
429
+ extContent.thumbnailHeight = img.height;
430
+ extContent.thumbnailSha256 = img.fileSha256;
431
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
432
+ }
433
+ }
434
+ if (options.backgroundColor) {
435
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
436
+ }
437
+ if (options.textColor) {
438
+ extContent.textArgb = await assertColor(options.textColor);
439
+ }
440
+ if (options.font) {
441
+ extContent.font = options.font;
442
+ }
443
+ m.extendedTextMessage = extContent;
444
+ } else if (hasNonNullishProperty(message, "contacts")) {
445
+ const contactLen = message.contacts.contacts.length;
446
+ if (!contactLen) {
447
+ throw new Boom("require atleast 1 contact", { statusCode: 400 });
448
+ }
449
+ if (contactLen === 1) {
450
+ m.contactMessage = WAProto.Message.ContactMessage.create(
451
+ message.contacts.contacts[0],
452
+ );
453
+ } else {
454
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(
455
+ message.contacts,
456
+ );
457
+ }
458
+ } else if (hasNonNullishProperty(message, "location")) {
459
+ m.locationMessage = WAProto.Message.LocationMessage.create(
460
+ message.location,
461
+ );
462
+ } else if (hasNonNullishProperty(message, "react")) {
463
+ if (!message.react.senderTimestampMs) {
464
+ message.react.senderTimestampMs = Date.now();
465
+ }
466
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
467
+ } else if (hasNonNullishProperty(message, "delete")) {
468
+ m.protocolMessage = {
469
+ key: message.delete,
470
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE,
471
+ };
472
+ } else if (hasNonNullishProperty(message, "forward")) {
473
+ m = generateForwardMessageContent(message.forward, message.force);
474
+ } else if (hasNonNullishProperty(message, "disappearingMessagesInChat")) {
475
+ const exp =
476
+ typeof message.disappearingMessagesInChat === "boolean"
477
+ ? message.disappearingMessagesInChat
478
+ ? WA_DEFAULT_EPHEMERAL
479
+ : 0
480
+ : message.disappearingMessagesInChat;
481
+ m = prepareDisappearingMessageSettingContent(exp);
482
+ } else if (hasNonNullishProperty(message, "groupInvite")) {
483
+ m.groupInviteMessage = {};
484
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
485
+ m.groupInviteMessage.inviteExpiration =
486
+ message.groupInvite.inviteExpiration;
487
+ m.groupInviteMessage.caption = message.groupInvite.text;
488
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
489
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
490
+ //TODO: use built-in interface and get disappearing mode info etc.
491
+ //TODO: cache / use store!?
492
+ if (options.getProfilePicUrl) {
493
+ const pfpUrl = await options.getProfilePicUrl(
494
+ message.groupInvite.jid,
495
+ "preview",
496
+ );
497
+ if (pfpUrl) {
498
+ const resp = await fetch(pfpUrl, {
499
+ method: "GET",
500
+ dispatcher: options?.options?.dispatcher,
554
501
  });
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;
565
- }
566
- m.messageContextInfo = {
567
- // encKey
568
- messageSecret: message.event.messageSecret || randomBytes(32)
569
- };
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)
593
- };
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
- }
613
- }
614
- else if (hasNonNullishProperty(message, 'album')) {
615
- m.albumMessage = {
616
- expectedImageCount: message.album.expectedImageCount,
617
- expectedVideoCount: message.album.expectedVideoCount
618
- };
619
- }
620
- else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
621
- m.protocolMessage = {
622
- type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
623
- };
624
- }
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
- };
502
+ if (resp.ok) {
503
+ const buf = Buffer.from(await resp.arrayBuffer());
504
+ m.groupInviteMessage.jpegThumbnail = buf;
673
505
  }
674
- else if (message.title) {
675
- interactiveMessage.header = {
676
- title: message.title,
677
- hasMediaAttachment: false
678
- };
679
- }
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
- }
506
+ }
507
+ }
508
+ } else if (hasNonNullishProperty(message, "pin")) {
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,
693
523
  };
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
- }
524
+ break;
525
+ case "plain":
526
+ m.buttonsResponseMessage = {
527
+ selectedButtonId: message.buttonReply.id,
528
+ selectedDisplayText: message.buttonReply.displayText,
529
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
734
530
  };
531
+ break;
735
532
  }
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
- }
533
+ } else if (hasOptionalProperty(message, "ptv") && message.ptv) {
534
+ const { videoMessage } = await prepareWAMessageMedia(
535
+ { video: message.video },
536
+ options,
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 });
758
584
  }
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
- };
585
+ if (
586
+ message.poll.selectableCount < 0 ||
587
+ message.poll.selectableCount > message.poll.values.length
588
+ ) {
589
+ throw new Boom(
590
+ `poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`,
591
+ {
592
+ statusCode: 400,
593
+ },
594
+ );
768
595
  }
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;
596
+ m.messageContextInfo = {
597
+ // encKey
598
+ messageSecret: message.poll.messageSecret || randomBytes(32),
599
+ };
600
+ const pollCreationMessage = {
601
+ name: message.poll.name,
602
+ selectableOptionsCount: message.poll.selectableCount,
603
+ options: message.poll.values.map((optionName) => ({ optionName })),
604
+ };
605
+ if (message.poll.toAnnouncementGroup) {
606
+ // poll v2 is for community announcement groups (single select and multiple)
607
+ m.pollCreationMessageV2 = pollCreationMessage;
608
+ } else {
609
+ if (message.poll.selectableCount === 1) {
610
+ //poll v3 is for single select polls
611
+ m.pollCreationMessageV3 = pollCreationMessage;
612
+ } else {
613
+ // poll for multiple choice polls
614
+ m.pollCreationMessage = pollCreationMessage;
615
+ }
616
+ }
617
+ } else if (hasNonNullishProperty(message, "sharePhoneNumber")) {
618
+ m.protocolMessage = {
619
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER,
620
+ };
621
+ } else if (hasNonNullishProperty(message, "requestPhoneNumber")) {
622
+ m.requestPhoneNumberMessage = {};
623
+ } else if (hasNonNullishProperty(message, "limitSharing")) {
624
+ m.protocolMessage = {
625
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
626
+ limitSharing: {
627
+ sharingLimited: message.limitSharing === true,
628
+ trigger: 1,
629
+ limitSharingSettingTimestamp: Date.now(),
630
+ initiatedByMe: true,
631
+ },
632
+ };
633
+ } else if (hasNonNullishProperty(message, "stickerPack")) {
634
+ const { zip } = await import("fflate").then((m) => m);
635
+ const { stickers, cover, name, publisher, packId, description } =
636
+ message.stickerPack;
637
+ if (!stickers?.length)
638
+ throw new Boom("Sticker pack must contain at least one sticker", {
639
+ statusCode: 400,
640
+ });
641
+ if (stickers.length > 60)
642
+ throw new Boom("Sticker pack exceeds the maximum limit of 60 stickers", {
643
+ statusCode: 400,
644
+ });
645
+ const stickerPackId = packId || generateMessageIDV2();
646
+ const [_sharp] = await Promise.all([import("sharp").catch(() => null)]);
647
+ if (!_sharp)
648
+ throw new Boom("sharp is required for sticker pack generation");
649
+ const sharpLib = _sharp.default || _sharp;
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();
777
703
  }
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
- }
704
+ if (webp.length > 1024 * 1024)
705
+ throw new Boom(`Sticker ${i} exceeds 1MB`);
706
+ const hash = sha256(webp).toString("base64").replace(/\//g, "-");
707
+ const fname = `${hash}.webp`;
708
+ zipData[fname] = [new Uint8Array(webp), { level: 0 }];
709
+ return {
710
+ fileName: fname,
711
+ mimetype: "image/webp",
712
+ isAnimated: animated,
713
+ emojis: s.emojis || [],
714
+ accessibilityLabel: s.accessibilityLabel || "",
786
715
  };
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);
716
+ }),
717
+ );
718
+ const coverRaw = await getStreamBuf(cover);
719
+ const coverWebp = isWebP(coverRaw)
720
+ ? coverRaw
721
+ : await sharpLib(coverRaw).webp().toBuffer();
722
+ const trayIconFileName = `${stickerPackId}.webp`;
723
+ zipData[trayIconFileName] = [new Uint8Array(coverWebp), { level: 0 }];
724
+ const zipBuffer = await new Promise((res, rej) =>
725
+ zip(zipData, (e, d) => (e ? rej(e) : res(Buffer.from(d)))),
726
+ );
727
+ const stickerPackUpload = await encryptedStream(zipBuffer, "sticker-pack", {
728
+ logger: options.logger,
729
+ opts: options.options,
730
+ });
731
+ const stickerPackResult = await options.upload(
732
+ stickerPackUpload.encWriteStream,
733
+ {
734
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString("base64"),
735
+ mediaType: "sticker-pack",
736
+ timeoutMs: options.mediaUploadTimeoutMs,
737
+ },
738
+ );
739
+ m.stickerPackMessage = {
740
+ name,
741
+ publisher,
742
+ stickerPackId,
743
+ packDescription: description,
744
+ stickerPackOrigin:
745
+ WAProto.Message.StickerPackMessage.StickerPackOrigin.THIRD_PARTY,
746
+ stickerPackSize: zipBuffer.length,
747
+ stickers: stickerMeta,
748
+ fileSha256: stickerPackUpload.fileSha256,
749
+ fileEncSha256: stickerPackUpload.fileEncSha256,
750
+ mediaKey: stickerPackUpload.mediaKey,
751
+ directPath: stickerPackResult.directPath,
752
+ fileLength: stickerPackUpload.fileLength,
753
+ mediaKeyTimestamp: unixTimestampSeconds(),
754
+ trayIconFileName,
755
+ };
756
+ try {
757
+ const thumbBuf = await sharpLib(coverRaw)
758
+ .resize(252, 252)
759
+ .jpeg()
760
+ .toBuffer();
761
+ const thumbUpload = await encryptedStream(
762
+ thumbBuf,
763
+ "thumbnail-sticker-pack",
764
+ {
765
+ logger: options.logger,
766
+ opts: options.options,
767
+ mediaKey: stickerPackUpload.mediaKey,
768
+ },
769
+ );
770
+ const thumbResult = await options.upload(thumbUpload.encWriteStream, {
771
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString("base64"),
772
+ mediaType: "thumbnail-sticker-pack",
773
+ timeoutMs: options.mediaUploadTimeoutMs,
774
+ });
775
+ Object.assign(m.stickerPackMessage, {
776
+ thumbnailDirectPath: thumbResult.directPath,
777
+ thumbnailSha256: thumbUpload.fileSha256,
778
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
779
+ thumbnailHeight: 252,
780
+ thumbnailWidth: 252,
781
+ imageDataHash: sha256(thumbBuf).toString("base64"),
782
+ });
783
+ } catch (e) {
784
+ options.logger?.warn?.(`Sticker pack thumbnail failed: ${e?.message}`);
785
+ }
786
+ m.stickerPackMessage.contextInfo = {
787
+ ...(message.contextInfo || {}),
788
+ ...(message.mentions ? { mentionedJid: message.mentions } : {}),
789
+ };
790
+ } else {
791
+ m = await prepareWAMessageMedia(message, options);
792
+ }
793
+ if (hasOptionalProperty(message, "viewOnce") && !!message.viewOnce) {
794
+ m = { viewOnceMessage: { message: m } };
795
+ }
796
+ if (
797
+ (hasOptionalProperty(message, "mentions") && message.mentions?.length) ||
798
+ (hasOptionalProperty(message, "mentionAll") && message.mentionAll)
799
+ ) {
800
+ const messageType = Object.keys(m)[0];
801
+ const key = m[messageType];
802
+ if (key && "contextInfo" in key) {
803
+ key.contextInfo = key.contextInfo || {};
804
+ if (message.mentions?.length) {
805
+ key.contextInfo.mentionedJid = message.mentions;
806
+ }
807
+ if (message.mentionAll) {
808
+ key.contextInfo.nonJidMentions = 1;
809
+ }
810
+ } else if (key) {
811
+ key.contextInfo = {
812
+ mentionedJid: message.mentions,
813
+ nonJidMentions: message.mentionAll ? 1 : 0,
814
+ };
815
+ }
816
+ }
817
+ if (hasOptionalProperty(message, "edit")) {
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);
796
843
  };
797
844
  export const generateWAMessageFromContent = (jid, message, options) => {
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
- }
845
+ // set timestamp to now
846
+ // if not specified
847
+ if (!options.timestamp) {
848
+ options.timestamp = new Date();
849
+ }
850
+ const innerMessage = normalizeMessageContent(message);
851
+ const key = getContentType(innerMessage);
852
+ const timestamp = unixTimestampSeconds(options.timestamp);
853
+ const { quoted, userJid } = options;
854
+ if (quoted && !isJidNewsletter(jid)) {
855
+ const participant = quoted.key.fromMe
856
+ ? userJid // TODO: Add support for LIDs
857
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
858
+ let quotedMsg = normalizeMessageContent(quoted.message);
859
+ const msgType = getContentType(quotedMsg);
860
+ // strip any redundant properties
861
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
862
+ const quotedContent = quotedMsg[msgType];
833
863
  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 (
834
887
  // if we want to send a disappearing message
835
888
  !!options?.ephemeralExpiration &&
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
889
+ // and it's not a protocol message -- delete, toggle disappear message
890
+ key !== "protocolMessage" &&
891
+ // already not converted to disappearing message
892
+ key !== "ephemeralMessage" &&
893
+ // newsletters don't support ephemeral messages
894
+ !isJidNewsletter(jid)
895
+ ) {
896
+ /* @ts-ignore */
897
+ innerMessage[key].contextInfo = {
898
+ ...(innerMessage[key].contextInfo || {}),
899
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL,
900
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
862
901
  };
863
- return WAProto.WebMessageInfo.fromObject(messageJSON);
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);
864
918
  };
865
919
  export const generateWAMessage = async (jid, content, options) => {
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);
920
+ // ensure msg ID is with every log
921
+ options.logger = options?.logger?.child({ msgId: options.messageId });
922
+ // Pass jid in the options to generateWAMessageContent
923
+ return generateWAMessageFromContent(
924
+ jid,
925
+ await generateWAMessageContent(content, { ...options, jid }),
926
+ options,
927
+ );
870
928
  };
871
929
  /** Get the key to access the true type of content */
872
930
  export const getContentType = (content) => {
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
- }
931
+ if (content) {
932
+ const keys = Object.keys(content);
933
+ const key = keys.find(
934
+ (k) =>
935
+ (k === "conversation" || k.includes("Message")) &&
936
+ k !== "senderKeyDistributionMessage",
937
+ );
938
+ return key;
939
+ }
878
940
  };
879
941
  /**
880
942
  * Normalizes ephemeral, view once messages to regular message content
@@ -883,115 +945,132 @@ export const getContentType = (content) => {
883
945
  * @returns
884
946
  */
885
947
  export const normalizeMessageContent = (content) => {
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
- }
948
+ if (!content) {
949
+ return undefined;
950
+ }
951
+ // set max iterations to prevent an infinite loop
952
+ for (let i = 0; i < 5; i++) {
953
+ const inner = getFutureProofMessage(content);
954
+ if (!inner) {
955
+ break;
956
+ }
957
+ content = inner.message;
958
+ }
959
+ return content;
960
+ function getFutureProofMessage(message) {
961
+ return (
962
+ message?.ephemeralMessage ||
963
+ message?.viewOnceMessage ||
964
+ message?.documentWithCaptionMessage ||
965
+ message?.viewOnceMessageV2 ||
966
+ message?.viewOnceMessageV2Extension ||
967
+ message?.viewOnceMessageV3 ||
968
+ message?.ptvMessage ||
969
+ message?.editedMessage ||
970
+ message?.associatedChildMessage ||
971
+ message?.groupStatusMessage ||
972
+ message?.groupStatusMessageV2
973
+ );
974
+ }
909
975
  };
910
976
  /**
911
977
  * Extract the true message content from a message
912
978
  * Eg. extracts the inner message from a disappearing message/view once message
913
979
  */
914
980
  export const extractMessageContent = (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;
981
+ const extractFromTemplateMessage = (msg) => {
982
+ if (msg.imageMessage) {
983
+ return { imageMessage: msg.imageMessage };
984
+ } else if (msg.documentMessage) {
985
+ return { documentMessage: msg.documentMessage };
986
+ } else if (msg.videoMessage) {
987
+ return { videoMessage: msg.videoMessage };
988
+ } else if (msg.locationMessage) {
989
+ return { locationMessage: msg.locationMessage };
990
+ } else {
991
+ return {
992
+ conversation:
993
+ "contentText" in msg
994
+ ? msg.contentText
995
+ : "hydratedContentText" in msg
996
+ ? msg.hydratedContentText
997
+ : "",
998
+ };
999
+ }
1000
+ };
1001
+ content = normalizeMessageContent(content);
1002
+ if (content?.buttonsMessage) {
1003
+ return extractFromTemplateMessage(content.buttonsMessage);
1004
+ }
1005
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1006
+ return extractFromTemplateMessage(
1007
+ content?.templateMessage?.hydratedFourRowTemplate,
1008
+ );
1009
+ }
1010
+ if (content?.templateMessage?.hydratedTemplate) {
1011
+ return extractFromTemplateMessage(
1012
+ content?.templateMessage?.hydratedTemplate,
1013
+ );
1014
+ }
1015
+ if (content?.templateMessage?.fourRowTemplate) {
1016
+ return extractFromTemplateMessage(
1017
+ content?.templateMessage?.fourRowTemplate,
1018
+ );
1019
+ }
1020
+ return content;
948
1021
  };
949
1022
  /**
950
1023
  * Returns the device predicted by message ID
951
1024
  */
952
- export const getDevice = (id) => /^3A.{18}$/.test(id)
953
- ? 'ios'
1025
+ export const getDevice = (id) =>
1026
+ /^3A.{18}$/.test(id)
1027
+ ? "ios"
954
1028
  : /^3E.{20}$/.test(id)
955
- ? 'web'
956
- : /^(.{21}|.{32})$/.test(id)
957
- ? 'android'
958
- : /^(3F|.{18}$)/.test(id)
959
- ? 'desktop'
960
- : 'unknown';
1029
+ ? "web"
1030
+ : /^(.{21}|.{32})$/.test(id)
1031
+ ? "android"
1032
+ : /^(3F|.{18}$)/.test(id)
1033
+ ? "desktop"
1034
+ : "unknown";
961
1035
  /** Upserts a receipt in the message */
962
1036
  export const updateMessageWithReceipt = (msg, receipt) => {
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
- }
1037
+ msg.userReceipt = msg.userReceipt || [];
1038
+ const recp = msg.userReceipt.find((m) => m.userJid === receipt.userJid);
1039
+ if (recp) {
1040
+ Object.assign(recp, receipt);
1041
+ } else {
1042
+ msg.userReceipt.push(receipt);
1043
+ }
971
1044
  };
972
1045
  /** Update the message with a new reaction */
973
1046
  export const updateMessageWithReaction = (msg, reaction) => {
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;
1047
+ const authorID = getKeyAuthor(reaction.key);
1048
+ const reactions = (msg.reactions || []).filter(
1049
+ (r) => getKeyAuthor(r.key) !== authorID,
1050
+ );
1051
+ reaction.text = reaction.text || "";
1052
+ reactions.push(reaction);
1053
+ msg.reactions = reactions;
979
1054
  };
980
1055
  /** Update the message with a new poll update */
981
1056
  export const updateMessageWithPollUpdate = (msg, update) => {
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;
1057
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1058
+ const reactions = (msg.pollUpdates || []).filter(
1059
+ (r) => getKeyAuthor(r.pollUpdateMessageKey) !== authorID,
1060
+ );
1061
+ if (update.vote?.selectedOptions?.length) {
1062
+ reactions.push(update);
1063
+ }
1064
+ msg.pollUpdates = reactions;
988
1065
  };
989
1066
  /** Update the message with a new event response */
990
1067
  export const updateMessageWithEventResponse = (msg, update) => {
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;
1068
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1069
+ const responses = (msg.eventResponses || []).filter(
1070
+ (r) => getKeyAuthor(r.eventResponseMessageKey) !== authorID,
1071
+ );
1072
+ responses.push(update);
1073
+ msg.eventResponses = responses;
995
1074
  };
996
1075
  /**
997
1076
  * Aggregates all poll updates in a poll.
@@ -1000,37 +1079,40 @@ export const updateMessageWithEventResponse = (msg, update) => {
1000
1079
  * @returns A list of options & their voters
1001
1080
  */
1002
1081
  export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
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: []
1082
+ const opts =
1083
+ message?.pollCreationMessage?.options ||
1084
+ message?.pollCreationMessageV2?.options ||
1085
+ message?.pollCreationMessageV3?.options ||
1086
+ [];
1087
+ const voteHashMap = opts.reduce((acc, opt) => {
1088
+ const hash = sha256(Buffer.from(opt.optionName || "")).toString();
1089
+ acc[hash] = {
1090
+ name: opt.optionName || "",
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: [],
1012
1107
  };
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);
1108
+ data = voteHashMap[hash];
1109
+ }
1110
+ voteHashMap[hash].voters.push(
1111
+ getKeyAuthor(update.pollUpdateMessageKey, meId),
1112
+ );
1113
+ }
1114
+ }
1115
+ return Object.values(voteHashMap);
1034
1116
  }
1035
1117
  /**
1036
1118
  * Aggregates all event responses in an event message.
@@ -1039,102 +1121,159 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1039
1121
  * @returns A list of response types & their responders
1040
1122
  */
1041
1123
  export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
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);
1124
+ const responseTypes = ["GOING", "NOT_GOING", "MAYBE"];
1125
+ const responseMap = {};
1126
+ for (const type of responseTypes) {
1127
+ responseMap[type] = {
1128
+ response: type,
1129
+ responders: [],
1130
+ };
1131
+ }
1132
+ for (const update of eventResponses || []) {
1133
+ const responseType = update.eventResponse || "UNKNOWN";
1134
+ if (responseType !== "UNKNOWN" && responseMap[responseType]) {
1135
+ responseMap[responseType].responders.push(
1136
+ getKeyAuthor(update.eventResponseMessageKey, meId),
1137
+ );
1138
+ }
1139
+ }
1140
+ return Object.values(responseMap);
1057
1141
  }
1058
1142
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1059
1143
  export const aggregateMessageKeysNotFromMe = (keys) => {
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
- }
1144
+ const keyMap = {};
1145
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1146
+ if (!fromMe) {
1147
+ const uqKey = `${remoteJid}:${participant || ""}`;
1148
+ if (!keyMap[uqKey]) {
1149
+ keyMap[uqKey] = {
1150
+ jid: remoteJid,
1151
+ participant: participant,
1152
+ messageIds: [],
1153
+ };
1154
+ }
1155
+ keyMap[uqKey].messageIds.push(id);
1073
1156
  }
1074
- return Object.values(keyMap);
1157
+ }
1158
+ return Object.values(keyMap);
1075
1159
  };
1076
1160
  const REUPLOAD_REQUIRED_STATUS = [410, 404];
1077
1161
  /**
1078
1162
  * Downloads the given message. Throws an error if it's not a media message
1079
1163
  */
1080
1164
  export const downloadMediaMessage = async (message, type, options, ctx) => {
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
- }
1165
+ const result = await downloadMsg().catch(async (error) => {
1166
+ if (
1167
+ ctx &&
1168
+ typeof error?.status === "number" && // treat errors with status as HTTP failures requiring reupload
1169
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)
1170
+ ) {
1171
+ ctx.logger.info(
1172
+ { key: message.key },
1173
+ "sending reupload media request...",
1174
+ );
1175
+ // request reupload
1176
+ message = await ctx.reuploadRequest(message);
1177
+ const result = await downloadMsg();
1178
+ return result;
1179
+ }
1180
+ throw error;
1181
+ });
1182
+ return result;
1183
+ async function downloadMsg() {
1184
+ const mContent = extractMessageContent(message.message);
1185
+ if (!mContent) {
1186
+ throw new Boom("No message present", { statusCode: 400, data: message });
1187
+ }
1188
+ const contentType = getContentType(mContent);
1189
+ let mediaType = contentType?.replace("Message", "");
1190
+ const media = mContent[contentType];
1191
+ if (
1192
+ !media ||
1193
+ typeof media !== "object" ||
1194
+ (!("url" in media) && !("thumbnailDirectPath" in media))
1195
+ ) {
1196
+ throw new Boom(`"${contentType}" message is not a media message`);
1197
+ }
1198
+ let download;
1199
+ if ("thumbnailDirectPath" in media && !("url" in media)) {
1200
+ download = {
1201
+ directPath: media.thumbnailDirectPath,
1202
+ mediaKey: media.mediaKey,
1203
+ };
1204
+ mediaType = "thumbnail-link";
1205
+ } else {
1206
+ download = media;
1207
+ }
1208
+ const stream = await downloadContentFromMessage(
1209
+ download,
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
+ }
1126
1222
  };
1127
1223
  /** Checks whether the given message is a media message; if it is returns the inner content */
1128
1224
  export const assertMediaContent = (content) => {
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;
1225
+ content = extractMessageContent(content);
1226
+ const mediaContent =
1227
+ content?.documentMessage ||
1228
+ content?.imageMessage ||
1229
+ content?.videoMessage ||
1230
+ content?.audioMessage ||
1231
+ content?.stickerMessage;
1232
+ if (!mediaContent) {
1233
+ throw new Boom("given message is not a media message", {
1234
+ statusCode: 400,
1235
+ data: content,
1236
+ });
1237
+ }
1238
+ return mediaContent;
1239
+ };
1240
+ /**
1241
+ * Builds the `additionalNodes` payload WhatsApp requires to recognize an
1242
+ * outgoing message as an interactive / native-flow message (buttons, single
1243
+ * & multi select lists, carousels, CTA buttons, etc).
1244
+ *
1245
+ * Without this `<biz><interactive native_flow></interactive></biz>` node
1246
+ * attached via `relayMessage(jid, message, { additionalNodes })`, WhatsApp's
1247
+ * servers silently accept the message but never render the buttons — the
1248
+ * message just shows up as the body text with no interactive UI.
1249
+ *
1250
+ * This mirrors the exact node shape already used internally for every
1251
+ * interactive send in this library (see Modded/message_builder.js), so it is
1252
+ * safe to reuse for any hand-built interactiveMessage/nativeFlowMessage.
1253
+ *
1254
+ * @param {string} [_jid] - kept for call-signature compatibility (e.g. `buildInteractiveAdditionalNodes(jid, message)`), currently unused
1255
+ * @param {object} [_message] - kept for call-signature compatibility, currently unused
1256
+ * @param {{ name?: string, v?: string }} [options] - override the native_flow `name`/`v` attrs if needed
1257
+ * @returns {Array<object>} additionalNodes array ready to pass to relayMessage
1258
+ */
1259
+ export const buildInteractiveAdditionalNodes = (_jid, _message, options = {}) => {
1260
+ return [
1261
+ {
1262
+ tag: 'biz',
1263
+ attrs: {},
1264
+ content: [
1265
+ {
1266
+ tag: 'interactive',
1267
+ attrs: { type: 'native_flow', v: '1' },
1268
+ content: [
1269
+ {
1270
+ tag: 'native_flow',
1271
+ attrs: { v: options.v || '9', name: options.name || 'mixed' },
1272
+ },
1273
+ ],
1274
+ },
1275
+ ],
1276
+ },
1277
+ ];
1139
1278
  };
1140
- //# sourceMappingURL=messages.js.map
1279
+ //# sourceMappingURL=messages.js.map