@pontalabs/baileys 1.0.5 → 1.0.7

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 (270) hide show
  1. package/WAProto/fix-imports.js +85 -0
  2. package/lib/Defaults/index.d.ts.map +1 -0
  3. package/lib/Defaults/index.js.map +1 -0
  4. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  5. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  6. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  7. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  8. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  9. package/lib/Signal/Group/group_cipher.js.map +1 -0
  10. package/lib/Signal/Group/index.d.ts.map +1 -0
  11. package/lib/Signal/Group/index.js.map +1 -0
  12. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  13. package/lib/Signal/Group/keyhelper.js.map +1 -0
  14. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  15. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  18. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  19. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  20. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  21. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  22. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  23. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  24. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  25. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  26. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  27. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  28. package/lib/Signal/libsignal.d.ts.map +1 -0
  29. package/lib/Signal/libsignal.js.map +1 -0
  30. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  31. package/lib/Signal/lid-mapping.js.map +1 -0
  32. package/lib/Socket/Client/index.d.ts.map +1 -0
  33. package/lib/Socket/Client/index.js.map +1 -0
  34. package/lib/Socket/Client/types.d.ts.map +1 -0
  35. package/lib/Socket/Client/types.js.map +1 -0
  36. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  37. package/lib/Socket/Client/websocket.js.map +1 -0
  38. package/lib/Socket/business.d.ts.map +1 -0
  39. package/lib/Socket/business.js.map +1 -0
  40. package/lib/Socket/chats.d.ts.map +1 -0
  41. package/lib/Socket/chats.js.map +1 -0
  42. package/lib/Socket/communities.d.ts +273 -0
  43. package/lib/Socket/communities.d.ts.map +1 -0
  44. package/lib/Socket/communities.js +431 -0
  45. package/lib/Socket/communities.js.map +1 -0
  46. package/lib/Socket/community.js +10 -2
  47. package/lib/Socket/dugong.js +261 -0
  48. package/lib/Socket/dugong.js.bak +204 -0
  49. package/lib/Socket/groups.d.ts.map +1 -0
  50. package/lib/Socket/groups.js +11 -2
  51. package/lib/Socket/groups.js.map +1 -0
  52. package/lib/Socket/index.d.ts.map +1 -0
  53. package/lib/Socket/index.js.bak +44 -0
  54. package/lib/Socket/index.js.map +1 -0
  55. package/lib/Socket/messages-recv.d.ts.map +1 -0
  56. package/lib/Socket/messages-recv.js +6 -2
  57. package/lib/Socket/messages-recv.js.map +1 -0
  58. package/lib/Socket/messages-send.d.ts.map +1 -0
  59. package/lib/Socket/messages-send.js.bak +1400 -0
  60. package/lib/Socket/messages-send.js.map +1 -0
  61. package/lib/Socket/mex.d.ts +3 -0
  62. package/lib/Socket/mex.d.ts.map +1 -0
  63. package/lib/Socket/mex.js +42 -0
  64. package/lib/Socket/mex.js.map +1 -0
  65. package/lib/Socket/newsletter.d.ts.map +1 -0
  66. package/lib/Socket/newsletter.js.map +1 -0
  67. package/lib/Socket/socket.d.ts.map +1 -0
  68. package/lib/Socket/socket.js.map +1 -0
  69. package/lib/Store/index.d.ts.map +1 -0
  70. package/lib/Store/index.js.map +1 -0
  71. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  72. package/lib/Store/make-in-memory-store.js.map +1 -0
  73. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  74. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  75. package/lib/Store/object-repository.d.ts.map +1 -0
  76. package/lib/Store/object-repository.js.map +1 -0
  77. package/lib/Types/Auth.d.ts.map +1 -0
  78. package/lib/Types/Auth.js.map +1 -0
  79. package/lib/Types/Bussines.d.ts +25 -0
  80. package/lib/Types/Bussines.d.ts.map +1 -0
  81. package/lib/Types/Bussines.js.map +1 -0
  82. package/lib/Types/Call.d.ts.map +1 -0
  83. package/lib/Types/Call.js.map +1 -0
  84. package/lib/Types/Chat.d.ts.map +1 -0
  85. package/lib/Types/Chat.js.map +1 -0
  86. package/lib/Types/Contact.d.ts.map +1 -0
  87. package/lib/Types/Contact.js.map +1 -0
  88. package/lib/Types/Events.d.ts.map +1 -0
  89. package/lib/Types/Events.js.map +1 -0
  90. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  91. package/lib/Types/GroupMetadata.js.map +1 -0
  92. package/lib/Types/Label.d.ts.map +1 -0
  93. package/lib/Types/Label.js.map +1 -0
  94. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  95. package/lib/Types/LabelAssociation.js.map +1 -0
  96. package/lib/Types/Message.d.ts.map +1 -0
  97. package/lib/Types/Message.js.map +1 -0
  98. package/lib/Types/Mex.d.ts +141 -0
  99. package/lib/Types/Mex.d.ts.map +1 -0
  100. package/lib/Types/Mex.js +37 -0
  101. package/lib/Types/Mex.js.map +1 -0
  102. package/lib/Types/Product.d.ts.map +1 -0
  103. package/lib/Types/Product.js.map +1 -0
  104. package/lib/Types/RichType.d.ts +3 -0
  105. package/lib/Types/RichType.d.ts.map +1 -0
  106. package/lib/Types/RichType.js +23 -0
  107. package/lib/Types/RichType.js.bak +23 -0
  108. package/lib/Types/RichType.js.map +1 -0
  109. package/lib/Types/Signal.d.ts.map +1 -0
  110. package/lib/Types/Signal.js.map +1 -0
  111. package/lib/Types/Socket.d.ts.map +1 -0
  112. package/lib/Types/Socket.js.map +1 -0
  113. package/lib/Types/State.d.ts.map +1 -0
  114. package/lib/Types/State.js.map +1 -0
  115. package/lib/Types/USync.d.ts.map +1 -0
  116. package/lib/Types/USync.js.map +1 -0
  117. package/lib/Types/index.d.ts.map +1 -0
  118. package/lib/Types/index.js.map +1 -0
  119. package/lib/Utils/auth-utils.d.ts.map +1 -0
  120. package/lib/Utils/auth-utils.js.map +1 -0
  121. package/lib/Utils/browser-utils.d.ts +4 -0
  122. package/lib/Utils/browser-utils.d.ts.map +1 -0
  123. package/lib/Utils/browser-utils.js +28 -0
  124. package/lib/Utils/browser-utils.js.map +1 -0
  125. package/lib/Utils/business.d.ts.map +1 -0
  126. package/lib/Utils/business.js.map +1 -0
  127. package/lib/Utils/chat-utils.d.ts.map +1 -0
  128. package/lib/Utils/chat-utils.js.map +1 -0
  129. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  130. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  131. package/lib/Utils/companion-reg-client-utils.js +35 -0
  132. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  133. package/lib/Utils/crypto.d.ts.map +1 -0
  134. package/lib/Utils/crypto.js.map +1 -0
  135. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  136. package/lib/Utils/decode-wa-message.js +10 -1
  137. package/lib/Utils/decode-wa-message.js.map +1 -0
  138. package/lib/Utils/event-buffer.d.ts.map +1 -0
  139. package/lib/Utils/event-buffer.js.map +1 -0
  140. package/lib/Utils/generics.d.ts.map +1 -0
  141. package/lib/Utils/generics.js.map +1 -0
  142. package/lib/Utils/history.d.ts.map +1 -0
  143. package/lib/Utils/history.js.map +1 -0
  144. package/lib/Utils/identity-change-handler.d.ts +44 -0
  145. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  146. package/lib/Utils/identity-change-handler.js +50 -0
  147. package/lib/Utils/identity-change-handler.js.map +1 -0
  148. package/lib/Utils/index.d.ts.map +1 -0
  149. package/lib/Utils/index.js.map +1 -0
  150. package/lib/Utils/link-preview.d.ts.map +1 -0
  151. package/lib/Utils/link-preview.js.map +1 -0
  152. package/lib/Utils/logger.d.ts.map +1 -0
  153. package/lib/Utils/logger.js.map +1 -0
  154. package/lib/Utils/lt-hash.d.ts.map +1 -0
  155. package/lib/Utils/lt-hash.js.map +1 -0
  156. package/lib/Utils/make-mutex.d.ts.map +1 -0
  157. package/lib/Utils/make-mutex.js.map +1 -0
  158. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  159. package/lib/Utils/message-retry-manager.js.map +1 -0
  160. package/lib/Utils/messages-media.d.ts.map +1 -0
  161. package/lib/Utils/messages-media.js.bak +786 -0
  162. package/lib/Utils/messages-media.js.map +1 -0
  163. package/lib/Utils/messages.d.ts.map +1 -0
  164. package/lib/Utils/messages.js.backup +1768 -0
  165. package/lib/Utils/messages.js.bak +1809 -0
  166. package/lib/Utils/messages.js.bak2 +893 -0
  167. package/lib/Utils/messages.js.bak3 +1183 -0
  168. package/lib/Utils/messages.js.map +1 -0
  169. package/lib/Utils/noise-handler.d.ts.map +1 -0
  170. package/lib/Utils/noise-handler.js.map +1 -0
  171. package/lib/Utils/offline-node-processor.d.ts +17 -0
  172. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  173. package/lib/Utils/offline-node-processor.js +40 -0
  174. package/lib/Utils/offline-node-processor.js.map +1 -0
  175. package/lib/Utils/pre-key-manager.d.ts +28 -0
  176. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  177. package/lib/Utils/pre-key-manager.js +106 -0
  178. package/lib/Utils/pre-key-manager.js.map +1 -0
  179. package/lib/Utils/process-message.d.ts.map +1 -0
  180. package/lib/Utils/process-message.js.map +1 -0
  181. package/lib/Utils/reporting-utils.d.ts +11 -0
  182. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  183. package/lib/Utils/reporting-utils.js +258 -0
  184. package/lib/Utils/reporting-utils.js.map +1 -0
  185. package/lib/Utils/rich-message-utils.d.ts +49 -0
  186. package/lib/Utils/rich-message-utils.d.ts.map +1 -0
  187. package/lib/Utils/rich-message-utils.js.backup +706 -0
  188. package/lib/Utils/rich-message-utils.js.bak +246 -0
  189. package/lib/Utils/rich-message-utils.js.map +1 -0
  190. package/lib/Utils/rich-message-utils.js.original +1332 -0
  191. package/lib/Utils/signal.d.ts.map +1 -0
  192. package/lib/Utils/signal.js.map +1 -0
  193. package/lib/Utils/stanza-ack.d.ts +11 -0
  194. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  195. package/lib/Utils/stanza-ack.js +38 -0
  196. package/lib/Utils/stanza-ack.js.map +1 -0
  197. package/lib/Utils/sync-action-utils.d.ts +19 -0
  198. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  199. package/lib/Utils/sync-action-utils.js +49 -0
  200. package/lib/Utils/sync-action-utils.js.map +1 -0
  201. package/lib/Utils/tc-token-utils.d.ts +37 -0
  202. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  203. package/lib/Utils/tc-token-utils.js +163 -0
  204. package/lib/Utils/tc-token-utils.js.map +1 -0
  205. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  206. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  207. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  208. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  209. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  210. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  211. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  212. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  213. package/lib/Utils/validate-connection.d.ts.map +1 -0
  214. package/lib/Utils/validate-connection.js.map +1 -0
  215. package/lib/WABinary/constants.d.ts.map +1 -0
  216. package/lib/WABinary/constants.js.bak +1373 -0
  217. package/lib/WABinary/constants.js.map +1 -0
  218. package/lib/WABinary/decode.d.ts.map +1 -0
  219. package/lib/WABinary/decode.js.map +1 -0
  220. package/lib/WABinary/encode.d.ts.map +1 -0
  221. package/lib/WABinary/encode.js.map +1 -0
  222. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  223. package/lib/WABinary/generic-utils.js.map +1 -0
  224. package/lib/WABinary/index.d.ts.map +1 -0
  225. package/lib/WABinary/index.js.map +1 -0
  226. package/lib/WABinary/jid-utils.d.ts +4 -1
  227. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  228. package/lib/WABinary/jid-utils.js +32 -0
  229. package/lib/WABinary/jid-utils.js.map +1 -0
  230. package/lib/WABinary/types.d.ts.map +1 -0
  231. package/lib/WABinary/types.js.map +1 -0
  232. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  233. package/lib/WAM/BinaryInfo.js.map +1 -0
  234. package/lib/WAM/constants.d.ts.map +1 -0
  235. package/lib/WAM/constants.js.map +1 -0
  236. package/lib/WAM/encode.d.ts.map +1 -0
  237. package/lib/WAM/encode.js.map +1 -0
  238. package/lib/WAM/index.d.ts.map +1 -0
  239. package/lib/WAM/index.js.map +1 -0
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  241. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  242. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  243. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  244. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  245. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  246. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  247. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  248. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  249. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  250. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  251. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  252. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  253. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  254. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  255. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  256. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  257. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  258. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  259. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  260. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  261. package/lib/WAUSync/Protocols/index.js.map +1 -0
  262. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  263. package/lib/WAUSync/USyncQuery.js.map +1 -0
  264. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  265. package/lib/WAUSync/USyncUser.js.map +1 -0
  266. package/lib/WAUSync/index.d.ts.map +1 -0
  267. package/lib/WAUSync/index.js.map +1 -0
  268. package/lib/index.d.ts.map +1 -0
  269. package/lib/index.js.map +1 -0
  270. package/package.json +1 -1
