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