@fer2809fl/baileys 7.0.1 → 7.0.2

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