@@ -0,0 +1,1809 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
4
+ import { promises as fs } from 'fs';
5
+ import {} from 'stream';
6
+ import { proto } from '../../WAProto/index.js';
7
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
8
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
9
+ import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
10
+ import { sha256 } from './crypto.js';
11
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
12
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
13
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
14
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
15
+ const CONCURRENCY_LIMIT = 10;
16
+ const MIMETYPE_MAP = {
17
+ image: 'image/jpeg',
18
+ video: 'video/mp4',
19
+ document: 'application/pdf',
20
+ audio: 'audio/ogg; codecs=opus',
21
+ sticker: 'image/webp',
22
+ 'product-catalog-image': 'image/jpeg'
23
+ };
24
+ const MessageTypeProto = {
25
+ image: WAProto.Message.ImageMessage,
26
+ video: WAProto.Message.VideoMessage,
27
+ audio: WAProto.Message.AudioMessage,
28
+ sticker: WAProto.Message.StickerMessage,
29
+ document: WAProto.Message.DocumentMessage
30
+ };
31
+ /**
32
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
33
+ * @param text eg. hello https://google.com
34
+ * @returns the URL, eg. https://google.com
35
+ */
36
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
37
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
38
+ const url = extractUrlFromText(text);
39
+ if (!!getUrlInfo && url) {
40
+ try {
41
+ const urlInfo = await getUrlInfo(url);
42
+ return urlInfo;
43
+ }
44
+ catch (error) {
45
+ // ignore if fails
46
+ logger?.warn({ trace: error.stack }, 'url generation failed');
47
+ }
48
+ }
49
+ };
50
+ const assertColor = async (color) => {
51
+ let assertedColor;
52
+ if (typeof color === 'number') {
53
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
54
+ }
55
+ else {
56
+ let hex = color.trim().replace('#', '');
57
+ if (hex.length <= 6) {
58
+ hex = 'FF' + hex.padStart(6, '0');
59
+ }
60
+ assertedColor = parseInt(hex, 16);
61
+ return assertedColor;
62
+ }
63
+ };
64
+ export const prepareWAMessageMedia = async (message, options) => {
65
+ const logger = options.logger;
66
+ let mediaType;
67
+ for (const key of MEDIA_KEYS) {
68
+ if (key in message) {
69
+ mediaType = key;
70
+ }
71
+ }
72
+ if (!mediaType) {
73
+ throw new Boom('Invalid media type', { statusCode: 400 });
74
+ }
75
+ const uploadData = {
76
+ ...message,
77
+ media: message[mediaType]
78
+ };
79
+ delete uploadData[mediaType];
80
+ // check if cacheable + generate cache key
81
+ const cacheableKey = typeof uploadData.media === 'object' &&
82
+ 'url' in uploadData.media &&
83
+ !!uploadData.media.url &&
84
+ !!options.mediaCache &&
85
+ mediaType + ':' + uploadData.media.url.toString();
86
+ if (mediaType === 'document' && !uploadData.fileName) {
87
+ uploadData.fileName = 'file';
88
+ }
89
+ if (!uploadData.mimetype) {
90
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
91
+ }
92
+ if (cacheableKey) {
93
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
94
+ if (mediaBuff) {
95
+ logger?.debug({ cacheableKey }, 'got media cache hit');
96
+ const obj = proto.Message.decode(mediaBuff);
97
+ const key = `${mediaType}Message`;
98
+ Object.assign(obj[key], { ...uploadData, media: undefined });
99
+ return obj;
100
+ }
101
+ }
102
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
103
+ if (isNewsletter) {
104
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
105
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
106
+ const fileSha256B64 = fileSha256.toString('base64');
107
+ // Generate thumbnail for image/video before uploading (filePath still exists)
108
+ if ((mediaType === 'image' || mediaType === 'video') && !uploadData.jpegThumbnail) {
109
+ try {
110
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(filePath, mediaType, options);
111
+ uploadData.jpegThumbnail = thumbnail;
112
+ if (!uploadData.width && originalImageDimensions) {
113
+ uploadData.width = originalImageDimensions.width;
114
+ uploadData.height = originalImageDimensions.height;
115
+ }
116
+ } catch (e) {
117
+ logger?.warn({ err: e }, 'failed to generate thumbnail for newsletter media');
118
+ }
119
+ }
120
+ const { mediaUrl, directPath } = await options.upload(filePath, {
121
+ fileEncSha256B64: fileSha256B64,
122
+ mediaType: mediaType,
123
+ timeoutMs: options.mediaUploadTimeoutMs
124
+ });
125
+ await fs.unlink(filePath);
126
+ const obj = WAProto.Message.fromObject({
127
+ // todo: add more support here
128
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
129
+ url: mediaUrl,
130
+ directPath,
131
+ fileSha256,
132
+ fileLength,
133
+ ...uploadData,
134
+ media: undefined
135
+ })
136
+ });
137
+ if (uploadData.ptv) {
138
+ obj.ptvMessage = obj.videoMessage;
139
+ delete obj.videoMessage;
140
+ }
141
+ if (obj.stickerMessage) {
142
+ obj.stickerMessage.stickerSentTs = Date.now();
143
+ }
144
+ if (cacheableKey) {
145
+ logger?.debug({ cacheableKey }, 'set cache');
146
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
147
+ }
148
+ return obj;
149
+ }
150
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
151
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
152
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
153
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
154
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
155
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
156
+ logger,
157
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
158
+ opts: options.options
159
+ });
160
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
161
+ const [{ mediaUrl, directPath }] = await Promise.all([
162
+ (async () => {
163
+ const result = await options.upload(encFilePath, {
164
+ fileEncSha256B64,
165
+ mediaType,
166
+ timeoutMs: options.mediaUploadTimeoutMs
167
+ });
168
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
169
+ return result;
170
+ })(),
171
+ (async () => {
172
+ try {
173
+ if (requiresThumbnailComputation) {
174
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
175
+ uploadData.jpegThumbnail = thumbnail;
176
+ if (!uploadData.width && originalImageDimensions) {
177
+ uploadData.width = originalImageDimensions.width;
178
+ uploadData.height = originalImageDimensions.height;
179
+ logger?.debug('set dimensions');
180
+ }
181
+ logger?.debug('generated thumbnail');
182
+ }
183
+ if (requiresDurationComputation) {
184
+ uploadData.seconds = await getAudioDuration(originalFilePath);
185
+ logger?.debug('computed audio duration');
186
+ }
187
+ if (requiresWaveformProcessing) {
188
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
189
+ logger?.debug('processed waveform');
190
+ }
191
+ if (requiresAudioBackground) {
192
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
193
+ logger?.debug('computed backgroundColor audio status');
194
+ }
195
+ }
196
+ catch (error) {
197
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
198
+ }
199
+ })()
200
+ ]).finally(async () => {
201
+ try {
202
+ await fs.unlink(encFilePath);
203
+ if (originalFilePath) {
204
+ await fs.unlink(originalFilePath);
205
+ }
206
+ logger?.debug('removed tmp files');
207
+ }
208
+ catch (error) {
209
+ logger?.warn('failed to remove tmp file');
210
+ }
211
+ });
212
+ const obj = WAProto.Message.fromObject({
213
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
214
+ url: mediaUrl,
215
+ directPath,
216
+ mediaKey,
217
+ fileEncSha256,
218
+ fileSha256,
219
+ fileLength,
220
+ mediaKeyTimestamp: unixTimestampSeconds(),
221
+ ...uploadData,
222
+ media: undefined
223
+ })
224
+ });
225
+ if (uploadData.ptv) {
226
+ obj.ptvMessage = obj.videoMessage;
227
+ delete obj.videoMessage;
228
+ }
229
+ if (cacheableKey) {
230
+ logger?.debug({ cacheableKey }, 'set cache');
231
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
232
+ }
233
+ return obj;
234
+ };
235
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
236
+ ephemeralExpiration = ephemeralExpiration || 0;
237
+ const content = {
238
+ ephemeralMessage: {
239
+ message: {
240
+ protocolMessage: {
241
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
242
+ ephemeralExpiration
243
+ }
244
+ }
245
+ }
246
+ };
247
+ return WAProto.Message.fromObject(content);
248
+ };
249
+ /**
250
+ * Generate forwarded message content like WA does
251
+ * @param message the message to forward
252
+ * @param options.forceForward will show the message as forwarded even if it is from you
253
+ */
254
+ export const generateForwardMessageContent = (message, forceForward) => {
255
+ let content = message.message;
256
+ if (!content) {
257
+ throw new Boom('no content in message', { statusCode: 400 });
258
+ }
259
+ // hacky copy
260
+ content = normalizeMessageContent(content);
261
+ content = proto.Message.decode(proto.Message.encode(content).finish());
262
+ let key = Object.keys(content)[0];
263
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
264
+ score += message.key.fromMe && !forceForward ? 0 : 1;
265
+ if (key === 'conversation') {
266
+ content.extendedTextMessage = { text: content[key] };
267
+ delete content.conversation;
268
+ key = 'extendedTextMessage';
269
+ }
270
+ const key_ = content?.[key];
271
+ if (score > 0) {
272
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
273
+ }
274
+ else {
275
+ key_.contextInfo = {};
276
+ }
277
+ return content;
278
+ };
279
+ export const hasNonNullishProperty = (message, key) => {
280
+ return message != null &&
281
+ typeof message === 'object' &&
282
+ key in message &&
283
+ message[key] != null;
284
+ };
285
+ export const hasOptionalProperty = (obj, key) => {
286
+ return obj != null &&
287
+ typeof obj === 'object' &&
288
+ key in obj &&
289
+ obj[key] != null;
290
+ };
291
+ // Validate album message media to avoid bug
292
+ export const hasValidAlbumMedia = (message) => {
293
+ return message.imageMessage ||
294
+ message.videoMessage;
295
+ };
296
+ export const hasValidInteractiveHeader = (message) => {
297
+ return message.imageMessage ||
298
+ message.videoMessage ||
299
+ message.documentMessage ||
300
+ message.productMessage ||
301
+ message.locationMessage;
302
+ };
303
+ // Validate carousel cards header to avoid bug
304
+ export const hasValidCarouselHeader = (message) => {
305
+ return message.imageMessage ||
306
+ message.videoMessage ||
307
+ message.productMessage;
308
+ };
309
+ // Extract product message into a standalone function so it can also be reused as the header for interactive messages
310
+ const prepareProductMessage = async (message, options) => {
311
+ if (!message.businessOwnerJid) {
312
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
313
+ }
314
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
315
+ const content = {
316
+ ...message,
317
+ product: {
318
+ currencyCode: 'IDR',
319
+ priceAmount1000: 1000,
320
+ title: LIBRARY_NAME,
321
+ ...message.product,
322
+ productImage: imageMessage
323
+ }
324
+ };
325
+ delete content.image;
326
+ return content;
327
+ };
328
+ const prepareStickerPackMessage = async (message, options) => {
329
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: pontalabs', description = '🏷️ pontalabs/baileys' } = message;
330
+ if (stickers.length > 60) {
331
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
332
+ }
333
+ if (stickers.length === 0) {
334
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
335
+ }
336
+ if (!cover) {
337
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
338
+ }
339
+ const logger = options.logger;
340
+ let cacheableKey = false;
341
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
342
+ const urls = [];
343
+ for (let i = 0; i < stickers.length; i++) {
344
+ const data = stickers[i].data;
345
+ if (typeof data === 'object' && data?.url) {
346
+ urls.push(data.url);
347
+ }
348
+ }
349
+ if (urls.length > 0) {
350
+ cacheableKey = 'sticker:' + urls.join('@');
351
+ }
352
+ }
353
+ if (cacheableKey) {
354
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
355
+ if (mediaBuff) {
356
+ logger?.debug({ cacheableKey }, 'got media cache hit');
357
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
358
+ }
359
+ }
360
+ const lib = await getImageProcessingLibrary();
361
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
362
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
363
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
364
+ if (!hasSharp && !hasImage) {
365
+ throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
366
+ }
367
+ const stickerPackIdValue = generateMessageIDV2();
368
+ const stickerData = {};
369
+ const stickerMetadata = new Array(stickers.length);
370
+ for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
371
+ const promises = [];
372
+ const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length);
373
+ for (let j = i; j < chunkEnd; j++) {
374
+ promises.push((async (index) => {
375
+ const sticker = stickers[index];
376
+ const { stream } = await getStream(sticker.data);
377
+ const buffer = await toBuffer(stream);
378
+ let webpBuffer;
379
+ let isAnimated = false;
380
+ if (isWebPBuffer(buffer)) {
381
+ webpBuffer = buffer;
382
+ isAnimated = isAnimatedWebP(buffer);
383
+ }
384
+ else if (hasSharp) {
385
+ webpBuffer = await lib.sharp.default(buffer)
386
+ .resize(512, 512, { fit: 'inside' })
387
+ .webp({ quality: 80 })
388
+ .toBuffer();
389
+ }
390
+ else {
391
+ webpBuffer = await new lib.image.Transformer(buffer)
392
+ .resize(512, 512)
393
+ .webp(80);
394
+ }
395
+ if (webpBuffer.length > 1024 * 1024) {
396
+ throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
397
+ }
398
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
399
+ const fileName = `${hash}.webp`;
400
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
401
+ stickerMetadata[index] = {
402
+ fileName,
403
+ mimetype: 'image/webp',
404
+ isAnimated,
405
+ emojis: sticker.emojis || ['✨'],
406
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
407
+ };
408
+ })(j));
409
+ }
410
+ await Promise.all(promises);
411
+ }
412
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
413
+ const { stream: coverStream } = await getStream(cover);
414
+ const coverBuffer = await toBuffer(coverStream);
415
+ let coverWebpBuffer;
416
+ if (isWebPBuffer(coverBuffer)) {
417
+ coverWebpBuffer = coverBuffer;
418
+ }
419
+ else if (hasSharp) {
420
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
421
+ .resize(512, 512, { fit: 'inside' })
422
+ .webp({ quality: 80 })
423
+ .toBuffer();
424
+ }
425
+ else {
426
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
427
+ .resize(512, 512)
428
+ .webp(80);
429
+ }
430
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
431
+ const zipBuffer = await new Promise((resolve, reject) => {
432
+ zip(stickerData, (error, data) => error ? reject(error) : resolve(Buffer.from(data)));
433
+ });
434
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
435
+ logger,
436
+ opts: options.options
437
+ });
438
+ let stickerPackUploadResult;
439
+ try {
440
+ stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
441
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
442
+ mediaType: 'sticker-pack',
443
+ timeoutMs: options.mediaUploadTimeoutMs
444
+ });
445
+ }
446
+ finally {
447
+ fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
448
+ }
449
+ const obj = {
450
+ name,
451
+ publisher,
452
+ stickerPackId: stickerPackIdValue,
453
+ packDescription: description,
454
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
455
+ stickerPackSize: zipBuffer.length,
456
+ stickers: stickerMetadata,
457
+ fileSha256: stickerPackUpload.fileSha256,
458
+ fileEncSha256: stickerPackUpload.fileEncSha256,
459
+ mediaKey: stickerPackUpload.mediaKey,
460
+ directPath: stickerPackUploadResult.directPath,
461
+ fileLength: stickerPackUpload.fileLength,
462
+ mediaKeyTimestamp: unixTimestampSeconds(),
463
+ trayIconFileName
464
+ };
465
+ try {
466
+ let thumbnailBuffer;
467
+ if (hasSharp) {
468
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
469
+ }
470
+ else if (hasImage) {
471
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
472
+ }
473
+ else if (hasJimp) {
474
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
475
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
476
+ }
477
+ else {
478
+ throw new Error('No image processing library available for thumbnail generation');
479
+ }
480
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
481
+ throw new Error('Failed to generate thumbnail buffer');
482
+ }
483
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
484
+ logger,
485
+ opts: options.options,
486
+ mediaKey: stickerPackUpload.mediaKey
487
+ });
488
+ let thumbUploadResult;
489
+ try {
490
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
491
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
492
+ mediaType: 'thumbnail-sticker-pack',
493
+ timeoutMs: options.mediaUploadTimeoutMs
494
+ });
495
+ }
496
+ finally {
497
+ fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
498
+ }
499
+ Object.assign(obj, {
500
+ thumbnailDirectPath: thumbUploadResult.directPath,
501
+ thumbnailSha256: thumbUpload.fileSha256,
502
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
503
+ thumbnailHeight: 252,
504
+ thumbnailWidth: 252,
505
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
506
+ });
507
+ }
508
+ catch (error) {
509
+ logger?.warn(`Thumbnail generation failed: ${error}`);
510
+ }
511
+ if (cacheableKey) {
512
+ logger?.debug({ cacheableKey }, 'set cache (background)');
513
+ options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish());
514
+ }
515
+ return WAProto.Message.StickerPackMessage.fromObject(obj);
516
+ };
517
+ const prepareNativeFlowButtons = (message) => {
518
+ const buttons = message.nativeFlow;
519
+ const isButtonsFieldArray = Array.isArray(buttons);
520
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
521
+ const messageParamsJson = {};
522
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
523
+ Object.assign(messageParamsJson, {
524
+ limited_time_offer: {
525
+ text: message.offerText || LIBRARY_NAME,
526
+ url: (message.offerUrl && /^https?:\/\//i.test(message.offerUrl)) ? message.offerUrl : DONATE_URL,
527
+ copy_code: message.offerCode,
528
+ expiration_time: message.offerExpiration
529
+ }
530
+ });
531
+ }
532
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
533
+ Object.assign(messageParamsJson, {
534
+ bottom_sheet: {
535
+ in_thread_buttons_limit: 1,
536
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
537
+ list_title: message.optionTitle || '📄 Select Options',
538
+ button_title: message.optionText
539
+ }
540
+ });
541
+ }
542
+ return {
543
+ buttons: correctedField.map(button => {
544
+ const buttonText = button.text || button.buttonText;
545
+ const buttonIcon = button.icon?.toUpperCase();
546
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
547
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: buttonText || '👉🏻 Click', id: button.id, icon: buttonIcon }) };
548
+ }
549
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
550
+ return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: buttonText || '📋 Copy', copy_code: button.copy, icon: buttonIcon }) };
551
+ }
552
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
553
+ return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: buttonText || '🌐 Visit', url: button.url, merchant_url: button.url, webview_interaction: button.useWebview, icon: buttonIcon }) };
554
+ }
555
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
556
+ return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: buttonText || '📞 Call', phone_number: button.call, icon: buttonIcon }) };
557
+ }
558
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
559
+ return { name: 'single_select', buttonParamsJson: JSON.stringify({ title: buttonText || '📋 Select', sections: button.sections, icon: buttonIcon }) };
560
+ }
561
+ return button;
562
+ }),
563
+ messageParamsJson: JSON.stringify(messageParamsJson),
564
+ messageVersion: 3
565
+ };
566
+ };
567
+ export const generateWAMessageContent = async (message, options) => {
568
+ var _a, _b;
569
+ let m = {};
570
+ if (hasNonNullishProperty(message, 'raw')) {
571
+ delete message.raw;
572
+ return message;
573
+ }
574
+ else if (hasNonNullishProperty(message, 'code') ||
575
+ hasNonNullishProperty(message, 'links') ||
576
+ hasNonNullishProperty(message, 'table') ||
577
+ hasNonNullishProperty(message, 'richResponse') ||
578
+ hasNonNullishProperty(message, 'latex') ||
579
+ hasNonNullishProperty(message, 'gridImage') ||
580
+ hasNonNullishProperty(message, 'inlineImage') ||
581
+ hasNonNullishProperty(message, 'dynamic') ||
582
+ hasNonNullishProperty(message, 'map') ||
583
+ hasNonNullishProperty(message, 'contentItems') ||
584
+ // tipe baru (nama prefixed 'rich' agar tidak konflik dengan media biasa)
585
+ hasNonNullishProperty(message, 'richImage') ||
586
+ hasNonNullishProperty(message, 'richVideo') ||
587
+ hasNonNullishProperty(message, 'reels') ||
588
+ hasNonNullishProperty(message, 'source') ||
589
+ hasNonNullishProperty(message, 'richProduct') ||
590
+ hasNonNullishProperty(message, 'richPost') ||
591
+ hasNonNullishProperty(message, 'tip') ||
592
+ hasNonNullishProperty(message, 'suggest')) {
593
+ m = prepareRichResponseMessage(message);
594
+ }
595
+ else if (hasNonNullishProperty(message, 'text')) {
596
+ const extContent = { text: message.text };
597
+ let urlInfo = message.linkPreview;
598
+ if (typeof urlInfo === 'undefined') {
599
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
600
+ }
601
+ if (urlInfo) {
602
+ extContent.matchedText = urlInfo['matched-text'];
603
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
604
+ extContent.description = urlInfo.description;
605
+ extContent.title = urlInfo.title;
606
+ extContent.previewType = 0;
607
+ const img = urlInfo.highQualityThumbnail;
608
+ if (img) {
609
+ extContent.thumbnailDirectPath = img.directPath;
610
+ extContent.mediaKey = img.mediaKey;
611
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
612
+ extContent.thumbnailWidth = img.width;
613
+ extContent.thumbnailHeight = img.height;
614
+ extContent.thumbnailSha256 = img.fileSha256;
615
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
616
+ }
617
+ }
618
+ if (options.backgroundColor) {
619
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
620
+ }
621
+ if (options.font) {
622
+ extContent.font = options.font;
623
+ }
624
+ m.extendedTextMessage = extContent;
625
+ }
626
+ else if (hasNonNullishProperty(message, 'contacts')) {
627
+ const contactLen = message.contacts.contacts.length;
628
+ if (!contactLen) {
629
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
630
+ }
631
+ if (contactLen === 1) {
632
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
633
+ }
634
+ else {
635
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
636
+ }
637
+ }
638
+ else if (hasNonNullishProperty(message, 'location')) {
639
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
640
+ }
641
+ else if (hasNonNullishProperty(message, 'react')) {
642
+ if (!message.react.senderTimestampMs) {
643
+ message.react.senderTimestampMs = Date.now();
644
+ }
645
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
646
+ }
647
+ else if (hasNonNullishProperty(message, 'delete')) {
648
+ m.protocolMessage = {
649
+ key: message.delete,
650
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
651
+ };
652
+ }
653
+ else if (hasNonNullishProperty(message, 'forward')) {
654
+ m = generateForwardMessageContent(message.forward, message.force);
655
+ }
656
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
657
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
658
+ ? message.disappearingMessagesInChat
659
+ ? WA_DEFAULT_EPHEMERAL
660
+ : 0
661
+ : message.disappearingMessagesInChat;
662
+ m = prepareDisappearingMessageSettingContent(exp);
663
+ }
664
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
665
+ m.groupInviteMessage = {};
666
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
667
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
668
+ m.groupInviteMessage.caption = message.groupInvite.text;
669
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
670
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
671
+ //TODO: use built-in interface and get disappearing mode info etc.
672
+ //TODO: cache / use store!?
673
+ if (options.getProfilePicUrl) {
674
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
675
+ if (pfpUrl) {
676
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
677
+ if (resp.ok) {
678
+ const buf = Buffer.from(await resp.arrayBuffer());
679
+ m.groupInviteMessage.jpegThumbnail = buf;
680
+ }
681
+ }
682
+ }
683
+ }
684
+ else if (hasNonNullishProperty(message, 'stickers')) {
685
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
686
+ }
687
+ else if (hasNonNullishProperty(message, 'pin')) {
688
+ m.pinInChatMessage = {};
689
+ m.messageContextInfo = {};
690
+ m.pinInChatMessage.key = message.pin;
691
+ m.pinInChatMessage.type = message.type;
692
+ m.pinInChatMessage.senderTimestampMs = Date.now();
693
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
694
+ }
695
+ else if (hasNonNullishProperty(message, 'keep')) {
696
+ m.keepInChatMessage = {};
697
+ m.keepInChatMessage.key = message.keep;
698
+ m.keepInChatMessage.keepType = message.type;
699
+ m.keepInChatMessage.timestampMs = Date.now();
700
+ }
701
+ else if (hasNonNullishProperty(message, 'flowReply')) {
702
+ m.interactiveResponseMessage = {
703
+ body: {
704
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
705
+ text: message.flowReply.text
706
+ },
707
+ nativeFlowResponseMessage: {
708
+ name: message.flowReply.name,
709
+ paramsJson: message.flowReply.paramsJson || '{}',
710
+ version: message.flowReply.version || 1
711
+ }
712
+ };
713
+ }
714
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
715
+ switch (message.type) {
716
+ case 'template':
717
+ m.templateButtonReplyMessage = {
718
+ selectedDisplayText: message.buttonReply.displayText,
719
+ selectedId: message.buttonReply.id,
720
+ selectedIndex: message.buttonReply.index
721
+ };
722
+ break;
723
+ case 'plain':
724
+ m.buttonsResponseMessage = {
725
+ selectedButtonId: message.buttonReply.id,
726
+ selectedDisplayText: message.buttonReply.displayText,
727
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
728
+ };
729
+ break;
730
+ }
731
+ }
732
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
733
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
734
+ m.ptvMessage = videoMessage;
735
+ }
736
+ else if (hasNonNullishProperty(message, 'product')) {
737
+ if (!message.businessOwnerJid) {
738
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
739
+ }
740
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
741
+ const content = {
742
+ ...message,
743
+ product: {
744
+ currencyCode: 'IDR',
745
+ priceAmount1000: 1000,
746
+ title: LIBRARY_NAME,
747
+ ...message.product,
748
+ productImage: imageMessage
749
+ }
750
+ };
751
+ delete content.image;
752
+ m.productMessage = WAProto.Message.ProductMessage.create(content);
753
+ }
754
+ else if (hasNonNullishProperty(message, 'listReply')) {
755
+ m.listResponseMessage = {
756
+ description: message.listReply.description,
757
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
758
+ singleSelectReply: {
759
+ selectedRowId: message.listReply.id
760
+ },
761
+ title: message.listReply.title
762
+ };
763
+ }
764
+ else if (hasNonNullishProperty(message, 'event')) {
765
+ m.eventMessage = {};
766
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
767
+ if (message.event.call && options.getCallLink) {
768
+ const token = await options.getCallLink(message.event.call, { startTime });
769
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
770
+ }
771
+ m.messageContextInfo = {
772
+ // encKey
773
+ messageSecret: message.event.messageSecret || randomBytes(32)
774
+ };
775
+ m.eventMessage.name = message.event.name;
776
+ m.eventMessage.description = message.event.description;
777
+ m.eventMessage.startTime = startTime;
778
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
779
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
780
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
781
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
782
+ m.eventMessage.location = message.event.location;
783
+ }
784
+ else if (hasNonNullishProperty(message, 'poll')) {
785
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
786
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
787
+ if (!Array.isArray(message.poll.values)) {
788
+ throw new Boom('Invalid poll values', { statusCode: 400 });
789
+ }
790
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
791
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
792
+ statusCode: 400
793
+ });
794
+ }
795
+ const pollCreationMessage = {
796
+ name: message.poll.name,
797
+ selectableOptionsCount: message.poll.selectableCount,
798
+ options: message.poll.values.map(optionName => ({ optionName })),
799
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
800
+ hideParticipantName: message.poll.hideVoter ?? false,
801
+ allowAddOption: message.poll.canAddOption ?? false
802
+ };
803
+ if (message.poll.toAnnouncementGroup) {
804
+ // poll v2 is for community announcement groups (single select and multiple)
805
+ m.pollCreationMessageV2 = pollCreationMessage;
806
+ }
807
+ else {
808
+ // Add quiz message support
809
+ if (message.poll.pollType === 1) {
810
+ if (!message.poll.correctAnswer) {
811
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
812
+ }
813
+ m.pollCreationMessageV5 = {
814
+ // quiz for newsletter only
815
+ ...pollCreationMessage,
816
+ correctAnswer: {
817
+ optionName: message.poll.correctAnswer.toString()
818
+ },
819
+ pollType: 1,
820
+ selectableOptionsCount: 1
821
+ };
822
+ }
823
+ else if (message.poll.selectableCount === 1) {
824
+ //poll v3 is for single select polls
825
+ m.pollCreationMessageV3 = pollCreationMessage;
826
+ }
827
+ else {
828
+ // poll for multiple choice polls
829
+ m.pollCreationMessage = pollCreationMessage;
830
+ }
831
+ }
832
+ m.messageContextInfo = {
833
+ // encKey
834
+ messageSecret: message.poll.messageSecret || randomBytes(32)
835
+ };
836
+ }
837
+ else if (hasNonNullishProperty(message, 'pollResult')) {
838
+ const pollResultSnapshotMessage = {
839
+ name: message.pollResult.name,
840
+ pollVotes: message.pollResult.votes.map(vote => ({
841
+ optionName: vote.name,
842
+ optionVoteCount: parseInt(vote.voteCount)
843
+ }))
844
+ };
845
+ if (message.pollResult.pollType === 1) {
846
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
847
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
848
+ }
849
+ else {
850
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
851
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
852
+ }
853
+ }
854
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
855
+ if (!message.pollUpdate.key) {
856
+ throw new Boom('Message key is required', { statusCode: 400 });
857
+ }
858
+ if (!message.pollUpdate.vote) {
859
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
860
+ }
861
+ m.pollUpdateMessage = {
862
+ metadata: message.pollUpdate.metadata,
863
+ pollCreationMessageKey: message.pollUpdate.key,
864
+ senderTimestampMs: Date.now(),
865
+ vote: message.pollUpdate.vote
866
+ };
867
+ }
868
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
869
+ m.paymentInviteMessage = {
870
+ expiryTimestamp: Date.now(),
871
+ serviceType: message.paymentInviteServiceType
872
+ };
873
+ }
874
+ else if (hasNonNullishProperty(message, 'orderText')) {
875
+ if (!Buffer.isBuffer(message.thumbnail)) {
876
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
877
+ }
878
+ m.orderMessage = {
879
+ itemCount: 1,
880
+ messageVersion: 1,
881
+ orderTitle: LIBRARY_NAME,
882
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
883
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
884
+ token: generateMessageIDV2(),
885
+ totalAmount1000: 1000,
886
+ totalCurrencyCode: 'IDR',
887
+ ...message,
888
+ message: message.orderText
889
+ };
890
+ delete m.orderMessage.orderText;
891
+ }
892
+ else if (hasNonNullishProperty(message, 'album')) {
893
+ if (!Array.isArray(message.album)) {
894
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
895
+ }
896
+ let videoCount = 0;
897
+ for (let i = 0; i < message.album.length; i++) {
898
+ if (message.album[i].video)
899
+ videoCount++;
900
+ }
901
+ ;
902
+ let imageCount = 0;
903
+ for (let i = 0; i < message.album.length; i++) {
904
+ if (message.album[i].image)
905
+ imageCount++;
906
+ }
907
+ ;
908
+ if ((videoCount + imageCount) < 2) {
909
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
910
+ }
911
+ m.albumMessage = {
912
+ expectedImageCount: imageCount,
913
+ expectedVideoCount: videoCount
914
+ };
915
+ }
916
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
917
+ m.protocolMessage = {
918
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
919
+ };
920
+ }
921
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
922
+ m.requestPhoneNumberMessage = {};
923
+ }
924
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
925
+ m.protocolMessage = {
926
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
927
+ limitSharing: {
928
+ sharingLimited: message.limitSharing === true,
929
+ trigger: 1,
930
+ limitSharingSettingTimestamp: Date.now(),
931
+ initiatedByMe: true
932
+ }
933
+ };
934
+ }
935
+ else if (hasNonNullishProperty(message, 'buttonsMessage')) {
936
+ // Direct buttonsMessage passthrough — supports headerType 6 (locationMessage), etc.
937
+ const btnMsg = { ...message.buttonsMessage };
938
+ if (btnMsg.locationMessage?.jpegThumbnail && !Buffer.isBuffer(btnMsg.locationMessage.jpegThumbnail)) {
939
+ const lib = await getImageProcessingLibrary();
940
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
941
+ if (hasSharp) {
942
+ const rawBuf = typeof btnMsg.locationMessage.jpegThumbnail === 'string'
943
+ ? (await fs.readFile(btnMsg.locationMessage.jpegThumbnail))
944
+ : btnMsg.locationMessage.jpegThumbnail;
945
+ btnMsg.locationMessage.jpegThumbnail = await lib.sharp.default(rawBuf)
946
+ .resize(300, 300, { fit: 'inside', withoutEnlargement: true })
947
+ .jpeg({ quality: 80 })
948
+ .toBuffer();
949
+ }
950
+ }
951
+ m = { buttonsMessage: btnMsg };
952
+ }
953
+ else {
954
+ m = await prepareWAMessageMedia(message, options);
955
+ }
956
+ if (hasNonNullishProperty(message, 'buttons')) {
957
+ const buttonsMessage = {
958
+ buttons: message.buttons.map(button => {
959
+ const buttonText = button.text || button.buttonText;
960
+ if (hasOptionalProperty(button, 'sections')) {
961
+ return {
962
+ nativeFlowInfo: {
963
+ name: 'single_select',
964
+ paramsJson: JSON.stringify({
965
+ title: buttonText,
966
+ sections: button.sections
967
+ })
968
+ },
969
+ type: ButtonType.NATIVE_FLOW
970
+ };
971
+ }
972
+ else if (hasOptionalProperty(button, 'name')) {
973
+ return {
974
+ nativeFlowInfo: {
975
+ name: button.name,
976
+ paramsJson: button.paramsJson
977
+ },
978
+ type: ButtonType.NATIVE_FLOW
979
+ };
980
+ }
981
+ return {
982
+ buttonId: button.id || button.buttonId,
983
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
984
+ type: button.type || ButtonType.RESPONSE
985
+ };
986
+ })
987
+ };
988
+ if (hasOptionalProperty(message, 'text')) {
989
+ buttonsMessage.contentText = message.text;
990
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
991
+ }
992
+ else {
993
+ if (hasOptionalProperty(message, 'caption')) {
994
+ buttonsMessage.contentText = message.caption;
995
+ }
996
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
997
+ buttonsMessage.headerType = ButtonHeaderType[type];
998
+ Object.assign(buttonsMessage, m);
999
+ }
1000
+ if (hasOptionalProperty(message, 'footer')) {
1001
+ buttonsMessage.footerText = message.footer;
1002
+ }
1003
+ m = { buttonsMessage };
1004
+ }
1005
+ else if (hasNonNullishProperty(message, 'sections')) {
1006
+ const listMessage = {
1007
+ sections: message.sections,
1008
+ buttonText: message.buttonText,
1009
+ title: message.title,
1010
+ footerText: message.footer,
1011
+ description: message.text,
1012
+ listType: ListType.SINGLE_SELECT
1013
+ };
1014
+ m = { listMessage };
1015
+ }
1016
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1017
+ const hydratedTemplate = {
1018
+ hydratedButtons: message.templateButtons.map((button, i) => {
1019
+ const buttonText = button.text || button.buttonText;
1020
+ if (hasOptionalProperty(button, 'id')) {
1021
+ return {
1022
+ index: i,
1023
+ quickReplyButton: {
1024
+ displayText: buttonText || '👉🏻 Click',
1025
+ id: button.id
1026
+ }
1027
+ };
1028
+ }
1029
+ else if (hasOptionalProperty(button, 'url')) {
1030
+ return {
1031
+ index: i,
1032
+ urlButton: {
1033
+ displayText: buttonText || '🌐 Visit',
1034
+ url: button.url
1035
+ }
1036
+ };
1037
+ }
1038
+ else if (hasOptionalProperty(button, 'call')) {
1039
+ return {
1040
+ index: i,
1041
+ callButton: {
1042
+ displayText: buttonText || '📞 Call',
1043
+ phoneNumber: button.call
1044
+ }
1045
+ };
1046
+ }
1047
+ button.index = button.index || i;
1048
+ return button;
1049
+ })
1050
+ };
1051
+ if (hasOptionalProperty(message, 'text')) {
1052
+ hydratedTemplate.hydratedContentText = message.text;
1053
+ }
1054
+ else {
1055
+ if (hasOptionalProperty(message, 'caption')) {
1056
+ hydratedTemplate.hydratedTitleText = message.title;
1057
+ hydratedTemplate.hydratedContentText = message.caption;
1058
+ }
1059
+ ;
1060
+ Object.assign(hydratedTemplate, m);
1061
+ }
1062
+ if (hasOptionalProperty(message, 'footer')) {
1063
+ hydratedTemplate.hydratedFooterText = message.footer;
1064
+ }
1065
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now();
1066
+ m = {
1067
+ templateMessage: {
1068
+ hydratedFourRowTemplate: hydratedTemplate,
1069
+ hydratedTemplate: hydratedTemplate
1070
+ }
1071
+ };
1072
+ }
1073
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1074
+ const interactiveMessage = {
1075
+ nativeFlowMessage: prepareNativeFlowButtons(message)
1076
+ };
1077
+ if (hasOptionalProperty(message, 'bizJid')) {
1078
+ interactiveMessage.collectionMessage = {
1079
+ bizJid: message.bizJid,
1080
+ id: message.id,
1081
+ messageVersion: 1
1082
+ };
1083
+ }
1084
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1085
+ interactiveMessage.shopStorefrontMessage = {
1086
+ surface: message.shopSurface,
1087
+ id: message.id,
1088
+ messageVersion: 1
1089
+ };
1090
+ }
1091
+ if (hasOptionalProperty(message, 'text')) {
1092
+ interactiveMessage.body = { text: message.text };
1093
+ }
1094
+ else {
1095
+ if (hasOptionalProperty(message, 'caption')) {
1096
+ const isValidHeader = hasValidInteractiveHeader(m);
1097
+ if (!isValidHeader) {
1098
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1099
+ }
1100
+ interactiveMessage.header = {
1101
+ title: message.title || '',
1102
+ subtitle: message.subtitle || '',
1103
+ hasMediaAttachment: isValidHeader
1104
+ };
1105
+ interactiveMessage.body = { text: message.caption };
1106
+ }
1107
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1108
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1109
+ }
1110
+ Object.assign(interactiveMessage.header, m);
1111
+ }
1112
+ if (hasOptionalProperty(message, 'audioFooter')) {
1113
+ const { audioMessage } = await prepareWAMessageMedia({
1114
+ audio: message.audioFooter
1115
+ }, options);
1116
+ interactiveMessage.footer = {
1117
+ audioMessage,
1118
+ hasMediaAttachment: true
1119
+ };
1120
+ }
1121
+ else if (hasOptionalProperty(message, 'footer')) {
1122
+ interactiveMessage.footer = { text: message.footer };
1123
+ }
1124
+ m = { interactiveMessage };
1125
+ }
1126
+ else if (hasNonNullishProperty(message, 'cards')) {
1127
+ const interactiveMessage = {
1128
+ carouselMessage: {
1129
+ cards: await Promise.all(message.cards.map(async (card) => {
1130
+ let carouselHeader = {};
1131
+ if (hasNonNullishProperty(card, 'product')) {
1132
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1133
+ }
1134
+ else {
1135
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1136
+ }
1137
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1138
+ if (!isValidHeader) {
1139
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1140
+ }
1141
+ const carouselCard = {
1142
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1143
+ };
1144
+ if (hasOptionalProperty(card, 'text')) {
1145
+ carouselCard.body = { text: card.text };
1146
+ }
1147
+ else {
1148
+ if (hasOptionalProperty(card, 'caption')) {
1149
+ carouselCard.header = {
1150
+ title: card.title || '',
1151
+ subtitle: card.subtitle || '',
1152
+ hasMediaAttachment: isValidHeader
1153
+ };
1154
+ carouselCard.body = { text: card.caption };
1155
+ }
1156
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1157
+ carouselCard.jpegThumbnail = card.thumbnail;
1158
+ }
1159
+ Object.assign(carouselCard.header, carouselHeader);
1160
+ }
1161
+ if (hasOptionalProperty(card, 'audioFooter')) {
1162
+ const { audioMessage } = await prepareWAMessageMedia({
1163
+ audio: card.audioFooter
1164
+ }, options);
1165
+ carouselCard.footer = {
1166
+ audioMessage,
1167
+ hasMediaAttachment: true
1168
+ };
1169
+ }
1170
+ else if (hasOptionalProperty(card, 'footer')) {
1171
+ carouselCard.footer = { text: card.footer };
1172
+ }
1173
+ return carouselCard;
1174
+ })),
1175
+ carouselCardType: CarouselCardType.UNKNOWN,
1176
+ messageVersion: 1
1177
+ }
1178
+ };
1179
+ if (hasOptionalProperty(message, 'text')) {
1180
+ interactiveMessage.body = { text: message.text };
1181
+ }
1182
+ if (hasOptionalProperty(message, 'footer')) {
1183
+ interactiveMessage.footer = { text: message.footer };
1184
+ }
1185
+ m = { interactiveMessage };
1186
+ }
1187
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1188
+ const requestPaymentMessage = {
1189
+ amount: {
1190
+ currencyCode: 'IDR',
1191
+ offset: 1000,
1192
+ value: 1000
1193
+ },
1194
+ amount1000: 1000,
1195
+ currencyCodeIso4217: 'IDR',
1196
+ expiryTimestamp: Date.now(),
1197
+ noteMessage: m,
1198
+ requestFrom: message.requestPaymentFrom,
1199
+ ...message
1200
+ };
1201
+ delete requestPaymentMessage.requestPaymentFrom;
1202
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1203
+ Object.assign(requestPaymentMessage.noteMessage, m);
1204
+ }
1205
+ else {
1206
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1207
+ }
1208
+ m = { requestPaymentMessage };
1209
+ }
1210
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1211
+ const attachment = m.imageMessage || m.documentMessage;
1212
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1213
+ const invoiceMessage = {
1214
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1215
+ note: message.invoiceNote
1216
+ };
1217
+ if (attachment) {
1218
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1219
+ Object.assign(invoiceMessage, {
1220
+ attachmentDirectPath: directPath,
1221
+ attachmentFileEncSha256: fileEncSha256,
1222
+ attachmentFileSha256: fileSha256,
1223
+ attachmentJpegThumbnail: jpegThumbnail,
1224
+ attachmentMediaKey: mediaKey,
1225
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1226
+ attachmentMimetype: mimetype,
1227
+ token: generateMessageIDV2()
1228
+ });
1229
+ }
1230
+ else {
1231
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1232
+ }
1233
+ m = { invoiceMessage };
1234
+ }
1235
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1236
+ const messageType = Object.keys(m)[0];
1237
+ const key = m[messageType];
1238
+ const content = message.externalAdReply;
1239
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1240
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1241
+ }
1242
+ if (!content.url || typeof content.url !== 'string' || !/^https?:\/\//i.test(content.url)) {
1243
+ options.logger?.warn({ givenUrl: content.url }, 'externalAdReply: field "url" kosong/tidak valid (harus diawali http:// atau https://) — fallback ke DONATE_URL, link produk asli TIDAK terkirim. Cek kode yang mengisi `url` di externalAdReply.');
1244
+ content.url = DONATE_URL;
1245
+ }
1246
+ const externalAdReply = {
1247
+ ...content,
1248
+ body: content.body,
1249
+ mediaType: content.mediaType || 1,
1250
+ mediaUrl: content.url,
1251
+ renderLargerThumbnail: content.largeThumbnail,
1252
+ sourceUrl: content.url,
1253
+ thumbnail: content.thumbnail,
1254
+ thumbnailUrl: content.url + '?update=' + Date.now(),
1255
+ title: content.title || LIBRARY_NAME
1256
+ };
1257
+ delete externalAdReply.subTitle;
1258
+ delete externalAdReply.largeThumbnail;
1259
+ delete externalAdReply.url;
1260
+ if ('contextInfo' in key && !!key.contextInfo) {
1261
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1262
+ }
1263
+ else if (key) {
1264
+ key.contextInfo = { externalAdReply };
1265
+ }
1266
+ }
1267
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1268
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1269
+ const messageType = Object.keys(m)[0];
1270
+ const key = m[messageType];
1271
+ if (key && 'contextInfo' in key) {
1272
+ key.contextInfo = key.contextInfo || {};
1273
+ if (message.mentions?.length) {
1274
+ key.contextInfo.mentionedJid = message.mentions;
1275
+ }
1276
+ if (message.mentionAll) {
1277
+ key.contextInfo.nonJidMentions = 1;
1278
+ }
1279
+ }
1280
+ else if (key) {
1281
+ key.contextInfo = {
1282
+ mentionedJid: message.mentions,
1283
+ nonJidMentions: message.mentionAll ? 1 : 0
1284
+ };
1285
+ }
1286
+ }
1287
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1288
+ const messageType = Object.keys(m)[0];
1289
+ const key = m[messageType];
1290
+ if ('contextInfo' in key && !!key.contextInfo) {
1291
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1292
+ }
1293
+ else if (key) {
1294
+ key.contextInfo = message.contextInfo;
1295
+ }
1296
+ }
1297
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1298
+ const messageType = Object.keys(m)[0];
1299
+ const key = m[messageType];
1300
+ if ('contextInfo' in key && !!key.contextInfo) {
1301
+ key.contextInfo.isGroupStatus = message.groupStatus;
1302
+ }
1303
+ else if (key) {
1304
+ key.contextInfo = {
1305
+ isGroupStatus: message.groupStatus
1306
+ };
1307
+ }
1308
+ m = { groupStatusMessageV2: { message: m } };
1309
+ delete message.groupStatus;
1310
+ }
1311
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1312
+ const messageType = Object.keys(m)[0];
1313
+ const key = m[messageType];
1314
+ if ('contextInfo' in key && !!key.contextInfo) {
1315
+ key.contextInfo.isSpoiler = message.spoiler;
1316
+ }
1317
+ else if (key) {
1318
+ key.contextInfo = {
1319
+ isSpoiler: message.spoiler
1320
+ };
1321
+ }
1322
+ m = { spoilerMessage: { message: m } };
1323
+ delete message.spoiler;
1324
+ }
1325
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1326
+ if (!m.interactiveMessage) {
1327
+ throw new Boom('Invalid message type for template', { statusCode: 400 });
1328
+ }
1329
+ m = {
1330
+ templateMessage: {
1331
+ interactiveMessageTemplate: m.interactiveMessage,
1332
+ templateId: message.id || 'template-' + Date.now()
1333
+ }
1334
+ };
1335
+ delete message.interactiveAsTemplate;
1336
+ }
1337
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1338
+ m = { ephemeralMessage: { message: m } };
1339
+ delete message.ephemeral;
1340
+ }
1341
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1342
+ m = { lottieStickerMessage: { message: m } };
1343
+ }
1344
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1345
+ m = { viewOnceMessage: { message: m } };
1346
+ }
1347
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1348
+ m = { viewOnceMessageV2: { message: m } };
1349
+ delete message.viewOnceV2;
1350
+ }
1351
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1352
+ m = { viewOnceMessageV2Extension: { message: m } };
1353
+ delete message.viewOnceV2Extension;
1354
+ }
1355
+ if (hasOptionalProperty(message, 'edit')) {
1356
+ m = {
1357
+ protocolMessage: {
1358
+ key: message.edit,
1359
+ editedMessage: m,
1360
+ timestampMs: Date.now(),
1361
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1362
+ }
1363
+ };
1364
+ }
1365
+ if (shouldIncludeReportingToken(m)) {
1366
+ m.messageContextInfo = m.messageContextInfo || {};
1367
+ if (!m.messageContextInfo.messageSecret) {
1368
+ m.messageContextInfo.messageSecret = randomBytes(32);
1369
+ }
1370
+ }
1371
+ return WAProto.Message.create(m);
1372
+ };
1373
+ export const generateWAMessageFromContent = (jid, message, options) => {
1374
+ // set timestamp to now
1375
+ // if not specified
1376
+ if (!options.timestamp) {
1377
+ options.timestamp = new Date();
1378
+ }
1379
+ const innerMessage = normalizeMessageContent(message);
1380
+ const messageContextInfo = message.messageContextInfo;
1381
+ const key = getContentType(innerMessage);
1382
+ const timestamp = unixTimestampSeconds(options.timestamp);
1383
+ const isNewsletter = isJidNewsletter(jid);
1384
+ const { quoted, userJid } = options;
1385
+ if (quoted) {
1386
+ const participant = quoted.key.fromMe
1387
+ ? userJid // TODO: Add support for LIDs
1388
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1389
+ let quotedMsg = normalizeMessageContent(quoted.message);
1390
+ const msgType = getContentType(quotedMsg);
1391
+ // strip any redundant properties
1392
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1393
+ const quotedContent = quotedMsg[msgType];
1394
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1395
+ delete quotedContent.contextInfo;
1396
+ }
1397
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1398
+ contextInfo.participant = jidNormalizedUser(participant);
1399
+ contextInfo.stanzaId = quoted.key.id;
1400
+ contextInfo.quotedMessage = quotedMsg;
1401
+ // if a participant is quoted, then it must be a group
1402
+ // hence, remoteJid of group must also be entered
1403
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
1404
+ contextInfo.remoteJid = quoted.key.remoteJid;
1405
+ }
1406
+ if (contextInfo && innerMessage[key]) {
1407
+ /* @ts-ignore */
1408
+ innerMessage[key].contextInfo = contextInfo;
1409
+ }
1410
+ }
1411
+ if (
1412
+ // if we want to send a disappearing message
1413
+ !!options?.ephemeralExpiration &&
1414
+ // and it's not a protocol message -- delete, toggle disappear message
1415
+ key !== 'protocolMessage' &&
1416
+ // already not converted to disappearing message
1417
+ key !== 'ephemeralMessage' &&
1418
+ // newsletters don't support ephemeral messages
1419
+ !isNewsletter) {
1420
+ /* @ts-ignore */
1421
+ innerMessage[key].contextInfo = {
1422
+ ...(innerMessage[key].contextInfo || {}),
1423
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1424
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1425
+ };
1426
+ }
1427
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1428
+ messageContextInfo.deviceListMetadata = {
1429
+ recipientKeyHash: randomBytes(10),
1430
+ recipientTimestamp: unixTimestampSeconds()
1431
+ };
1432
+ messageContextInfo.deviceListMetadataVersion = 2;
1433
+ }
1434
+ message = WAProto.Message.create(message);
1435
+ const messageJSON = {
1436
+ key: {
1437
+ remoteJid: jid,
1438
+ fromMe: true,
1439
+ id: options?.messageId || generateMessageIDV2()
1440
+ },
1441
+ message: message,
1442
+ messageTimestamp: timestamp,
1443
+ messageStubParameters: [],
1444
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
1445
+ status: WAMessageStatus.PENDING
1446
+ };
1447
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1448
+ };
1449
+ export const generateWAMessage = async (jid, content, options) => {
1450
+ // ensure msg ID is with every log
1451
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1452
+ // Pass jid in the options to generateWAMessageContent
1453
+ if (jid) {
1454
+ options.jid = jid;
1455
+ }
1456
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1457
+ };
1458
+ /** Get the key to access the true type of content */
1459
+ export const getContentType = (content) => {
1460
+ if (content) {
1461
+ const keys = Object.keys(content);
1462
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1463
+ return key;
1464
+ }
1465
+ };
1466
+ export const normalizeMessageContent = (content) => {
1467
+ if (!content) {
1468
+ return undefined;
1469
+ }
1470
+ // set max iterations to prevent an infinite loop
1471
+ for (let i = 0; i < 5; i++) {
1472
+ const inner = getFutureProofMessage(content);
1473
+ if (!inner) {
1474
+ break;
1475
+ }
1476
+ content = inner.message;
1477
+ }
1478
+ return content;
1479
+ function getFutureProofMessage(message) {
1480
+ return (message?.associatedChildMessage ||
1481
+ message?.botForwardedMessage ||
1482
+ message?.botInvokeMessage ||
1483
+ message?.botTaskMessage ||
1484
+ message?.documentWithCaptionMessage ||
1485
+ message?.editedMessage ||
1486
+ message?.ephemeralMessage ||
1487
+ message?.eventCoverImage ||
1488
+ message?.groupMentionedMessage ||
1489
+ message?.groupStatusMentionMessage ||
1490
+ message?.groupStatusMessage ||
1491
+ message?.groupStatusMessageV2 ||
1492
+ message?.limitSharingMessage ||
1493
+ message?.lottieStickerMessage ||
1494
+ message?.newsletterAdminProfileMessage ||
1495
+ message?.newsletterAdminProfileMessageV2 ||
1496
+ message?.newsletterAdminProfileStatusMessage ||
1497
+ message?.pollCreationMessageV4 ||
1498
+ message?.pollCreationOptionImageMessage ||
1499
+ message?.questionMessage ||
1500
+ message?.questionReplyMessage ||
1501
+ message?.spoilerMessage ||
1502
+ message?.statusAddYours ||
1503
+ message?.statusMentionMessage ||
1504
+ message?.viewOnceMessage ||
1505
+ message?.viewOnceMessageV2 ||
1506
+ message?.viewOnceMessageV2Extension);
1507
+ }
1508
+ };
1509
+ /**
1510
+ * Extract the true message content from a message
1511
+ * Eg. extracts the inner message from a disappearing message/view once message
1512
+ */
1513
+ export const extractMessageContent = (content) => {
1514
+ const extractFromTemplateMessage = (msg) => {
1515
+ if (msg.imageMessage) {
1516
+ return { imageMessage: msg.imageMessage };
1517
+ }
1518
+ else if (msg.documentMessage) {
1519
+ return { documentMessage: msg.documentMessage };
1520
+ }
1521
+ else if (msg.videoMessage) {
1522
+ return { videoMessage: msg.videoMessage };
1523
+ }
1524
+ else if (msg.locationMessage) {
1525
+ return { locationMessage: msg.locationMessage };
1526
+ }
1527
+ else {
1528
+ return {
1529
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1530
+ };
1531
+ }
1532
+ };
1533
+ content = normalizeMessageContent(content);
1534
+ if (content?.buttonsMessage) {
1535
+ return extractFromTemplateMessage(content.buttonsMessage);
1536
+ }
1537
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1538
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1539
+ }
1540
+ if (content?.templateMessage?.hydratedTemplate) {
1541
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1542
+ }
1543
+ if (content?.templateMessage?.fourRowTemplate) {
1544
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1545
+ }
1546
+ return content;
1547
+ };
1548
+ /**
1549
+ * Returns the device predicted by message ID
1550
+ */
1551
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1552
+ ? 'ios'
1553
+ : /^3E.{20}$/.test(id)
1554
+ ? 'web'
1555
+ : /^(.{21}|.{32})$/.test(id)
1556
+ ? 'android'
1557
+ : /^(3F|.{18}$)/.test(id)
1558
+ ? 'desktop'
1559
+ : 'unknown';
1560
+ /** Upserts a receipt in the message */
1561
+ export const updateMessageWithReceipt = (msg, receipt) => {
1562
+ msg.userReceipt = msg.userReceipt || [];
1563
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1564
+ if (recp) {
1565
+ Object.assign(recp, receipt);
1566
+ }
1567
+ else {
1568
+ msg.userReceipt.push(receipt);
1569
+ }
1570
+ };
1571
+ /** Update the message with a new reaction */
1572
+ export const updateMessageWithReaction = (msg, reaction) => {
1573
+ const authorID = getKeyAuthor(reaction.key);
1574
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
1575
+ reaction.text = reaction.text || '';
1576
+ reactions.push(reaction);
1577
+ msg.reactions = reactions;
1578
+ };
1579
+ /** Update the message with a new poll update */
1580
+ export const updateMessageWithPollUpdate = (msg, update) => {
1581
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1582
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
1583
+ if (update.vote?.selectedOptions?.length) {
1584
+ reactions.push(update);
1585
+ }
1586
+ msg.pollUpdates = reactions;
1587
+ };
1588
+ /** Update the message with a new event response */
1589
+ export const updateMessageWithEventResponse = (msg, update) => {
1590
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1591
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1592
+ responses.push(update);
1593
+ msg.eventResponses = responses;
1594
+ };
1595
+ /**
1596
+ * Aggregates all poll updates in a poll.
1597
+ * @param msg the poll creation message
1598
+ * @param meId your jid
1599
+ * @returns A list of options & their voters
1600
+ */
1601
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1602
+ const opts = message?.pollCreationMessage?.options ||
1603
+ message?.pollCreationMessageV2?.options ||
1604
+ message?.pollCreationMessageV3?.options ||
1605
+ [];
1606
+ const voteHashMap = opts.reduce((acc, opt) => {
1607
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
1608
+ acc[hash] = {
1609
+ name: opt.optionName || '',
1610
+ voters: []
1611
+ };
1612
+ return acc;
1613
+ }, {});
1614
+ for (const update of pollUpdates || []) {
1615
+ const { vote } = update;
1616
+ if (!vote) {
1617
+ continue;
1618
+ }
1619
+ for (const option of vote.selectedOptions || []) {
1620
+ const hash = option.toString();
1621
+ let data = voteHashMap[hash];
1622
+ if (!data) {
1623
+ voteHashMap[hash] = {
1624
+ name: 'Unknown',
1625
+ voters: []
1626
+ };
1627
+ data = voteHashMap[hash];
1628
+ }
1629
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
1630
+ }
1631
+ }
1632
+ return Object.values(voteHashMap);
1633
+ }
1634
+ /**
1635
+ * Aggregates all event responses in an event message.
1636
+ * @param msg the event creation message
1637
+ * @param meId your jid
1638
+ * @returns A list of response types & their responders
1639
+ */
1640
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1641
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1642
+ const responseMap = {};
1643
+ for (const type of responseTypes) {
1644
+ responseMap[type] = {
1645
+ response: type,
1646
+ responders: []
1647
+ };
1648
+ }
1649
+ for (const update of eventResponses || []) {
1650
+ const responseType = update.eventResponse || 'UNKNOWN';
1651
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1652
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1653
+ }
1654
+ }
1655
+ return Object.values(responseMap);
1656
+ }
1657
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1658
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1659
+ const keyMap = {};
1660
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1661
+ if (!fromMe) {
1662
+ const uqKey = `${remoteJid}:${participant || ''}`;
1663
+ if (!keyMap[uqKey]) {
1664
+ keyMap[uqKey] = {
1665
+ jid: remoteJid,
1666
+ participant: participant,
1667
+ messageIds: []
1668
+ };
1669
+ }
1670
+ keyMap[uqKey].messageIds.push(id);
1671
+ }
1672
+ }
1673
+ return Object.values(keyMap);
1674
+ };
1675
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1676
+ /**
1677
+ * Downloads the given message. Throws an error if it's not a media message
1678
+ */
1679
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1680
+ const result = await downloadMsg().catch(async (error) => {
1681
+ if (ctx &&
1682
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
1683
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1684
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1685
+ // request reupload
1686
+ message = await ctx.reuploadRequest(message);
1687
+ const result = await downloadMsg();
1688
+ return result;
1689
+ }
1690
+ throw error;
1691
+ });
1692
+ return result;
1693
+ async function downloadMsg() {
1694
+ const mContent = extractMessageContent(message.message);
1695
+ if (!mContent) {
1696
+ throw new Boom('No message present', { statusCode: 400, data: message });
1697
+ }
1698
+ const contentType = getContentType(mContent);
1699
+ let mediaType = contentType?.replace('Message', '');
1700
+ const media = mContent[contentType];
1701
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1702
+ throw new Boom(`"${contentType}" message is not a media message`);
1703
+ }
1704
+ let download;
1705
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1706
+ download = {
1707
+ directPath: media.thumbnailDirectPath,
1708
+ mediaKey: media.mediaKey
1709
+ };
1710
+ mediaType = 'thumbnail-link';
1711
+ }
1712
+ else {
1713
+ download = media;
1714
+ }
1715
+ const stream = await downloadContentFromMessage(download, mediaType, options);
1716
+ if (type === 'buffer') {
1717
+ const bufferArray = [];
1718
+ for await (const chunk of stream) {
1719
+ bufferArray.push(chunk);
1720
+ }
1721
+ return Buffer.concat(bufferArray);
1722
+ }
1723
+ return stream;
1724
+ }
1725
+ };
1726
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1727
+ export const assertMediaContent = (content) => {
1728
+ content = extractMessageContent(content);
1729
+ const mediaContent = content?.documentMessage ||
1730
+ content?.imageMessage ||
1731
+ content?.videoMessage ||
1732
+ content?.audioMessage ||
1733
+ content?.stickerMessage;
1734
+ if (!mediaContent) {
1735
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1736
+ }
1737
+ return mediaContent;
1738
+ };
1739
+ /**
1740
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
1741
+ * or ANIM/ANMF chunks
1742
+ */
1743
+ const isAnimatedWebP = (buffer) => {
1744
+ // WebP must start with RIFF....WEBP
1745
+ if (buffer.length < 12 ||
1746
+ buffer[0] !== 0x52 ||
1747
+ buffer[1] !== 0x49 ||
1748
+ buffer[2] !== 0x46 ||
1749
+ buffer[3] !== 0x46 ||
1750
+ buffer[8] !== 0x57 ||
1751
+ buffer[9] !== 0x45 ||
1752
+ buffer[10] !== 0x42 ||
1753
+ buffer[11] !== 0x50) {
1754
+ return false;
1755
+ }
1756
+ ;
1757
+ // Parse chunks starting after RIFF header (12 bytes)
1758
+ let offset = 12;
1759
+ while (offset < buffer.length - 8) {
1760
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
1761
+ const chunkSize = buffer.readUInt32LE(offset + 4);
1762
+ if (chunkFourCC === 'VP8X') {
1763
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
1764
+ const flagsOffset = offset + 8;
1765
+ if (flagsOffset < buffer.length) {
1766
+ const flags = buffer[flagsOffset];
1767
+ if (flags & 0x02) {
1768
+ return true;
1769
+ }
1770
+ ;
1771
+ }
1772
+ ;
1773
+ }
1774
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
1775
+ // ANIM or ANMF chunks indicate animation
1776
+ return true;
1777
+ }
1778
+ ;
1779
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
1780
+ offset += 8 + chunkSize + (chunkSize % 2);
1781
+ }
1782
+ ;
1783
+ return false;
1784
+ };
1785
+ /**
1786
+ * Checks if a buffer is a WebP file
1787
+ */
1788
+ const isWebPBuffer = (buffer) => {
1789
+ return (buffer.length >= 12 &&
1790
+ buffer[0] === 0x52 &&
1791
+ buffer[1] === 0x49 &&
1792
+ buffer[2] === 0x46 &&
1793
+ buffer[3] === 0x46 &&
1794
+ buffer[8] === 0x57 &&
1795
+ buffer[9] === 0x45 &&
1796
+ buffer[10] === 0x42 &&
1797
+ buffer[11] === 0x50);
1798
+ };
1799
+ export const shouldIncludeBizBinaryNode = (message) => {
1800
+ const hasValidInteractive = message.interactiveMessage &&
1801
+ !message.interactiveMessage.carouselMessage &&
1802
+ !message.interactiveMessage.collectionMessage &&
1803
+ !message.interactiveMessage.shopStorefrontMessage;
1804
+ return (message.buttonsMessage ||
1805
+ message.interactiveMessage ||
1806
+ message.listMessage ||
1807
+ hasValidInteractive);
1808
+ };
1809
+ //# sourceMappingURL=messages.js.map