@nerxa/socketon 0.0.0-stage → 1.21.0

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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +100 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +37 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,2223 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
4
+ import { promises as fs } from 'fs';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { ButtonHeaderType, ButtonType, CarouselCardType, ListType, WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
+ import { sha256 } from './crypto.js';
10
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
+ import { downloadContentFromMessage, encryptedStream, extractImageThumb, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
12
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
13
+ import { buildMusicMessage, normalizeStickers } from './status-stickers.js';
14
+ import { buildSocialPreview } from './link-preview-metadata.js';
15
+ import { buildPaymentReminder, buildSplitPayment, buildSplitPaymentUpdate } from './payment-messages.js';
16
+ import { NATIVE_FLOW_BUTTON_LIMIT, WEB_SUPPORTED_INTERACTIVE_FLOWS, getNativeFlowNameByButtonName } from './native-flow.js';
17
+
18
+ const trimEmptyValues = (object) => {
19
+ for (const key of Object.keys(object)) {
20
+ if (object[key] === undefined) {
21
+ delete object[key];
22
+ }
23
+ }
24
+ return object;
25
+ };
26
+
27
+ /**
28
+ * externalAdReply wants the artwork inline as jpeg bytes, and a full cover is
29
+ * far past what a thumbnail may weigh, so it is downscaled when an image
30
+ * library is around and passed through untouched when none is.
31
+ */
32
+ const songThumbnail = async (artwork, width, logger) => {
33
+ const source = Buffer.isBuffer(artwork) ? artwork : await toBuffer(await getStream(artwork).then(({ stream }) => stream));
34
+ try {
35
+ const { buffer } = await extractImageThumb(source, width);
36
+ return buffer;
37
+ }
38
+ catch (error) {
39
+ logger?.warn?.({ trace: error?.message }, 'could not downscale the song artwork, sending it whole');
40
+ return source;
41
+ }
42
+ };
43
+ const CONCURRENCY_LIMIT = 15;
44
+ const MIMETYPE_MAP = {
45
+ image: 'image/jpeg',
46
+ video: 'video/mp4',
47
+ document: 'application/pdf',
48
+ audio: 'audio/ogg; codecs=opus',
49
+ sticker: 'image/webp',
50
+ 'product-catalog-image': 'image/jpeg'
51
+ };
52
+ const MessageTypeProto = {
53
+ image: WAProto.Message.ImageMessage,
54
+ video: WAProto.Message.VideoMessage,
55
+ audio: WAProto.Message.AudioMessage,
56
+ sticker: WAProto.Message.StickerMessage,
57
+ document: WAProto.Message.DocumentMessage
58
+ };
59
+
60
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
61
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
62
+ const url = extractUrlFromText(text);
63
+ if (!!getUrlInfo && url) {
64
+ try {
65
+ const urlInfo = await getUrlInfo(url);
66
+ return urlInfo;
67
+ }
68
+ catch (error) {
69
+
70
+ logger?.warn({ trace: error.stack }, 'url generation failed');
71
+ }
72
+ }
73
+ };
74
+ export const prepareLinkThumbnail = async (image, options, { thumbnailWidth = 640, upload = true } = {}) => {
75
+ if (upload && typeof options?.upload !== 'function') {
76
+ throw new Boom('a large link thumbnail has to be uploaded, so this needs an upload function', { statusCode: 400 });
77
+ }
78
+ const source = Buffer.isBuffer(image) ? image : await toBuffer(await getStream(image).then(({ stream }) => stream));
79
+ let full;
80
+ let width;
81
+ let height;
82
+ try {
83
+ const probe = await extractImageThumb(source, thumbnailWidth);
84
+ const original = probe.original;
85
+ width = Math.min(thumbnailWidth, original.width);
86
+ height = Math.round(original.height * width / original.width);
87
+ full = width === thumbnailWidth ? probe.buffer : (await extractImageThumb(source, width)).buffer;
88
+ }
89
+ catch (error) {
90
+ options.logger?.warn?.({ trace: error?.message }, 'no image library could measure the link thumbnail, so the card stays small');
91
+ return { jpegThumbnail: source };
92
+ }
93
+ let jpegThumbnail;
94
+ try {
95
+ jpegThumbnail = (await extractImageThumb(source, Math.min(192, width))).buffer;
96
+ }
97
+ catch {
98
+ jpegThumbnail = full;
99
+ }
100
+ if (!upload) {
101
+ return { jpegThumbnail };
102
+ }
103
+ const blob = await encryptedStream(full, 'thumbnail-link', {
104
+ logger: options.logger,
105
+ opts: options.options
106
+ });
107
+ let result;
108
+ try {
109
+ result = await options.upload(blob.encFilePath, {
110
+ fileEncSha256B64: blob.fileEncSha256.toString('base64'),
111
+ mediaType: 'thumbnail-link',
112
+ timeoutMs: options.mediaUploadTimeoutMs
113
+ });
114
+ }
115
+ finally {
116
+ fs.unlink(blob.encFilePath).catch(() => options.logger?.warn?.('failed to remove tmp file'));
117
+ }
118
+ return {
119
+ jpegThumbnail,
120
+ highQualityThumbnail: {
121
+ directPath: result.directPath,
122
+ mediaKey: blob.mediaKey,
123
+ mediaKeyTimestamp: unixTimestampSeconds(),
124
+ fileSha256: blob.fileSha256,
125
+ fileEncSha256: blob.fileEncSha256,
126
+ width,
127
+ height
128
+ }
129
+ };
130
+ };
131
+ const eventSeconds = (value, name) => {
132
+ if (value instanceof Date) {
133
+ return Math.floor(value.getTime() / 1000);
134
+ }
135
+ const number = Number(value);
136
+ if (!Number.isFinite(number)) {
137
+ throw new Boom(`event ${name} must be a Date or a unix timestamp`, { statusCode: 400 });
138
+ }
139
+ return Math.floor(number > 1e11 ? number / 1000 : number);
140
+ };
141
+ const assertColor = async (color) => {
142
+ if (typeof color === 'number') {
143
+ return color >= 0 ? color : 0xffffffff + color + 1;
144
+ }
145
+ let hex = color.trim().replace('#', '');
146
+ if (hex.length <= 6) {
147
+ hex = 'FF' + hex.padStart(6, '0');
148
+ }
149
+ return parseInt(hex, 16);
150
+ };
151
+ export const getPollOptionHash = (optionName, fileSha256) => {
152
+ const nameHash = createHash('sha256').update(String(optionName), 'utf-8').digest('hex');
153
+ const fileHash = fileSha256 ? Buffer.from(fileSha256).toString('base64') : '';
154
+ return createHash('sha256').update(nameHash + fileHash, 'utf-8').digest('hex');
155
+ };
156
+ export const prepareWAMessageMedia = async (message, options) => {
157
+ const logger = options.logger;
158
+ let mediaType;
159
+ for (const key of MEDIA_KEYS) {
160
+ if (key in message) {
161
+ mediaType = key;
162
+ }
163
+ }
164
+ if (!mediaType) {
165
+ throw new Boom('Invalid media type', { statusCode: 400 });
166
+ }
167
+ const uploadData = {
168
+ ...message,
169
+ media: message[mediaType]
170
+ };
171
+ delete uploadData[mediaType];
172
+
173
+ const annotations = uploadData.statusStickers ?? uploadData.interactiveAnnotations;
174
+ delete uploadData.statusStickers;
175
+ if (annotations) {
176
+ if (mediaType !== 'image' && mediaType !== 'video') {
177
+ throw new Boom('status stickers only ride on an image or a video', { statusCode: 400 });
178
+ }
179
+ uploadData.interactiveAnnotations = normalizeStickers(annotations);
180
+ }
181
+
182
+ const cacheableKey = typeof uploadData.media === 'object' &&
183
+ 'url' in uploadData.media &&
184
+ !!uploadData.media.url &&
185
+ !!options.mediaCache &&
186
+ mediaType + ':' + uploadData.media.url.toString();
187
+ if (mediaType === 'document' && !uploadData.fileName) {
188
+ uploadData.fileName = 'file';
189
+ }
190
+ if (!uploadData.mimetype) {
191
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
192
+ }
193
+ if (cacheableKey) {
194
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
195
+ if (mediaBuff) {
196
+ logger?.debug({ cacheableKey }, 'got media cache hit');
197
+ const obj = proto.Message.decode(mediaBuff);
198
+ const key = `${mediaType}Message`;
199
+ Object.assign(obj[key], { ...uploadData, media: undefined });
200
+ return obj;
201
+ }
202
+ }
203
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
204
+ if (isNewsletter) {
205
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
206
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
207
+ const fileSha256B64 = fileSha256.toString('base64');
208
+ const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
209
+ fileEncSha256B64: fileSha256B64,
210
+ mediaType: mediaType,
211
+ timeoutMs: options.mediaUploadTimeoutMs,
212
+ newsletter: isNewsletter
213
+ });
214
+ await fs.unlink(filePath);
215
+ const obj = WAProto.Message.fromObject({
216
+
217
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
218
+ url: mediaUrl,
219
+ directPath,
220
+ fileSha256,
221
+ fileLength,
222
+ thumbnailDirectPath,
223
+ thumbnailSha256,
224
+ ...uploadData,
225
+ media: undefined
226
+ })
227
+ });
228
+ if (uploadData.ptv) {
229
+ obj.ptvMessage = obj.videoMessage;
230
+ delete obj.videoMessage;
231
+ }
232
+ if (obj.stickerMessage) {
233
+ obj.stickerMessage.stickerSentTs = Date.now();
234
+ }
235
+ if (cacheableKey) {
236
+ logger?.debug({ cacheableKey }, 'set cache');
237
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
238
+ }
239
+ return obj;
240
+ }
241
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
242
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
243
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
244
+ const requiresAudioBackground = options.backgroundColor != null && mediaType === 'audio' && uploadData.ptt === true;
245
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
246
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
247
+ logger,
248
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
249
+ opts: options.options
250
+ });
251
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
252
+ const [{ mediaUrl, directPath }] = await Promise.all([
253
+ (async () => {
254
+ const result = await options.upload(encFilePath, {
255
+ fileEncSha256B64,
256
+ mediaType,
257
+ timeoutMs: options.mediaUploadTimeoutMs
258
+ });
259
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
260
+ return result;
261
+ })(),
262
+ (async () => {
263
+ if (requiresAudioBackground) {
264
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
265
+ logger?.debug('computed backgroundColor audio status');
266
+ }
267
+ try {
268
+ if (requiresThumbnailComputation) {
269
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
270
+ uploadData.jpegThumbnail = thumbnail;
271
+ if (!uploadData.width && originalImageDimensions) {
272
+ uploadData.width = originalImageDimensions.width;
273
+ uploadData.height = originalImageDimensions.height;
274
+ logger?.debug('set dimensions');
275
+ }
276
+ logger?.debug('generated thumbnail');
277
+ }
278
+ if (requiresDurationComputation) {
279
+ uploadData.seconds = await getAudioDuration(originalFilePath);
280
+ logger?.debug('computed audio duration');
281
+ }
282
+ if (requiresWaveformProcessing) {
283
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
284
+ logger?.debug('processed waveform');
285
+ }
286
+ }
287
+ catch (error) {
288
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
289
+ }
290
+ })()
291
+ ]).finally(async () => {
292
+ try {
293
+ await fs.unlink(encFilePath);
294
+ if (originalFilePath) {
295
+ await fs.unlink(originalFilePath);
296
+ }
297
+ logger?.debug('removed tmp files');
298
+ }
299
+ catch (error) {
300
+ logger?.warn('failed to remove tmp file');
301
+ }
302
+ });
303
+ const obj = WAProto.Message.fromObject({
304
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
305
+ url: mediaUrl,
306
+ directPath,
307
+ mediaKey,
308
+ fileEncSha256,
309
+ fileSha256,
310
+ fileLength,
311
+ mediaKeyTimestamp: unixTimestampSeconds(),
312
+ ...uploadData,
313
+ media: undefined
314
+ })
315
+ });
316
+ if (uploadData.ptv) {
317
+ obj.ptvMessage = obj.videoMessage;
318
+ delete obj.videoMessage;
319
+ }
320
+ if (cacheableKey) {
321
+ logger?.debug({ cacheableKey }, 'set cache');
322
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
323
+ }
324
+ return obj;
325
+ };
326
+
327
+ const prepareProductMessage = async (message, options) => {
328
+ if (!message.businessOwnerJid) {
329
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
330
+ }
331
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
332
+
333
+ const { image, ...content } = message;
334
+ content.product = {
335
+ currencyCode: 'IDR',
336
+ priceAmount1000: 1000,
337
+ title: LIBRARY_NAME,
338
+ ...message.product,
339
+ productImage: imageMessage
340
+ };
341
+ return content;
342
+ };
343
+
344
+ const prepareStickerPackMessage = async (message, options) => {
345
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: rexxhayanasi', description = '🏷️ rexxhayanasi/elaina' } = message;
346
+ if (stickers.length > 60) {
347
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
348
+ }
349
+ if (stickers.length === 0) {
350
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
351
+ }
352
+ if (!cover) {
353
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
354
+ }
355
+ const logger = options.logger;
356
+
357
+ let cacheableKey = false;
358
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
359
+ const urls = [];
360
+ for (let i = 0; i < stickers.length; i++) {
361
+ const data = stickers[i].data;
362
+ if (typeof data === 'object' && data?.url) {
363
+ urls.push(data.url);
364
+ }
365
+ }
366
+ if (urls.length > 0) {
367
+ cacheableKey = 'sticker:' + urls.join('@');
368
+ }
369
+ }
370
+ if (cacheableKey) {
371
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
372
+ if (mediaBuff) {
373
+ logger?.debug({ cacheableKey }, 'got media cache hit');
374
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
375
+ }
376
+ }
377
+ const lib = await getImageProcessingLibrary();
378
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
379
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
380
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
381
+ if (!hasSharp && !hasImage) {
382
+ throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
383
+ }
384
+ const stickerPackIdValue = generateMessageIDV2();
385
+ const stickerData = {};
386
+ const stickerMetadata = new Array(stickers.length);
387
+ for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
388
+ const promises = [];
389
+ const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length);
390
+ for (let j = i; j < chunkEnd; j++) {
391
+ promises.push((async (index) => {
392
+ const sticker = stickers[index];
393
+ const { stream } = await getStream(sticker.data);
394
+ const buffer = await toBuffer(stream);
395
+ let webpBuffer;
396
+ let isAnimated = false;
397
+ if (isWebPBuffer(buffer)) {
398
+ webpBuffer = buffer;
399
+ isAnimated = isAnimatedWebP(buffer);
400
+ }
401
+ else if (hasSharp) {
402
+ webpBuffer = await lib.sharp.default(buffer)
403
+ .resize(512, 512, { fit: 'inside' })
404
+ .webp({ quality: 80 })
405
+ .toBuffer();
406
+ }
407
+ else {
408
+ webpBuffer = await new lib.image.Transformer(buffer)
409
+ .resize(512, 512)
410
+ .webp(80);
411
+ }
412
+ if (webpBuffer.length > 1024 * 1024) {
413
+ throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
414
+ }
415
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
416
+ const fileName = `${hash}.webp`;
417
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
418
+ stickerMetadata[index] = {
419
+ fileName,
420
+ mimetype: 'image/webp',
421
+ isAnimated,
422
+ emojis: sticker.emojis || ['✨'],
423
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
424
+ };
425
+ })(j));
426
+ }
427
+ await Promise.all(promises);
428
+ }
429
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
430
+ const { stream: coverStream } = await getStream(cover);
431
+ const coverBuffer = await toBuffer(coverStream);
432
+ let coverWebpBuffer;
433
+ if (isWebPBuffer(coverBuffer)) {
434
+ coverWebpBuffer = coverBuffer;
435
+ }
436
+ else if (hasSharp) {
437
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
438
+ .resize(512, 512, { fit: 'inside' })
439
+ .webp({ quality: 80 })
440
+ .toBuffer();
441
+ }
442
+ else {
443
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
444
+ .resize(512, 512)
445
+ .webp(80);
446
+ }
447
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
448
+ const zipBuffer = await new Promise((resolve, reject) => {
449
+ zip(stickerData, (error, data) => error ? reject(error) : resolve(Buffer.from(data)));
450
+ });
451
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
452
+ logger,
453
+ opts: options.options
454
+ });
455
+ let stickerPackUploadResult;
456
+ try {
457
+ stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
458
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
459
+ mediaType: 'sticker-pack',
460
+ timeoutMs: options.mediaUploadTimeoutMs
461
+ });
462
+ }
463
+ finally {
464
+ fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
465
+ }
466
+ const obj = {
467
+ name,
468
+ publisher,
469
+ stickerPackId: stickerPackIdValue,
470
+ packDescription: description,
471
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
472
+ stickerPackSize: zipBuffer.length,
473
+ stickers: stickerMetadata,
474
+ fileSha256: stickerPackUpload.fileSha256,
475
+ fileEncSha256: stickerPackUpload.fileEncSha256,
476
+ mediaKey: stickerPackUpload.mediaKey,
477
+ directPath: stickerPackUploadResult.directPath,
478
+ fileLength: stickerPackUpload.fileLength,
479
+ mediaKeyTimestamp: unixTimestampSeconds(),
480
+ trayIconFileName
481
+ };
482
+ try {
483
+ let thumbnailBuffer;
484
+ if (hasSharp) {
485
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
486
+ }
487
+ else if (hasImage) {
488
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
489
+ }
490
+ else if (hasJimp) {
491
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
492
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
493
+ }
494
+ else {
495
+ throw new Error('No image processing library available for thumbnail generation');
496
+ }
497
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
498
+ throw new Error('Failed to generate thumbnail buffer');
499
+ }
500
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
501
+ logger,
502
+ opts: options.options,
503
+ mediaKey: stickerPackUpload.mediaKey
504
+ });
505
+ let thumbUploadResult;
506
+ try {
507
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
508
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
509
+ mediaType: 'thumbnail-sticker-pack',
510
+ timeoutMs: options.mediaUploadTimeoutMs
511
+ });
512
+ }
513
+ finally {
514
+ fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
515
+ }
516
+ Object.assign(obj, {
517
+ thumbnailDirectPath: thumbUploadResult.directPath,
518
+ thumbnailSha256: thumbUpload.fileSha256,
519
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
520
+ thumbnailHeight: 252,
521
+ thumbnailWidth: 252,
522
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
523
+ });
524
+ }
525
+ catch (error) {
526
+ logger?.warn(`Thumbnail generation failed: ${error}`);
527
+ }
528
+ if (cacheableKey) {
529
+ logger?.debug({ cacheableKey }, 'set cache (background)');
530
+ options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish());
531
+ }
532
+ return WAProto.Message.StickerPackMessage.fromObject(obj);
533
+ };
534
+
535
+ const buttonLimitFor = buttons => buttons[0]?.name === 'quick_reply'
536
+ ? NATIVE_FLOW_BUTTON_LIMIT.quickReply
537
+ : NATIVE_FLOW_BUTTON_LIMIT.other;
538
+
539
+ export const nativeFlowButtonsViolateConstraints = (buttons = []) => {
540
+ if (!buttons.length) {
541
+ return false;
542
+ }
543
+ const isQuickReply = button => button?.name === 'quick_reply';
544
+ const firstIsQuickReply = isQuickReply(buttons[0]);
545
+ if (buttons.length > buttonLimitFor(buttons)) {
546
+ return true;
547
+ }
548
+ return !buttons.slice(1).every(button => {
549
+ const mapped = getNativeFlowNameByButtonName(button?.name);
550
+ const nameAllowed = mapped == null || WEB_SUPPORTED_INTERACTIVE_FLOWS.includes(mapped);
551
+ return nameAllowed && firstIsQuickReply === isQuickReply(button);
552
+ });
553
+ };
554
+
555
+ const warnOnNativeFlowConstraints = (buttons, logger) => {
556
+ if (!logger?.warn || !nativeFlowButtonsViolateConstraints(buttons)) {
557
+ return;
558
+ }
559
+ const limit = buttonLimitFor(buttons);
560
+ const kinds = [...new Set(buttons.map(button => button?.name))];
561
+ logger.warn({ buttons: buttons.length, limit, kinds }, 'these native flow buttons break the client\'s button constraints, '
562
+ + 'so it cannot work out a flow name and draws the whole message as unsupported: keep every button the same kind as the first '
563
+ + `and at most ${limit} of them`);
564
+ };
565
+
566
+ const prepareNativeFlowButtons = (message, options) => {
567
+ const buttons = message.nativeFlow;
568
+ const isButtonsFieldArray = Array.isArray(buttons);
569
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
570
+ const messageParamsJson = {};
571
+
572
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
573
+ Object.assign(messageParamsJson, {
574
+ limited_time_offer: {
575
+ text: message.offerText || LIBRARY_NAME,
576
+ url: message.offerUrl || DONATE_URL,
577
+ copy_code: message.offerCode,
578
+ expiration_time: message.offerExpiration
579
+ }
580
+ });
581
+ }
582
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
583
+ Object.assign(messageParamsJson, {
584
+ bottom_sheet: {
585
+ in_thread_buttons_limit: 1,
586
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
587
+ list_title: message.optionTitle || '📄 Select Options',
588
+ button_title: message.optionText
589
+ }
590
+ });
591
+ }
592
+ const prepared = correctedField.map(button => {
593
+ const buttonText = button.text || button.buttonText;
594
+ const buttonIcon = button.icon?.toUpperCase();
595
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
596
+ return {
597
+ name: 'quick_reply',
598
+ buttonParamsJson: JSON.stringify({
599
+ display_text: buttonText || '👉🏻 Click',
600
+ id: button.id,
601
+ icon: buttonIcon
602
+ })
603
+ };
604
+ }
605
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
606
+ return {
607
+ name: 'cta_copy',
608
+ buttonParamsJson: JSON.stringify({
609
+ display_text: buttonText || '📋 Copy',
610
+ copy_code: button.copy,
611
+ icon: buttonIcon
612
+ })
613
+ };
614
+ }
615
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
616
+ return {
617
+ name: 'cta_url',
618
+ buttonParamsJson: JSON.stringify({
619
+ display_text: buttonText || '🌐 Visit',
620
+ url: button.url,
621
+ merchant_url: button.url,
622
+ webview_interaction: button.useWebview,
623
+ icon: buttonIcon
624
+ })
625
+ };
626
+ }
627
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
628
+ return {
629
+ name: 'cta_call',
630
+ buttonParamsJson: JSON.stringify({
631
+ display_text: buttonText || '📞 Call',
632
+ phone_number: button.call,
633
+ icon: buttonIcon
634
+ })
635
+ };
636
+ }
637
+
638
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
639
+ return {
640
+ name: 'single_select',
641
+ buttonParamsJson: JSON.stringify({
642
+ title: buttonText || '📋 Select',
643
+ sections: button.sections,
644
+ icon: buttonIcon
645
+ })
646
+ };
647
+ }
648
+ return button;
649
+ });
650
+ warnOnNativeFlowConstraints(prepared, options?.logger);
651
+ return {
652
+ buttons: prepared,
653
+ messageParamsJson: JSON.stringify(messageParamsJson),
654
+ name: message.flowName || 'mixed',
655
+ messageVersion: 1
656
+ };
657
+ };
658
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
659
+ ephemeralExpiration = ephemeralExpiration || 0;
660
+ const content = {
661
+ ephemeralMessage: {
662
+ message: {
663
+ protocolMessage: {
664
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
665
+ ephemeralExpiration
666
+ }
667
+ }
668
+ }
669
+ };
670
+ return WAProto.Message.fromObject(content);
671
+ };
672
+
673
+ export const generateForwardMessageContent = (message, forceForward) => {
674
+ let content = message.message;
675
+ if (!content) {
676
+ throw new Boom('no content in message', { statusCode: 400 });
677
+ }
678
+
679
+ content = normalizeMessageContent(content);
680
+ content = proto.Message.decode(proto.Message.encode(content).finish());
681
+ let key = Object.keys(content)[0];
682
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
683
+ score += message.key.fromMe && !forceForward ? 0 : 1;
684
+ if (key === 'conversation') {
685
+ content.extendedTextMessage = { text: content[key] };
686
+ delete content.conversation;
687
+ key = 'extendedTextMessage';
688
+ }
689
+ const key_ = content?.[key];
690
+ if (score > 0) {
691
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
692
+ }
693
+ else {
694
+ key_.contextInfo = {};
695
+ }
696
+ return content;
697
+ };
698
+ export const hasNonNullishProperty = (message, key) => {
699
+ return message != null &&
700
+ typeof message === 'object' &&
701
+ key in message &&
702
+ message[key] != null;
703
+ };
704
+ export const hasOptionalProperty = (obj, key) => {
705
+ return obj != null &&
706
+ typeof obj === 'object' &&
707
+ key in obj &&
708
+ obj[key] != null;
709
+ };
710
+
711
+ export const hasValidAlbumMedia = (message) => {
712
+ return !!(message.imageMessage ||
713
+ message.videoMessage);
714
+ };
715
+ export const hasValidInteractiveHeader = (message) => {
716
+ return !!(message.imageMessage ||
717
+ message.videoMessage ||
718
+ message.documentMessage ||
719
+ message.productMessage ||
720
+ message.locationMessage);
721
+ };
722
+
723
+ const headerText = ({ title, subtitle }) => ({
724
+ ...(title ? { title } : {}),
725
+ ...(subtitle ? { subtitle } : {})
726
+ });
727
+
728
+ export const hasValidCarouselHeader = (message) => {
729
+ return !!(message.imageMessage ||
730
+ message.videoMessage ||
731
+ message.productMessage);
732
+ };
733
+
734
+ // Accept the same raw buttonsMessage payload used by Noxleyss. Location
735
+ // thumbnails are normalized to JPEG before being placed in the protobuf.
736
+ const processLocationThumbnail = async (input, options = {}) => {
737
+ let buffer;
738
+ if (Buffer.isBuffer(input)) {
739
+ buffer = input;
740
+ }
741
+ else if (typeof input === 'string' && /^https?:\/\//i.test(input)) {
742
+ const response = await fetch(input, { dispatcher: options?.dispatcher });
743
+ if (!response.ok) {
744
+ throw new Boom(`could not fetch location thumbnail: ${response.status}`, { statusCode: 400 });
745
+ }
746
+ buffer = Buffer.from(await response.arrayBuffer());
747
+ }
748
+ else if (typeof input === 'string') {
749
+ buffer = await fs.readFile(input);
750
+ }
751
+ else {
752
+ throw new Boom('location thumbnail must be a URL, file path, or Buffer', { statusCode: 400 });
753
+ }
754
+ const { buffer: jpeg } = await extractImageThumb(buffer, 300);
755
+ return jpeg;
756
+ };
757
+
758
+ export const generateWAMessageContent = async (message, options) => {
759
+ var _a, _b;
760
+ let m = {};
761
+
762
+ if (hasNonNullishProperty(message, 'raw')) {
763
+ delete message.raw;
764
+ return message;
765
+ }
766
+ else if (hasNonNullishProperty(message, 'richLink')) {
767
+ const { text, url, title, description, image, large = true, previewType, thumbnailWidth, ...rest } = message.richLink;
768
+ if (!url || typeof url !== 'string') {
769
+ throw new Boom('richLink needs a url', { statusCode: 400 });
770
+ }
771
+ let body = text ?? url;
772
+ if (!body.includes(url)) {
773
+ body = `${body}\n\n${url}`;
774
+ }
775
+ const extContent = {
776
+ ...rest,
777
+ text: body,
778
+ matchedText: url,
779
+ title,
780
+ description,
781
+ previewType: previewType ?? 0
782
+ };
783
+ if (image) {
784
+ const thumbnails = await prepareLinkThumbnail(image, options, { thumbnailWidth, upload: large });
785
+ extContent.jpegThumbnail = thumbnails.jpegThumbnail;
786
+ const hq = thumbnails.highQualityThumbnail;
787
+ if (hq) {
788
+ extContent.thumbnailDirectPath = hq.directPath;
789
+ extContent.mediaKey = hq.mediaKey;
790
+ extContent.mediaKeyTimestamp = hq.mediaKeyTimestamp;
791
+ extContent.thumbnailSha256 = hq.fileSha256;
792
+ extContent.thumbnailEncSha256 = hq.fileEncSha256;
793
+ extContent.thumbnailWidth = hq.width;
794
+ extContent.thumbnailHeight = hq.height;
795
+ }
796
+ }
797
+ m.extendedTextMessage = trimEmptyValues(extContent);
798
+ }
799
+ else if (hasNonNullishProperty(message, 'text')) {
800
+ const extContent = { text: message.text };
801
+ let urlInfo = message.linkPreview;
802
+ if (typeof urlInfo === 'undefined') {
803
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
804
+ }
805
+ if (urlInfo?.image && !urlInfo.highQualityThumbnail) {
806
+ urlInfo = {
807
+ ...urlInfo,
808
+ ...(await prepareLinkThumbnail(urlInfo.image, options, {
809
+ thumbnailWidth: urlInfo.thumbnailWidth,
810
+ upload: urlInfo.large !== false
811
+ }))
812
+ };
813
+ }
814
+ if (urlInfo) {
815
+ extContent.matchedText = urlInfo['matched-text'];
816
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
817
+ extContent.description = urlInfo.description;
818
+ extContent.title = urlInfo.title;
819
+ extContent.previewType = urlInfo.previewType ?? 0;
820
+ extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
821
+ const img = urlInfo.highQualityThumbnail;
822
+ if (img) {
823
+ extContent.thumbnailDirectPath = img.directPath;
824
+ extContent.mediaKey = img.mediaKey;
825
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
826
+ extContent.thumbnailWidth = img.width;
827
+ extContent.thumbnailHeight = img.height;
828
+ extContent.thumbnailSha256 = img.fileSha256;
829
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
830
+ }
831
+ }
832
+ const faviconData = message.favicon;
833
+ if (faviconData && typeof options.upload === 'function') {
834
+ const { imageMessage } = await prepareWAMessageMedia({
835
+ image: faviconData
836
+ }, options);
837
+ extContent.faviconMMSMetadata = {
838
+ thumbnailDirectPath: imageMessage.directPath,
839
+ mediaKey: imageMessage.mediaKey,
840
+ mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
841
+ thumbnailWidth: 32,
842
+ thumbnailHeight: 32,
843
+ thumbnailSha256: imageMessage.fileSha256,
844
+ thumbnailEncSha256: imageMessage.fileEncSha256
845
+ };
846
+ }
847
+ if (options.backgroundColor != null) {
848
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
849
+ }
850
+ if (options.textColor != null) {
851
+ extContent.textArgb = await assertColor(options.textColor);
852
+ }
853
+ if (options.font != null) {
854
+ extContent.font = options.font;
855
+ }
856
+ if (hasNonNullishProperty(message, 'socialPreview')) {
857
+ if (!extContent.matchedText) {
858
+ options.logger?.warn?.('socialPreview rides on a link preview and this message has no matched link, '
859
+ + 'so nothing is attached to anything. Adding the link fixes this warning but not the rendering: '
860
+ + 'no client reads these fields back out of a message you send, so socialPreview is for decoding '
861
+ + 'what Meta sends, not for drawing your own card');
862
+ }
863
+ Object.assign(extContent, buildSocialPreview(message.socialPreview));
864
+ }
865
+ m.extendedTextMessage = extContent;
866
+ }
867
+ else if (hasNonNullishProperty(message, 'contacts')) {
868
+ const contactLen = message.contacts.contacts.length;
869
+ if (!contactLen) {
870
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
871
+ }
872
+ if (contactLen === 1) {
873
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
874
+ }
875
+ else {
876
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
877
+ }
878
+ }
879
+ else if (hasNonNullishProperty(message, 'location')) {
880
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
881
+ }
882
+ else if (hasNonNullishProperty(message, 'react')) {
883
+ if (!message.react.senderTimestampMs) {
884
+ message.react.senderTimestampMs = Date.now();
885
+ }
886
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
887
+ }
888
+ else if (hasNonNullishProperty(message, 'delete')) {
889
+ m.protocolMessage = {
890
+ key: message.delete,
891
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
892
+ };
893
+ }
894
+ else if (hasNonNullishProperty(message, 'forward')) {
895
+ m = generateForwardMessageContent(message.forward, message.force);
896
+ }
897
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
898
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
899
+ ? message.disappearingMessagesInChat
900
+ ? WA_DEFAULT_EPHEMERAL
901
+ : 0
902
+ : message.disappearingMessagesInChat;
903
+ m = prepareDisappearingMessageSettingContent(exp);
904
+ }
905
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
906
+ m.groupInviteMessage = {};
907
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
908
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
909
+ m.groupInviteMessage.caption = message.groupInvite.text;
910
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
911
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
912
+
913
+ if (options.getProfilePicUrl) {
914
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
915
+ if (pfpUrl) {
916
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
917
+ if (resp.ok) {
918
+ const buf = Buffer.from(await resp.arrayBuffer());
919
+ m.groupInviteMessage.jpegThumbnail = buf;
920
+ }
921
+ }
922
+ }
923
+ }
924
+ else if (hasNonNullishProperty(message, 'stickers')) {
925
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
926
+ }
927
+ else if (hasNonNullishProperty(message, 'pin')) {
928
+ m.pinInChatMessage = {};
929
+ m.messageContextInfo = {};
930
+ m.pinInChatMessage.key = message.pin;
931
+ m.pinInChatMessage.type = message.type;
932
+ m.pinInChatMessage.senderTimestampMs = Date.now();
933
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
934
+ }
935
+ else if (hasNonNullishProperty(message, 'keep')) {
936
+ m.keepInChatMessage = {};
937
+ m.keepInChatMessage.key = message.keep;
938
+ m.keepInChatMessage.keepType = message.type;
939
+ m.keepInChatMessage.timestampMs = Date.now();
940
+ }
941
+ else if (hasNonNullishProperty(message, 'flowReply')) {
942
+ m.interactiveResponseMessage = {
943
+ body: {
944
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
945
+ text: message.flowReply.text
946
+ },
947
+ nativeFlowResponseMessage: {
948
+ name: message.flowReply.name,
949
+ paramsJson: message.flowReply.paramsJson || '{}',
950
+ version: message.flowReply.version || 1
951
+ }
952
+ };
953
+ }
954
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
955
+ switch (message.type) {
956
+ case 'template':
957
+ m.templateButtonReplyMessage = {
958
+ selectedDisplayText: message.buttonReply.displayText,
959
+ selectedId: message.buttonReply.id,
960
+ selectedIndex: message.buttonReply.index
961
+ };
962
+ break;
963
+ case 'plain':
964
+ m.buttonsResponseMessage = {
965
+ selectedButtonId: message.buttonReply.id,
966
+ selectedDisplayText: message.buttonReply.displayText,
967
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
968
+ };
969
+ break;
970
+ }
971
+ }
972
+ else if (hasNonNullishProperty(message, 'listReply')) {
973
+ m.listResponseMessage = {
974
+ description: message.listReply.description,
975
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
976
+ singleSelectReply: {
977
+ selectedRowId: message.listReply.id
978
+ },
979
+ title: message.listReply.title
980
+ };
981
+ }
982
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
983
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
984
+ m.ptvMessage = videoMessage;
985
+ }
986
+ else if (hasNonNullishProperty(message, 'product')) {
987
+ m.productMessage = await prepareProductMessage(message, options);
988
+ }
989
+ else if (hasNonNullishProperty(message, 'event')) {
990
+ m.eventMessage = {};
991
+ const startTime = eventSeconds(message.event.startDate, 'startDate');
992
+ if (message.event.call && options.getCallLink) {
993
+ const token = await options.getCallLink(message.event.call, { startTime });
994
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
995
+ }
996
+ m.messageContextInfo = {
997
+
998
+ messageSecret: message.event.messageSecret || randomBytes(32)
999
+ };
1000
+ m.eventMessage.name = message.event.name;
1001
+ m.eventMessage.description = message.event.description;
1002
+ m.eventMessage.startTime = startTime;
1003
+ m.eventMessage.endTime = message.event.endDate ? eventSeconds(message.event.endDate, 'endDate') : undefined;
1004
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
1005
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
1006
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
1007
+ m.eventMessage.location = message.event.location;
1008
+ }
1009
+ else if (hasNonNullishProperty(message, 'poll')) {
1010
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
1011
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
1012
+ if (!Array.isArray(message.poll.values)) {
1013
+ throw new Boom('Invalid poll values', { statusCode: 400 });
1014
+ }
1015
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
1016
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
1017
+ statusCode: 400
1018
+ });
1019
+ }
1020
+ let hasPollOptionImage = false;
1021
+ const pollOptions = [];
1022
+ for (const value of message.poll.values) {
1023
+ if (typeof value === 'string') {
1024
+ pollOptions.push({ optionName: value });
1025
+ continue;
1026
+ }
1027
+ if (!value?.name) {
1028
+ throw new Boom('Each photo poll option needs a name', { statusCode: 400 });
1029
+ }
1030
+ if (value.optionHash) {
1031
+ hasPollOptionImage = true;
1032
+ pollOptions.push({ optionName: value.name, optionHash: value.optionHash });
1033
+ continue;
1034
+ }
1035
+ if (!value.image) {
1036
+ pollOptions.push({ optionName: value.name });
1037
+ continue;
1038
+ }
1039
+ const prepared = await prepareWAMessageMedia({ image: value.image }, options);
1040
+ hasPollOptionImage = true;
1041
+ pollOptions.push({
1042
+ optionName: value.name,
1043
+ optionHash: getPollOptionHash(value.name, prepared.imageMessage?.fileSha256)
1044
+ });
1045
+ }
1046
+ const usesExtendedPollSettings = Boolean(message.poll.endDate) ||
1047
+ message.poll.hideVoter === true ||
1048
+ message.poll.canAddOption === true;
1049
+ const pollCreationMessage = {
1050
+ name: message.poll.name,
1051
+ selectableOptionsCount: message.poll.selectableCount,
1052
+ options: pollOptions,
1053
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
1054
+
1055
+ hideParticipantName: message.poll.hideVoter || undefined,
1056
+ allowAddOption: message.poll.canAddOption || undefined
1057
+ };
1058
+ if (hasPollOptionImage) {
1059
+ pollCreationMessage.pollContentType = proto.Message.PollContentType.IMAGE;
1060
+ }
1061
+ if (message.poll.toAnnouncementGroup) {
1062
+
1063
+ m.pollCreationMessageV2 = pollCreationMessage;
1064
+ }
1065
+ else {
1066
+
1067
+ if (message.poll.pollType === 1) {
1068
+ if (!message.poll.correctAnswer) {
1069
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
1070
+ }
1071
+ m.pollCreationMessageV5 = {
1072
+
1073
+ ...pollCreationMessage,
1074
+ correctAnswer: {
1075
+ optionName: message.poll.correctAnswer.toString()
1076
+ },
1077
+ pollType: 1,
1078
+ selectableOptionsCount: 1
1079
+ };
1080
+ }
1081
+ else if (hasPollOptionImage) {
1082
+
1083
+ m.pollCreationMessageV3 = pollCreationMessage;
1084
+ }
1085
+ else if (usesExtendedPollSettings) {
1086
+
1087
+ m.pollCreationMessageV6 = pollCreationMessage;
1088
+ }
1089
+ else if (message.poll.selectableCount === 1) {
1090
+
1091
+ m.pollCreationMessageV3 = pollCreationMessage;
1092
+ }
1093
+ else {
1094
+
1095
+ m.pollCreationMessage = pollCreationMessage;
1096
+ }
1097
+ }
1098
+ m.messageContextInfo = {
1099
+
1100
+ messageSecret: message.poll.messageSecret || randomBytes(32)
1101
+ };
1102
+ }
1103
+
1104
+ else if (hasNonNullishProperty(message, 'pollResult')) {
1105
+ const pollResultSnapshotMessage = {
1106
+ name: message.pollResult.name,
1107
+ pollVotes: message.pollResult.votes.map(vote => ({
1108
+ optionName: vote.name,
1109
+ optionVoteCount: parseInt(vote.voteCount)
1110
+ }))
1111
+ };
1112
+ if (message.pollResult.pollType === 1) {
1113
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
1114
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
1115
+ }
1116
+ else {
1117
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
1118
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
1119
+ }
1120
+ }
1121
+
1122
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
1123
+ if (!message.pollUpdate.key) {
1124
+ throw new Boom('Message key is required', { statusCode: 400 });
1125
+ }
1126
+ if (!message.pollUpdate.vote) {
1127
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
1128
+ }
1129
+ m.pollUpdateMessage = {
1130
+ metadata: message.pollUpdate.metadata,
1131
+ pollCreationMessageKey: message.pollUpdate.key,
1132
+ senderTimestampMs: Date.now(),
1133
+ vote: message.pollUpdate.vote
1134
+ };
1135
+ }
1136
+
1137
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
1138
+ m.paymentInviteMessage = {
1139
+ expiryTimestamp: Date.now(),
1140
+ serviceType: message.paymentInviteServiceType
1141
+ };
1142
+ }
1143
+
1144
+ else if (hasNonNullishProperty(message, 'orderText')) {
1145
+ if (!Buffer.isBuffer(message.thumbnail)) {
1146
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
1147
+ }
1148
+ m.orderMessage = {
1149
+ itemCount: 1,
1150
+ messageVersion: 1,
1151
+ orderTitle: LIBRARY_NAME,
1152
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
1153
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
1154
+ token: generateMessageIDV2(),
1155
+ totalAmount1000: 1000,
1156
+ totalCurrencyCode: 'IDR',
1157
+ ...message,
1158
+ message: message.orderText
1159
+ };
1160
+ delete m.orderMessage.orderText;
1161
+ }
1162
+
1163
+ else if (hasNonNullishProperty(message, 'album')) {
1164
+ if (!Array.isArray(message.album)) {
1165
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
1166
+ }
1167
+ let videoCount = 0;
1168
+ for (let i = 0; i < message.album.length; i++) {
1169
+ if (message.album[i].video)
1170
+ videoCount++;
1171
+ }
1172
+ ;
1173
+ let imageCount = 0;
1174
+ for (let i = 0; i < message.album.length; i++) {
1175
+ if (message.album[i].image)
1176
+ imageCount++;
1177
+ }
1178
+ ;
1179
+ if ((videoCount + imageCount) < 2) {
1180
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
1181
+ }
1182
+ m.albumMessage = {
1183
+ expectedImageCount: imageCount,
1184
+ expectedVideoCount: videoCount,
1185
+ ...(message.caption ? { caption: String(message.caption) } : {})
1186
+ };
1187
+ }
1188
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
1189
+ m.protocolMessage = {
1190
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
1191
+ };
1192
+ }
1193
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
1194
+ m.requestPhoneNumberMessage = {};
1195
+ }
1196
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
1197
+ m.protocolMessage = {
1198
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
1199
+ limitSharing: {
1200
+ sharingLimited: message.limitSharing === true,
1201
+ trigger: 1,
1202
+ limitSharingSettingTimestamp: Date.now(),
1203
+ initiatedByMe: true
1204
+ }
1205
+ };
1206
+ }
1207
+ else if (hasNonNullishProperty(message, 'music')) {
1208
+ m.musicMessage = buildMusicMessage(message.music);
1209
+ }
1210
+ else if (hasNonNullishProperty(message, 'splitPayment')) {
1211
+ m.splitPaymentMessage = buildSplitPayment(message.splitPayment);
1212
+ }
1213
+ else if (hasNonNullishProperty(message, 'splitPaymentUpdate')) {
1214
+ m.splitPaymentUpdateMessage = buildSplitPaymentUpdate(message.splitPaymentUpdate);
1215
+ }
1216
+ else if (hasNonNullishProperty(message, 'paymentReminder')) {
1217
+ m.paymentReminderMessage = buildPaymentReminder(message.paymentReminder);
1218
+ }
1219
+ else if (hasNonNullishProperty(message, 'song')) {
1220
+ const { audio, artwork, title, author, url, largeThumbnail = true, thumbnailWidth = 640, mediaType = 1, ...rest } = message.song;
1221
+ if (!audio) {
1222
+ throw new Boom('song needs audio', { statusCode: 400 });
1223
+ }
1224
+ const mimetype = rest.mimetype ?? 'audio/mpeg';
1225
+ if (rest.ptt === true && !/opus/i.test(mimetype)) {
1226
+ options.logger?.warn?.({ mimetype }, 'ptt asks for a voice note but this is not opus, and nothing here transcodes it');
1227
+ }
1228
+ m = await prepareWAMessageMedia({ audio, ...rest, mimetype }, options);
1229
+ const thumbnail = artwork ? await songThumbnail(artwork, thumbnailWidth, options.logger) : undefined;
1230
+ m.audioMessage.contextInfo = {
1231
+ ...m.audioMessage.contextInfo,
1232
+ externalAdReply: trimEmptyValues({
1233
+ title: title || LIBRARY_NAME,
1234
+ body: author,
1235
+ thumbnail,
1236
+ mediaType,
1237
+ renderLargerThumbnail: !!largeThumbnail,
1238
+ showAdAttribution: false,
1239
+ sourceUrl: url,
1240
+ mediaUrl: url
1241
+ })
1242
+ };
1243
+ }
1244
+ else if (hasNonNullishProperty(message, 'buttonsMessage')) {
1245
+ const bm = message.buttonsMessage;
1246
+ let locationMessage;
1247
+
1248
+ if (bm.locationMessage) {
1249
+ const loc = bm.locationMessage;
1250
+ const thumbnailInput = loc.jpegThumbnail || loc.thumbnail;
1251
+ const jpegThumbnail = thumbnailInput
1252
+ ? await processLocationThumbnail(thumbnailInput, options?.options)
1253
+ : undefined;
1254
+
1255
+ locationMessage = proto.Message.LocationMessage.create({
1256
+ degreesLatitude: loc.degreesLatitude ?? 0,
1257
+ degreesLongitude: loc.degreesLongitude ?? 0,
1258
+ name: loc.name || '',
1259
+ address: loc.address || '',
1260
+ jpegThumbnail
1261
+ });
1262
+ }
1263
+
1264
+ const buttons = (bm.buttons || []).map(button => proto.Message.ButtonsMessage.Button.create({
1265
+ buttonId: button.buttonId || '',
1266
+ buttonText: proto.Message.ButtonsMessage.Button.ButtonText.create({
1267
+ displayText: button.buttonText?.displayText || ''
1268
+ }),
1269
+ type: button.type ?? 1,
1270
+ nativeFlowInfo: button.nativeFlowInfo
1271
+ ? proto.Message.ButtonsMessage.Button.NativeFlowInfo.create({
1272
+ name: button.nativeFlowInfo.name || '',
1273
+ paramsJson: button.nativeFlowInfo.paramsJson || '',
1274
+ buttonParamsJson: button.nativeFlowInfo.buttonParamsJson || button.nativeFlowInfo.paramsJson || ''
1275
+ })
1276
+ : undefined
1277
+ }));
1278
+
1279
+ m = {
1280
+ buttonsMessage: proto.Message.ButtonsMessage.create({
1281
+ locationMessage,
1282
+ contentText: bm.contentText || '',
1283
+ footerText: bm.footerText || '',
1284
+ buttons,
1285
+ headerType: bm.headerType ?? 6,
1286
+ viewOnce: !!bm.viewOnce
1287
+ })
1288
+ };
1289
+ }
1290
+ else {
1291
+ m = await prepareWAMessageMedia(message, options);
1292
+ }
1293
+
1294
+ if (hasNonNullishProperty(message, 'buttons')) {
1295
+ const buttonsMessage = {
1296
+ buttons: message.buttons.map(button => {
1297
+
1298
+ const buttonText = button.text || button.buttonText;
1299
+ if (hasOptionalProperty(button, 'sections')) {
1300
+ return {
1301
+ nativeFlowInfo: {
1302
+ name: 'single_select',
1303
+ paramsJson: JSON.stringify({
1304
+ title: buttonText,
1305
+ sections: button.sections
1306
+ })
1307
+ },
1308
+ type: ButtonType.NATIVE_FLOW
1309
+ };
1310
+ }
1311
+ else if (hasOptionalProperty(button, 'name')) {
1312
+ return {
1313
+ nativeFlowInfo: {
1314
+ name: button.name,
1315
+ paramsJson: button.paramsJson
1316
+ },
1317
+ type: ButtonType.NATIVE_FLOW
1318
+ };
1319
+ }
1320
+ return {
1321
+ buttonId: button.id || button.buttonId,
1322
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1323
+ type: button.type || ButtonType.RESPONSE
1324
+ };
1325
+ })
1326
+ };
1327
+ if (hasOptionalProperty(message, 'text')) {
1328
+ buttonsMessage.contentText = message.text;
1329
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
1330
+ }
1331
+ else {
1332
+ if (hasOptionalProperty(message, 'caption')) {
1333
+ buttonsMessage.contentText = message.caption;
1334
+ }
1335
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1336
+ buttonsMessage.headerType = ButtonHeaderType[type];
1337
+ Object.assign(buttonsMessage, m);
1338
+ }
1339
+ if (hasOptionalProperty(message, 'footer')) {
1340
+ buttonsMessage.footerText = message.footer;
1341
+ }
1342
+ m = { buttonsMessage };
1343
+ }
1344
+ else if (hasNonNullishProperty(message, 'sections')) {
1345
+ const listMessage = {
1346
+ sections: message.sections,
1347
+ buttonText: message.buttonText,
1348
+ title: message.title,
1349
+ footerText: message.footer,
1350
+ description: message.text,
1351
+ listType: ListType.SINGLE_SELECT
1352
+ };
1353
+ m = { listMessage };
1354
+ }
1355
+
1356
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1357
+ const hydratedTemplate = {
1358
+ hydratedButtons: message.templateButtons.map((button, i) => {
1359
+ const buttonText = button.text || button.buttonText;
1360
+ if (hasOptionalProperty(button, 'id')) {
1361
+ return {
1362
+ index: i,
1363
+ quickReplyButton: {
1364
+ displayText: buttonText || '👉🏻 Click',
1365
+ id: button.id
1366
+ }
1367
+ };
1368
+ }
1369
+ else if (hasOptionalProperty(button, 'url')) {
1370
+ return {
1371
+ index: i,
1372
+ urlButton: {
1373
+ displayText: buttonText || '🌐 Visit',
1374
+ url: button.url
1375
+ }
1376
+ };
1377
+ }
1378
+ else if (hasOptionalProperty(button, 'call')) {
1379
+ return {
1380
+ index: i,
1381
+ callButton: {
1382
+ displayText: buttonText || '📞 Call',
1383
+ phoneNumber: button.call
1384
+ }
1385
+ };
1386
+ }
1387
+ button.index = button.index || i;
1388
+ return button;
1389
+ })
1390
+ };
1391
+ if (hasOptionalProperty(message, 'text')) {
1392
+ hydratedTemplate.hydratedContentText = message.text;
1393
+ }
1394
+ else {
1395
+ if (hasOptionalProperty(message, 'caption')) {
1396
+ hydratedTemplate.hydratedTitleText = message.title;
1397
+ hydratedTemplate.hydratedContentText = message.caption;
1398
+ }
1399
+ ;
1400
+ Object.assign(hydratedTemplate, m);
1401
+ }
1402
+ if (hasOptionalProperty(message, 'footer')) {
1403
+ hydratedTemplate.hydratedFooterText = message.footer;
1404
+ }
1405
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now();
1406
+ m = {
1407
+ templateMessage: {
1408
+ hydratedFourRowTemplate: hydratedTemplate,
1409
+ hydratedTemplate: hydratedTemplate
1410
+ }
1411
+ };
1412
+ }
1413
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1414
+ const interactiveMessage = {
1415
+ nativeFlowMessage: prepareNativeFlowButtons(message, options)
1416
+ };
1417
+ if (hasNonNullishProperty(message, 'bloksWidget')) {
1418
+ interactiveMessage.bloksWidget = message.bloksWidget;
1419
+ }
1420
+ if (hasOptionalProperty(message, 'bizJid')) {
1421
+ interactiveMessage.collectionMessage = {
1422
+ bizJid: message.bizJid,
1423
+ id: message.id,
1424
+ messageVersion: 1
1425
+ };
1426
+ }
1427
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1428
+ interactiveMessage.shopStorefrontMessage = {
1429
+ surface: message.shopSurface,
1430
+ id: message.id,
1431
+ messageVersion: 1
1432
+ };
1433
+ }
1434
+ if (hasOptionalProperty(message, 'text')) {
1435
+ interactiveMessage.body = { text: message.text };
1436
+ }
1437
+ else {
1438
+ if (hasOptionalProperty(message, 'caption')) {
1439
+ const isValidHeader = hasValidInteractiveHeader(m);
1440
+ if (!isValidHeader) {
1441
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1442
+ }
1443
+ interactiveMessage.header = {
1444
+ ...headerText(message),
1445
+ hasMediaAttachment: isValidHeader
1446
+ };
1447
+ interactiveMessage.body = { text: message.caption };
1448
+ }
1449
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1450
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1451
+ }
1452
+ Object.assign(interactiveMessage.header, m);
1453
+ }
1454
+ if (hasOptionalProperty(message, 'audioFooter')) {
1455
+ const { audioMessage } = await prepareWAMessageMedia({
1456
+ audio: message.audioFooter
1457
+ }, options);
1458
+ interactiveMessage.footer = {
1459
+ audioMessage,
1460
+ hasMediaAttachment: true
1461
+ };
1462
+ }
1463
+ else if (hasOptionalProperty(message, 'footer')) {
1464
+ interactiveMessage.footer = { text: message.footer };
1465
+ }
1466
+ m = { interactiveMessage };
1467
+ }
1468
+ else if (hasNonNullishProperty(message, 'cards')) {
1469
+ const interactiveMessage = {
1470
+ carouselMessage: {
1471
+ cards: await Promise.all(message.cards.map(async (card) => {
1472
+ let carouselHeader = {};
1473
+ if (hasNonNullishProperty(card, 'product')) {
1474
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1475
+ }
1476
+ else {
1477
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1478
+ }
1479
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1480
+ if (!isValidHeader) {
1481
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1482
+ }
1483
+ const carouselCard = {
1484
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [], options)
1485
+ };
1486
+ if (hasOptionalProperty(card, 'text')) {
1487
+ carouselCard.body = { text: card.text };
1488
+ }
1489
+ else {
1490
+ if (hasOptionalProperty(card, 'caption')) {
1491
+ carouselCard.header = {
1492
+ ...headerText(card),
1493
+ hasMediaAttachment: isValidHeader
1494
+ };
1495
+ carouselCard.body = { text: card.caption };
1496
+ }
1497
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1498
+ carouselCard.jpegThumbnail = card.thumbnail;
1499
+ }
1500
+ Object.assign(carouselCard.header, carouselHeader);
1501
+ }
1502
+ if (hasOptionalProperty(card, 'audioFooter')) {
1503
+ const { audioMessage } = await prepareWAMessageMedia({
1504
+ audio: card.audioFooter
1505
+ }, options);
1506
+ carouselCard.footer = {
1507
+ audioMessage,
1508
+ hasMediaAttachment: true
1509
+ };
1510
+ }
1511
+ else if (hasOptionalProperty(card, 'footer')) {
1512
+ carouselCard.footer = { text: card.footer };
1513
+ }
1514
+ return carouselCard;
1515
+ })),
1516
+ carouselCardType: CarouselCardType.UNKNOWN,
1517
+ messageVersion: 1
1518
+ }
1519
+ };
1520
+ if (hasOptionalProperty(message, 'text')) {
1521
+ interactiveMessage.body = { text: message.text };
1522
+ }
1523
+ if (hasOptionalProperty(message, 'footer')) {
1524
+ interactiveMessage.footer = { text: message.footer };
1525
+ }
1526
+ m = { interactiveMessage };
1527
+ }
1528
+
1529
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1530
+ const requestPaymentMessage = {
1531
+ amount: {
1532
+ currencyCode: 'IDR',
1533
+ offset: 1000,
1534
+ value: 1000
1535
+ },
1536
+ amount1000: 1000,
1537
+ currencyCodeIso4217: 'IDR',
1538
+ expiryTimestamp: Date.now(),
1539
+ noteMessage: m,
1540
+ requestFrom: message.requestPaymentFrom,
1541
+ ...message
1542
+ };
1543
+ delete requestPaymentMessage.requestPaymentFrom;
1544
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1545
+ Object.assign(requestPaymentMessage.noteMessage, m);
1546
+ }
1547
+ else {
1548
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1549
+ }
1550
+ m = { requestPaymentMessage };
1551
+ }
1552
+
1553
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1554
+ const attachment = m.imageMessage || m.documentMessage;
1555
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1556
+ const invoiceMessage = {
1557
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1558
+ note: message.invoiceNote
1559
+ };
1560
+ if (attachment) {
1561
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1562
+ Object.assign(invoiceMessage, {
1563
+ attachmentDirectPath: directPath,
1564
+ attachmentFileEncSha256: fileEncSha256,
1565
+ attachmentFileSha256: fileSha256,
1566
+ attachmentJpegThumbnail: jpegThumbnail,
1567
+ attachmentMediaKey: mediaKey,
1568
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1569
+ attachmentMimetype: mimetype,
1570
+ token: generateMessageIDV2()
1571
+ });
1572
+ }
1573
+ else {
1574
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1575
+ }
1576
+ m = { invoiceMessage };
1577
+ }
1578
+
1579
+ if (hasNonNullishProperty(message, 'statusLinkPreview')) {
1580
+ const style = Number(message.statusLinkPreview.style ?? message.statusLinkPreview);
1581
+ if (!Number.isInteger(style) || style < 0) {
1582
+ throw new Boom('statusLinkPreview style must be a non-negative integer', { statusCode: 400 });
1583
+ }
1584
+ m.statusLinkPreviewMetadata = { style };
1585
+ }
1586
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1587
+ const messageType = Object.keys(m)[0];
1588
+ const key = m[messageType];
1589
+ const content = message.externalAdReply;
1590
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1591
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1592
+ }
1593
+ if (!content.url || typeof content.url !== 'string') {
1594
+ content.url = DONATE_URL;
1595
+ }
1596
+ const externalAdReply = {
1597
+ ...content,
1598
+ body: content.body,
1599
+ mediaType: content.mediaType || 1,
1600
+ renderLargerThumbnail: content.largeThumbnail,
1601
+ sourceUrl: content.url,
1602
+ thumbnail: content.thumbnail,
1603
+ title: content.title || LIBRARY_NAME
1604
+ };
1605
+ if (content.thumbnailUrl) {
1606
+ externalAdReply.thumbnailUrl = content.thumbnailUrl;
1607
+ }
1608
+ if (content.mediaUrl) {
1609
+ externalAdReply.mediaUrl = content.mediaUrl;
1610
+ }
1611
+ delete externalAdReply.subTitle;
1612
+ delete externalAdReply.largeThumbnail;
1613
+ delete externalAdReply.url;
1614
+ if (!externalAdReply.thumbnail && !externalAdReply.thumbnailUrl) {
1615
+ options.logger?.warn?.('externalAdReply has no thumbnail and no thumbnailUrl, so the card draws without a picture');
1616
+ }
1617
+ if ('contextInfo' in key && !!key.contextInfo) {
1618
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1619
+ }
1620
+ else if (key) {
1621
+ key.contextInfo = { externalAdReply };
1622
+ }
1623
+ }
1624
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1625
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll) ||
1626
+ (hasOptionalProperty(message, 'groupMentions') && message.groupMentions?.length)) {
1627
+ const messageType = Object.keys(m)[0];
1628
+ const key = m[messageType];
1629
+ if (key && typeof key === 'object') {
1630
+ key.contextInfo = ('contextInfo' in key && key.contextInfo) ? key.contextInfo : {};
1631
+ if (message.mentions?.length) {
1632
+ key.contextInfo.mentionedJid = message.mentions;
1633
+ }
1634
+ if (message.mentionAll) {
1635
+ key.contextInfo.nonJidMentions = 1;
1636
+ }
1637
+ if (message.groupMentions?.length) {
1638
+ const normalized = message.groupMentions
1639
+ .filter((gm) => gm?.groupJid)
1640
+ .map((gm) => ({
1641
+ groupJid: `${String(gm.groupJid).split('@')[0]}@g.us`,
1642
+ groupSubject: gm.groupSubject
1643
+ }));
1644
+ key.contextInfo.groupMentions = normalized;
1645
+ const field = 'text' in key ? 'text' : 'caption' in key ? 'caption' : null;
1646
+ if (field) {
1647
+ let body = key[field] || '';
1648
+ for (const gm of normalized) {
1649
+ const token = `@${gm.groupJid}`;
1650
+ if (!body.includes(token)) {
1651
+ body = body.length ? `${body} ${token}` : token;
1652
+ }
1653
+ }
1654
+ key[field] = body;
1655
+ }
1656
+ }
1657
+ }
1658
+ }
1659
+ if (hasOptionalProperty(message, 'forwardedNewsletter') && !!message.forwardedNewsletter) {
1660
+ const messageType = Object.keys(m)[0];
1661
+ const key = m[messageType];
1662
+ if (key && typeof key === 'object') {
1663
+ const info = message.forwardedNewsletter;
1664
+ const forwardedNewsletterMessageInfo = { newsletterJid: info.newsletterJid };
1665
+ if (info.serverMessageId !== undefined) {
1666
+ forwardedNewsletterMessageInfo.serverMessageId = Number(info.serverMessageId) || 0;
1667
+ }
1668
+ if (info.newsletterName !== undefined) {
1669
+ forwardedNewsletterMessageInfo.newsletterName = info.newsletterName;
1670
+ }
1671
+ if (info.contentType !== undefined) {
1672
+ forwardedNewsletterMessageInfo.contentType = info.contentType;
1673
+ }
1674
+ if (info.accessibilityText !== undefined) {
1675
+ forwardedNewsletterMessageInfo.accessibilityText = info.accessibilityText;
1676
+ }
1677
+ key.contextInfo = ('contextInfo' in key && key.contextInfo) ? key.contextInfo : {};
1678
+ key.contextInfo.forwardedNewsletterMessageInfo = forwardedNewsletterMessageInfo;
1679
+ key.contextInfo.isForwarded = true;
1680
+ }
1681
+ }
1682
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1683
+ const messageType = Object.keys(m)[0];
1684
+ const key = m[messageType];
1685
+ if ('contextInfo' in key && !!key.contextInfo) {
1686
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1687
+ }
1688
+ else if (key) {
1689
+ key.contextInfo = message.contextInfo;
1690
+ }
1691
+ }
1692
+
1693
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1694
+ const messageType = Object.keys(m)[0];
1695
+ const key = m[messageType];
1696
+ if ('contextInfo' in key && !!key.contextInfo) {
1697
+ key.contextInfo.isGroupStatus = message.groupStatus;
1698
+ }
1699
+ else if (key) {
1700
+ key.contextInfo = {
1701
+ isGroupStatus: message.groupStatus
1702
+ };
1703
+ }
1704
+ m = { groupStatusMessageV2: { message: m } };
1705
+ delete message.groupStatus;
1706
+ }
1707
+
1708
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1709
+ const messageType = Object.keys(m)[0];
1710
+ const key = m[messageType];
1711
+ if ('contextInfo' in key && !!key.contextInfo) {
1712
+ key.contextInfo.isSpoiler = message.spoiler;
1713
+ }
1714
+ else if (key) {
1715
+ key.contextInfo = {
1716
+ isSpoiler: message.spoiler
1717
+ };
1718
+ }
1719
+ m = { spoilerMessage: { message: m } };
1720
+ delete message.spoiler;
1721
+ }
1722
+
1723
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1724
+ if (!m.interactiveMessage) {
1725
+ throw new Boom('Invalid message type for template', { statusCode: 400 });
1726
+ }
1727
+ m = {
1728
+ templateMessage: {
1729
+ interactiveMessageTemplate: m.interactiveMessage,
1730
+ templateId: message.id || 'template-' + Date.now()
1731
+ }
1732
+ };
1733
+ delete message.interactiveAsTemplate;
1734
+ }
1735
+
1736
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1737
+ m = { ephemeralMessage: { message: m } };
1738
+ delete message.ephemeral;
1739
+ }
1740
+
1741
+ const markInnerViewOnce = (inner) => {
1742
+ const key = getContentType(inner);
1743
+ const target = key && inner[key];
1744
+ if (target && typeof target === 'object' && 'viewOnce' in proto.Message[key.charAt(0).toUpperCase() + key.slice(1)].prototype) {
1745
+ target.viewOnce = true;
1746
+ }
1747
+ };
1748
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1749
+ m = { lottieStickerMessage: { message: m } };
1750
+ }
1751
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1752
+ markInnerViewOnce(m);
1753
+ m = { viewOnceMessage: { message: m } };
1754
+ }
1755
+
1756
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1757
+ markInnerViewOnce(m);
1758
+ m = { viewOnceMessageV2: { message: m } };
1759
+ delete message.viewOnceV2;
1760
+ }
1761
+
1762
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1763
+ markInnerViewOnce(m);
1764
+ m = { viewOnceMessageV2Extension: { message: m } };
1765
+ delete message.viewOnceV2Extension;
1766
+ }
1767
+ if (hasOptionalProperty(message, 'edit')) {
1768
+ m = {
1769
+ protocolMessage: {
1770
+ key: message.edit,
1771
+ editedMessage: m,
1772
+ timestampMs: Date.now(),
1773
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1774
+ }
1775
+ };
1776
+ }
1777
+ if (hasOptionalProperty(message, 'messageAssociation') && !!message.messageAssociation) {
1778
+ m.messageContextInfo = m.messageContextInfo || {};
1779
+ m.messageContextInfo.messageAssociation = message.messageAssociation;
1780
+ }
1781
+ if (shouldIncludeReportingToken(m)) {
1782
+ m.messageContextInfo = m.messageContextInfo || {};
1783
+ if (!m.messageContextInfo.messageSecret) {
1784
+ m.messageContextInfo.messageSecret = randomBytes(32);
1785
+ }
1786
+ }
1787
+ return WAProto.Message.create(m);
1788
+ };
1789
+ export const generateWAMessageFromContent = (jid, message, options) => {
1790
+
1791
+ if (!options.timestamp) {
1792
+ options.timestamp = new Date();
1793
+ }
1794
+ const innerMessage = normalizeMessageContent(message);
1795
+ const messageContextInfo = message.messageContextInfo;
1796
+ const key = getContentType(innerMessage);
1797
+ const timestamp = unixTimestampSeconds(options.timestamp);
1798
+ const isNewsletter = isJidNewsletter(jid);
1799
+ const { quoted, userJid } = options;
1800
+ const quotedContentType = quoted ? getContentType(normalizeMessageContent(quoted.message)) : undefined;
1801
+ if (quoted && (!quotedContentType || !key || !innerMessage[key])) {
1802
+ options.logger?.warn?.({
1803
+ jid,
1804
+ quotedId: quoted.key?.id,
1805
+ quotedContentType,
1806
+ contentType: key
1807
+ }, 'nothing quotable here, sending without the quote');
1808
+ }
1809
+ else if (quoted) {
1810
+ const participant = quoted.key.fromMe
1811
+ ? userJid
1812
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1813
+ const normalizedQuoted = normalizeMessageContent(quoted.message);
1814
+ const msgType = quotedContentType;
1815
+ const quotedMsg = proto.Message.create({ [msgType]: normalizedQuoted[msgType] });
1816
+ const quotedContent = quotedMsg[msgType];
1817
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1818
+ delete quotedContent.contextInfo;
1819
+ }
1820
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1821
+ contextInfo.participant = jidNormalizedUser(participant);
1822
+ contextInfo.stanzaId = quoted.key.id;
1823
+ contextInfo.quotedMessage = quotedMsg;
1824
+
1825
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
1826
+ contextInfo.remoteJid = quoted.key.remoteJid;
1827
+ }
1828
+ innerMessage[key].contextInfo = contextInfo;
1829
+ }
1830
+ if (
1831
+
1832
+ !!options?.ephemeralExpiration &&
1833
+
1834
+ key !== 'protocolMessage' &&
1835
+
1836
+ key !== 'ephemeralMessage' &&
1837
+
1838
+ !isNewsletter) {
1839
+
1840
+ innerMessage[key].contextInfo = {
1841
+ ...(innerMessage[key].contextInfo || {}),
1842
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1843
+
1844
+ };
1845
+ }
1846
+
1847
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1848
+ messageContextInfo.deviceListMetadata = {
1849
+ recipientKeyHash: randomBytes(10),
1850
+ recipientTimestamp: unixTimestampSeconds()
1851
+ };
1852
+ messageContextInfo.deviceListMetadataVersion = 2;
1853
+ }
1854
+ message = WAProto.Message.create(message);
1855
+ const messageJSON = {
1856
+ key: {
1857
+ remoteJid: jid,
1858
+ fromMe: true,
1859
+ id: options?.messageId || generateMessageIDV2()
1860
+ },
1861
+ message: message,
1862
+ messageTimestamp: timestamp,
1863
+ messageStubParameters: [],
1864
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined,
1865
+ status: WAMessageStatus.PENDING
1866
+ };
1867
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1868
+ };
1869
+ export const generateWAMessage = async (jid, content, options) => {
1870
+
1871
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1872
+
1873
+ if (jid) {
1874
+ options.jid = jid;
1875
+ }
1876
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1877
+ };
1878
+
1879
+ export const getContentType = (content) => {
1880
+ if (content) {
1881
+ const keys = Object.keys(content);
1882
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1883
+ return key;
1884
+ }
1885
+ };
1886
+
1887
+ export const FUTURE_PROOF_MESSAGE_KEYS = [
1888
+ 'acp2SettingMessage',
1889
+ 'associatedChildMessage',
1890
+ 'audioStickerMessage',
1891
+ 'botForwardedMessage',
1892
+ 'botGroupParticipantMessage',
1893
+ 'botInvokeMessage',
1894
+ 'botPlatformRegistrationSuccessMessage',
1895
+ 'botTaskMessage',
1896
+ 'documentWithCaptionMessage',
1897
+ 'editedMessage',
1898
+ 'ephemeralMessage',
1899
+ 'eventCoverImage',
1900
+ 'groupMentionedMessage',
1901
+ 'groupStatusMentionMessage',
1902
+ 'groupStatusMessage',
1903
+ 'groupStatusMessageV2',
1904
+ 'limitSharingMessage',
1905
+ 'lottieStickerMessage',
1906
+ 'newsletterAdminProfileMessage',
1907
+ 'newsletterAdminProfileMessageV2',
1908
+ 'newsletterAdminProfileStatusMessage',
1909
+ 'newsletterScheduledMessage',
1910
+ 'pollCreationMessageV4',
1911
+ 'pollCreationOptionImageMessage',
1912
+ 'questionMessage',
1913
+ 'questionReplyMessage',
1914
+ 'spoilerMessage',
1915
+ 'statusAddYours',
1916
+ 'statusMentionMessage',
1917
+ 'viewOnceMessage',
1918
+ 'viewOnceMessageV2',
1919
+ 'viewOnceMessageV2Extension'
1920
+ ];
1921
+
1922
+ const getFutureProofMessage = (message) => {
1923
+ if (!message) {
1924
+ return undefined;
1925
+ }
1926
+ for (const key of FUTURE_PROOF_MESSAGE_KEYS) {
1927
+ const wrapper = message[key];
1928
+ if (wrapper) {
1929
+ return wrapper;
1930
+ }
1931
+ }
1932
+ return undefined;
1933
+ };
1934
+
1935
+ export const normalizeMessageContent = (content) => {
1936
+ if (!content) {
1937
+ return undefined;
1938
+ }
1939
+
1940
+ for (let i = 0; i < 5; i++) {
1941
+ const inner = getFutureProofMessage(content);
1942
+ if (!inner) {
1943
+ break;
1944
+ }
1945
+ content = inner.message;
1946
+ }
1947
+ return content;
1948
+ };
1949
+
1950
+ export const extractMessageContent = (content) => {
1951
+ const extractFromTemplateMessage = (msg) => {
1952
+ if (msg.imageMessage) {
1953
+ return { imageMessage: msg.imageMessage };
1954
+ }
1955
+ else if (msg.documentMessage) {
1956
+ return { documentMessage: msg.documentMessage };
1957
+ }
1958
+ else if (msg.videoMessage) {
1959
+ return { videoMessage: msg.videoMessage };
1960
+ }
1961
+ else if (msg.locationMessage) {
1962
+ return { locationMessage: msg.locationMessage };
1963
+ }
1964
+ else {
1965
+ return {
1966
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1967
+ };
1968
+ }
1969
+ };
1970
+ content = normalizeMessageContent(content);
1971
+ if (content?.buttonsMessage) {
1972
+ return extractFromTemplateMessage(content.buttonsMessage);
1973
+ }
1974
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1975
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1976
+ }
1977
+ if (content?.templateMessage?.hydratedTemplate) {
1978
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1979
+ }
1980
+ if (content?.templateMessage?.fourRowTemplate) {
1981
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1982
+ }
1983
+ return content;
1984
+ };
1985
+
1986
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1987
+ ? 'ios'
1988
+ : /^3E.{20}$/.test(id)
1989
+ ? 'web'
1990
+ : /^(.{21}|.{32})$/.test(id)
1991
+ ? 'android'
1992
+ : /^(3F|.{18}$)/.test(id)
1993
+ ? 'desktop'
1994
+ : 'unknown';
1995
+
1996
+ export const updateMessageWithReceipt = (msg, receipt) => {
1997
+ msg.userReceipt = msg.userReceipt || [];
1998
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1999
+ if (recp) {
2000
+ Object.assign(recp, receipt);
2001
+ }
2002
+ else {
2003
+ msg.userReceipt.push(receipt);
2004
+ }
2005
+ };
2006
+
2007
+ export const updateMessageWithReaction = (msg, reaction) => {
2008
+ const authorID = getKeyAuthor(reaction.key);
2009
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
2010
+ reaction.text = reaction.text || '';
2011
+ reactions.push(reaction);
2012
+ msg.reactions = reactions;
2013
+ };
2014
+
2015
+ export const updateMessageWithPollUpdate = (msg, update) => {
2016
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
2017
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
2018
+ if (update.vote?.selectedOptions?.length) {
2019
+ reactions.push(update);
2020
+ }
2021
+ msg.pollUpdates = reactions;
2022
+ };
2023
+
2024
+ export const updateMessageWithEventResponse = (msg, update) => {
2025
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
2026
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
2027
+ responses.push(update);
2028
+ msg.eventResponses = responses;
2029
+ };
2030
+
2031
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
2032
+ const opts = message?.pollCreationMessage?.options ||
2033
+ message?.pollCreationMessageV2?.options ||
2034
+ message?.pollCreationMessageV3?.options ||
2035
+ [];
2036
+ const voteHashMap = opts.reduce((acc, opt) => {
2037
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
2038
+ acc[hash] = {
2039
+ name: opt.optionName || '',
2040
+ voters: []
2041
+ };
2042
+ return acc;
2043
+ }, {});
2044
+ for (const update of pollUpdates || []) {
2045
+ const { vote } = update;
2046
+ if (!vote) {
2047
+ continue;
2048
+ }
2049
+ for (const option of vote.selectedOptions || []) {
2050
+ const hash = option.toString();
2051
+ let data = voteHashMap[hash];
2052
+ if (!data) {
2053
+ voteHashMap[hash] = {
2054
+ name: 'Unknown',
2055
+ voters: []
2056
+ };
2057
+ data = voteHashMap[hash];
2058
+ }
2059
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
2060
+ }
2061
+ }
2062
+ return Object.values(voteHashMap);
2063
+ }
2064
+
2065
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
2066
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
2067
+ const responseMap = {};
2068
+ for (const type of responseTypes) {
2069
+ responseMap[type] = {
2070
+ response: type,
2071
+ responders: []
2072
+ };
2073
+ }
2074
+ for (const update of eventResponses || []) {
2075
+ const responseType = update.eventResponse || 'UNKNOWN';
2076
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
2077
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
2078
+ }
2079
+ }
2080
+ return Object.values(responseMap);
2081
+ }
2082
+
2083
+ export const aggregateMessageKeysNotFromMe = (keys) => {
2084
+ const keyMap = {};
2085
+ for (const { remoteJid, id, participant, fromMe } of keys) {
2086
+ if (!fromMe) {
2087
+ const uqKey = `${remoteJid}:${participant || ''}`;
2088
+ if (!keyMap[uqKey]) {
2089
+ keyMap[uqKey] = {
2090
+ jid: remoteJid,
2091
+ participant: participant,
2092
+ messageIds: []
2093
+ };
2094
+ }
2095
+ keyMap[uqKey].messageIds.push(id);
2096
+ }
2097
+ }
2098
+ return Object.values(keyMap);
2099
+ };
2100
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
2101
+
2102
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
2103
+ const result = await downloadMsg().catch(async (error) => {
2104
+ if (ctx &&
2105
+ typeof error?.status === 'number' &&
2106
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
2107
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
2108
+
2109
+ message = await ctx.reuploadRequest(message);
2110
+ const result = await downloadMsg();
2111
+ return result;
2112
+ }
2113
+ throw error;
2114
+ });
2115
+ return result;
2116
+ async function downloadMsg() {
2117
+ const mContent = extractMessageContent(message.message);
2118
+ if (!mContent) {
2119
+ throw new Boom('No message present', { statusCode: 400, data: message });
2120
+ }
2121
+ const contentType = getContentType(mContent);
2122
+ let mediaType = contentType?.replace('Message', '');
2123
+ const media = mContent[contentType];
2124
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
2125
+ throw new Boom(`"${contentType}" message is not a media message`);
2126
+ }
2127
+ let download;
2128
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
2129
+ download = {
2130
+ directPath: media.thumbnailDirectPath,
2131
+ mediaKey: media.mediaKey
2132
+ };
2133
+ mediaType = 'thumbnail-link';
2134
+ }
2135
+ else {
2136
+ download = media;
2137
+ }
2138
+ const stream = await downloadContentFromMessage(download, mediaType, options);
2139
+ if (type === 'buffer') {
2140
+ const bufferArray = [];
2141
+ for await (const chunk of stream) {
2142
+ bufferArray.push(chunk);
2143
+ }
2144
+ return Buffer.concat(bufferArray);
2145
+ }
2146
+ return stream;
2147
+ }
2148
+ };
2149
+
2150
+ export const assertMediaContent = (content) => {
2151
+ content = extractMessageContent(content);
2152
+ const mediaContent = content?.documentMessage ||
2153
+ content?.imageMessage ||
2154
+ content?.videoMessage ||
2155
+ content?.audioMessage ||
2156
+ content?.stickerMessage;
2157
+ if (!mediaContent) {
2158
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
2159
+ }
2160
+ return mediaContent;
2161
+ };
2162
+
2163
+ const isAnimatedWebP = (buffer) => {
2164
+
2165
+ if (buffer.length < 12 ||
2166
+ buffer[0] !== 0x52 ||
2167
+ buffer[1] !== 0x49 ||
2168
+ buffer[2] !== 0x46 ||
2169
+ buffer[3] !== 0x46 ||
2170
+ buffer[8] !== 0x57 ||
2171
+ buffer[9] !== 0x45 ||
2172
+ buffer[10] !== 0x42 ||
2173
+ buffer[11] !== 0x50) {
2174
+ return false;
2175
+ }
2176
+ ;
2177
+
2178
+ let offset = 12;
2179
+ while (offset < buffer.length - 8) {
2180
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
2181
+ const chunkSize = buffer.readUInt32LE(offset + 4);
2182
+ if (chunkFourCC === 'VP8X') {
2183
+
2184
+ const flagsOffset = offset + 8;
2185
+ if (flagsOffset < buffer.length) {
2186
+ const flags = buffer[flagsOffset];
2187
+ if (flags & 0x02) {
2188
+ return true;
2189
+ }
2190
+ ;
2191
+ }
2192
+ ;
2193
+ }
2194
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
2195
+
2196
+ return true;
2197
+ }
2198
+ ;
2199
+
2200
+ offset += 8 + chunkSize + (chunkSize % 2);
2201
+ }
2202
+ ;
2203
+ return false;
2204
+ };
2205
+
2206
+ const isWebPBuffer = (buffer) => {
2207
+ return (buffer.length >= 12 &&
2208
+ buffer[0] === 0x52 &&
2209
+ buffer[1] === 0x49 &&
2210
+ buffer[2] === 0x46 &&
2211
+ buffer[3] === 0x46 &&
2212
+ buffer[8] === 0x57 &&
2213
+ buffer[9] === 0x45 &&
2214
+ buffer[10] === 0x42 &&
2215
+ buffer[11] === 0x50);
2216
+ };
2217
+
2218
+ export const shouldIncludeBizBinaryNode = (message) => !!(message.buttonsMessage ||
2219
+ message.listMessage ||
2220
+ message.templateMessage ||
2221
+ (message.interactiveMessage &&
2222
+ (message.interactiveMessage.nativeFlowMessage ||
2223
+ message.interactiveMessage.carouselMessage?.cards?.some(card => card?.nativeFlowMessage))));