@nerxa/socketon 0.0.0-stage → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +100 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +37 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,1574 @@
1
+ import { TTLCache } from '../Utils/ttl-cache.js';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, MAX_OUTBOUND_RESEND_ENTRIES, MEMBER_LABEL_MAX_LENGTH, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getPollOptionHash, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AssociationType } from '../Types/index.js';
8
+ import { makeStatusMentionMessage } from '../Utils/modern-messages.js';
9
+ import { commitSenderKeyDelivery, pickSenderKeyRecipients, senderKeyResetSummary } from '../Utils/sender-key-memory.js';
10
+ import { describeUnusableGroupMetadata, isUsableGroupMetadata } from '../Utils/group-metadata-cache.js';
11
+ import { getUrlInfo } from '../Utils/link-preview.js';
12
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
13
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
14
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
15
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
16
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
17
+ import { makeNewsletterSocket } from './newsletter.js';
18
+ export const buildMemberLabelMessage = (jid, memberLabel) => {
19
+ if (!isJidGroup(jid)) {
20
+ throw new Boom('a member label belongs to a group, so jid must be a group jid', { statusCode: 400, data: { jid } });
21
+ }
22
+ const label = memberLabel === undefined || memberLabel === null ? '' : String(memberLabel).slice(0, MEMBER_LABEL_MAX_LENGTH);
23
+ return {
24
+ label,
25
+ content: {
26
+ protocolMessage: {
27
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
28
+ memberLabel: {
29
+ label,
30
+ labelTimestamp: unixTimestampSeconds()
31
+ }
32
+ }
33
+ },
34
+ node: {
35
+ tag: 'meta',
36
+ attrs: {
37
+ tag_reason: label ? 'user_update' : 'user_delete',
38
+ appdata: 'member_tag'
39
+ },
40
+ content: undefined
41
+ }
42
+ };
43
+ };
44
+ export const makeMessagesSocket = (config) => {
45
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
46
+ const sock = makeNewsletterSocket(config);
47
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
48
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
49
+
50
+ const inFlightTcTokenIssuance = new Set();
51
+ const userDevicesCache = config.userDevicesCache ||
52
+ new TTLCache({ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES });
53
+
54
+ const devicesMutex = makeMutex();
55
+
56
+ const outboundResendCache = config.outboundResendCache ||
57
+ new TTLCache({ stdTTL: DEFAULT_CACHE_TTLS.OUTBOUND_RESEND, maxKeys: MAX_OUTBOUND_RESEND_ENTRIES });
58
+ const rememberOutboundMessage = (messageId, jid, message) => {
59
+ if (!messageId || !message) {
60
+ return;
61
+ }
62
+ try {
63
+ outboundResendCache.set(messageId, { jid, message });
64
+ }
65
+ catch {
66
+
67
+ }
68
+ };
69
+
70
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
71
+
72
+ const encryptionMutex = makeKeyedMutex();
73
+
74
+ const mediaConnMutex = makeKeyedMutex();
75
+ let mediaConn;
76
+
77
+ let mediaHost = DEF_MEDIA_HOST;
78
+ const refreshMediaConn = async (forceGet = false) => {
79
+ return mediaConnMutex.mutex('media-conn', async () => {
80
+ const media = await mediaConn;
81
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
82
+ mediaConn = (async () => {
83
+ const result = await query({
84
+ tag: 'iq',
85
+ attrs: {
86
+ type: 'set',
87
+ xmlns: 'w:m',
88
+ to: S_WHATSAPP_NET
89
+ },
90
+ content: [{ tag: 'media_conn', attrs: {} }]
91
+ });
92
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
93
+
94
+ const node = {
95
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
96
+ hostname: attrs.hostname,
97
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
98
+ })),
99
+ auth: mediaConnNode.attrs.auth,
100
+ ttl: +mediaConnNode.attrs.ttl,
101
+ fetchDate: new Date()
102
+ };
103
+ logger.debug('fetched media conn');
104
+ if (node.hosts[0]) {
105
+ mediaHost = node.hosts[0].hostname;
106
+ }
107
+ return node;
108
+ })();
109
+ }
110
+ return mediaConn;
111
+ });
112
+ };
113
+
114
+ const sendReceipt = async (jid, participant, messageIds, type) => {
115
+ if (!messageIds || messageIds.length === 0) {
116
+ throw new Boom('missing ids in receipt');
117
+ }
118
+ const node = {
119
+ tag: 'receipt',
120
+ attrs: {
121
+ id: messageIds[0]
122
+ }
123
+ };
124
+ const isReadReceipt = type === 'read' || type === 'read-self';
125
+ if (isReadReceipt) {
126
+ node.attrs.t = unixTimestampSeconds().toString();
127
+ }
128
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
129
+ node.attrs.recipient = jid;
130
+ node.attrs.to = participant;
131
+ }
132
+ else {
133
+ node.attrs.to = jid;
134
+ if (participant) {
135
+ node.attrs.participant = participant;
136
+ }
137
+ }
138
+ if (type) {
139
+ node.attrs.type = type;
140
+ }
141
+ const remainingMessageIds = messageIds.slice(1);
142
+ if (remainingMessageIds.length) {
143
+ node.content = [
144
+ {
145
+ tag: 'list',
146
+ attrs: {},
147
+ content: remainingMessageIds.map(id => ({
148
+ tag: 'item',
149
+ attrs: { id }
150
+ }))
151
+ }
152
+ ];
153
+ }
154
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
155
+ await sendNode(node);
156
+ };
157
+
158
+ const sendReceipts = async (keys, type) => {
159
+ const recps = aggregateMessageKeysNotFromMe(keys);
160
+ for (const { jid, participant, messageIds } of recps) {
161
+ await sendReceipt(jid, participant, messageIds, type);
162
+ }
163
+ };
164
+
165
+ const readMessages = async (keys) => {
166
+ const privacySettings = await fetchPrivacySettings();
167
+
168
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
169
+ await sendReceipts(keys, readType);
170
+ };
171
+
172
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
173
+ const deviceResults = [];
174
+ if (!useCache) {
175
+ logger.debug('not using cache for devices');
176
+ }
177
+ const toFetch = [];
178
+ const jidsWithUser = jids
179
+ .map(jid => {
180
+ const decoded = jidDecode(jid);
181
+ const user = decoded?.user;
182
+ const device = decoded?.device;
183
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
184
+ if (isExplicitDevice && user) {
185
+ deviceResults.push({
186
+ user,
187
+ device,
188
+ jid
189
+ });
190
+ return null;
191
+ }
192
+ jid = jidNormalizedUser(jid);
193
+ return { jid, user };
194
+ })
195
+ .filter(jid => jid !== null);
196
+ let mgetDevices;
197
+ if (useCache && userDevicesCache.mget) {
198
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
199
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
200
+ }
201
+ for (const { jid, user } of jidsWithUser) {
202
+ if (useCache) {
203
+ const devices = mgetDevices?.[user] ||
204
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
205
+ if (devices) {
206
+ const devicesWithJid = devices.map(d => ({
207
+ ...d,
208
+ jid: jidEncode(d.user, d.server, d.device)
209
+ }));
210
+ deviceResults.push(...devicesWithJid);
211
+ logger.trace({ user }, 'using cache for devices');
212
+ }
213
+ else {
214
+ toFetch.push(jid);
215
+ }
216
+ }
217
+ else {
218
+ toFetch.push(jid);
219
+ }
220
+ }
221
+ if (!toFetch.length) {
222
+ return deviceResults;
223
+ }
224
+ const requestedLidUsers = new Set();
225
+ for (const jid of toFetch) {
226
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
227
+ const user = jidDecode(jid)?.user;
228
+ if (user)
229
+ requestedLidUsers.add(user);
230
+ }
231
+ }
232
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
233
+ for (const jid of toFetch) {
234
+ query.withUser(new USyncUser().withId(jid));
235
+ }
236
+ const result = await sock.executeUSyncQuery(query);
237
+ if (result) {
238
+
239
+ const lidResults = result.list.filter(a => !!a.lid);
240
+ if (lidResults.length > 0) {
241
+ logger.trace('Storing LID maps from device call');
242
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
243
+
244
+ try {
245
+ const lids = lidResults.map(a => a.lid);
246
+ if (lids.length) {
247
+ await assertSessions(lids, true);
248
+ }
249
+ }
250
+ catch (e) {
251
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
252
+ }
253
+ }
254
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
255
+ const deviceMap = {};
256
+ for (const item of extracted) {
257
+ deviceMap[item.user] = deviceMap[item.user] || [];
258
+ deviceMap[item.user]?.push(item);
259
+ }
260
+
261
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
262
+ const isLidUser = requestedLidUsers.has(user);
263
+
264
+ for (const item of userDevices) {
265
+ const finalJid = isLidUser
266
+ ? jidEncode(user, item.server, item.device)
267
+ : jidEncode(item.user, item.server, item.device);
268
+ deviceResults.push({
269
+ ...item,
270
+ jid: finalJid
271
+ });
272
+ logger.debug({
273
+ user: item.user,
274
+ device: item.device,
275
+ finalJid,
276
+ usedLid: isLidUser
277
+ }, 'Processed device with LID priority');
278
+ }
279
+ }
280
+ await devicesMutex.mutex(async () => {
281
+ if (userDevicesCache.mset) {
282
+
283
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
284
+ }
285
+ else {
286
+ for (const key in deviceMap) {
287
+ if (deviceMap[key])
288
+ await userDevicesCache.set(key, deviceMap[key]);
289
+ }
290
+ }
291
+ });
292
+ const userDeviceUpdates = {};
293
+ for (const [userId, devices] of Object.entries(deviceMap)) {
294
+ if (devices && devices.length > 0) {
295
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
296
+ }
297
+ }
298
+ if (Object.keys(userDeviceUpdates).length > 0) {
299
+ try {
300
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
301
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
302
+ }
303
+ catch (error) {
304
+ logger.warn({ error }, 'failed to store user device lists');
305
+ }
306
+ }
307
+ }
308
+ return deviceResults;
309
+ };
310
+
311
+ const updateMemberLabel = async (jid, memberLabel, options = {}) => {
312
+ const { label, content, node } = buildMemberLabelMessage(jid, memberLabel);
313
+ const messageId = await relayMessage(jid, content, {
314
+ ...options,
315
+ additionalNodes: [node, ...(options.additionalNodes ?? [])]
316
+ });
317
+ return { jid, label, messageId };
318
+ };
319
+
320
+ const removeMemberLabel = (jid, options = {}) => updateMemberLabel(jid, '', options);
321
+ const assertSessions = async (jids, force) => {
322
+ let didFetchNewSession = false;
323
+ const uniqueJids = [...new Set(jids)];
324
+ const jidsRequiringFetch = [];
325
+ logger.debug({ jids }, 'assertSessions call with jids');
326
+ for (const jid of uniqueJids) {
327
+ if (!force) {
328
+ const sessionValidation = await signalRepository.validateSession(jid);
329
+ if (sessionValidation.exists) {
330
+ continue;
331
+ }
332
+ }
333
+ jidsRequiringFetch.push(jid);
334
+ }
335
+ if (jidsRequiringFetch.length) {
336
+
337
+ const wireJids = [
338
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
339
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
340
+ ];
341
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
342
+ const result = await query({
343
+ tag: 'iq',
344
+ attrs: {
345
+ xmlns: 'encrypt',
346
+ type: 'get',
347
+ to: S_WHATSAPP_NET
348
+ },
349
+ content: [
350
+ {
351
+ tag: 'key',
352
+ attrs: {},
353
+ content: wireJids.map(jid => {
354
+ const attrs = { jid };
355
+ if (force)
356
+ attrs.reason = 'identity';
357
+ return { tag: 'user', attrs };
358
+ })
359
+ }
360
+ ]
361
+ });
362
+ await parseAndInjectE2ESessions(result, signalRepository);
363
+ didFetchNewSession = true;
364
+ }
365
+ return didFetchNewSession;
366
+ };
367
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
368
+
369
+ if (!authState.creds.me?.id) {
370
+ throw new Boom('Not authenticated');
371
+ }
372
+ const protocolMessage = {
373
+ protocolMessage: {
374
+ peerDataOperationRequestMessage: pdoMessage,
375
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
376
+ }
377
+ };
378
+ const meJid = jidNormalizedUser(authState.creds.me.id);
379
+ const msgId = await relayMessage(meJid, protocolMessage, {
380
+ additionalAttributes: {
381
+ category: 'peer',
382
+ push_priority: 'high_force'
383
+ },
384
+ additionalNodes: [
385
+ {
386
+ tag: 'meta',
387
+ attrs: { appdata: 'default' }
388
+ }
389
+ ]
390
+ });
391
+ return msgId;
392
+ };
393
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
394
+ if (!recipientJids.length) {
395
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
396
+ }
397
+ const patched = await patchMessageBeforeSending(message, recipientJids);
398
+ const patchedMessages = Array.isArray(patched)
399
+ ? patched
400
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
401
+ let shouldIncludeDeviceIdentity = false;
402
+ const meId = authState.creds.me.id;
403
+ const meLid = authState.creds.me?.lid;
404
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
405
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
406
+ try {
407
+ if (!jid)
408
+ return null;
409
+ let msgToEncrypt = patchedMessage;
410
+ if (dsmMessage) {
411
+ const { user: targetUser } = jidDecode(jid);
412
+ const { user: ownPnUser } = jidDecode(meId);
413
+ const ownLidUser = meLidUser;
414
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
415
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
416
+ if (isOwnUser && !isExactSenderDevice) {
417
+ msgToEncrypt = dsmMessage;
418
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
419
+ }
420
+ }
421
+ const bytes = encodeWAMessage(msgToEncrypt);
422
+ const mutexKey = jid;
423
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
424
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
425
+ if (type === 'pkmsg') {
426
+ shouldIncludeDeviceIdentity = true;
427
+ }
428
+ return {
429
+ tag: 'to',
430
+ attrs: { jid },
431
+ content: [
432
+ {
433
+ tag: 'enc',
434
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
435
+ content: ciphertext
436
+ }
437
+ ]
438
+ };
439
+ });
440
+ return node;
441
+ }
442
+ catch (err) {
443
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
444
+ return null;
445
+ }
446
+ });
447
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
448
+ if (recipientJids.length > 0 && nodes.length === 0) {
449
+ throw new Boom('All encryptions failed', { statusCode: 500 });
450
+ }
451
+ return { nodes, shouldIncludeDeviceIdentity };
452
+ };
453
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
454
+ const meId = assertMeId(authState.creds);
455
+ const meLid = authState.creds.me?.lid;
456
+ const isRetryResend = Boolean(participant?.jid);
457
+ let shouldIncludeDeviceIdentity = isRetryResend;
458
+ const statusJid = 'status@broadcast';
459
+ const { user, server } = jidDecode(jid);
460
+ const isGroup = server === 'g.us';
461
+ const isStatus = jid === statusJid;
462
+ const isLid = server === 'lid';
463
+ const isNewsletter = server === 'newsletter';
464
+ const isGroupOrStatus = isGroup || isStatus;
465
+ const finalJid = jid;
466
+ msgId = msgId || generateMessageIDV2(meId);
467
+ if (!isRetryResend) {
468
+ rememberOutboundMessage(msgId, jid, message);
469
+ }
470
+ useUserDevicesCache = useUserDevicesCache !== false;
471
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
472
+ const participants = [];
473
+ const destinationJid = !isStatus ? finalJid : statusJid;
474
+ const binaryNodeContent = [];
475
+ const devices = [];
476
+ let reportingMessage;
477
+ const meMsg = {
478
+ deviceSentMessage: {
479
+ destinationJid,
480
+ message
481
+ },
482
+ messageContextInfo: message.messageContextInfo
483
+ };
484
+ const extraAttrs = {};
485
+ if (participant) {
486
+ if (!isGroup && !isStatus) {
487
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
488
+ }
489
+ const { user, device } = jidDecode(participant.jid);
490
+ devices.push({
491
+ user,
492
+ device,
493
+ jid: participant.jid
494
+ });
495
+ }
496
+ await authState.keys.transaction(async () => {
497
+
498
+ const innerMessage = normalizeMessageContent(message);
499
+ const mediaType = getMediaType(innerMessage);
500
+ if (mediaType) {
501
+ extraAttrs['mediatype'] = mediaType;
502
+ }
503
+ if (isNewsletter) {
504
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
505
+ const bytes = encodeNewsletterMessage(patched);
506
+
507
+ if (additionalNodes && additionalNodes.length > 0) {
508
+ ;
509
+ binaryNodeContent.push(...additionalNodes);
510
+ }
511
+
512
+ const questionType = message?.questionMessage
513
+ ? 'question'
514
+ : message?.questionReplyMessage
515
+ ? 'reply'
516
+ : message?.questionResponseMessage
517
+ ? 'response'
518
+ : undefined;
519
+ if (questionType) {
520
+ const metaNode = binaryNodeContent.find(node => node?.tag === 'meta');
521
+ if (metaNode) {
522
+ metaNode.attrs = { ...metaNode.attrs, questiontype: questionType };
523
+ }
524
+ else {
525
+ binaryNodeContent.push({
526
+ tag: 'meta',
527
+ attrs: { questiontype: questionType },
528
+ content: undefined
529
+ });
530
+ }
531
+ }
532
+ binaryNodeContent.push({
533
+ tag: 'plaintext',
534
+ attrs: extraAttrs,
535
+ content: bytes
536
+ });
537
+ const stanza = {
538
+ tag: 'message',
539
+ attrs: {
540
+ to: jid,
541
+ id: msgId,
542
+ type: getMessageType(innerMessage),
543
+ ...(additionalAttributes || {})
544
+ },
545
+ content: binaryNodeContent
546
+ };
547
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
548
+ await sendNode(stanza);
549
+ return;
550
+ }
551
+
552
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
553
+
554
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
555
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
556
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
557
+ const metaAttrs = {};
558
+ if (isNeedMetaAttrs) {
559
+ metaAttrs.content_type = 'add_on';
560
+ }
561
+ if (isPollUpdate && !isGroupStatus) {
562
+ metaAttrs.polltype = 'vote';
563
+ }
564
+ if (isGroupStatus) {
565
+ metaAttrs.is_group_status = 'true';
566
+ }
567
+ binaryNodeContent.push({
568
+ tag: 'meta',
569
+ attrs: metaAttrs,
570
+ content: undefined
571
+ });
572
+ }
573
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
574
+ extraAttrs['decrypt-fail'] = 'hide';
575
+ }
576
+
577
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
578
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
579
+ }
580
+ if (isGroupOrStatus && !isRetryResend) {
581
+ const [groupData, senderKeyMap] = await Promise.all([
582
+ (async () => {
583
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
584
+ if (isUsableGroupMetadata(groupData)) {
585
+ logger.trace({ jid, participants: groupData.participants.length, addressingMode: groupData.addressingMode }, 'using cached group metadata');
586
+ }
587
+ else if (!isStatus) {
588
+ if (groupData) {
589
+ logger.debug({ jid, reason: describeUnusableGroupMetadata(groupData) }, 'cached group metadata is not usable, fetching it so the addressing mode is not guessed');
590
+ }
591
+ groupData = await groupMetadata(jid);
592
+ }
593
+ return groupData;
594
+ })(),
595
+ (async () => {
596
+ if (!participant && !isStatus) {
597
+
598
+ const result = await authState.keys.get('sender-key-memory', [jid]);
599
+ return result[jid] || {};
600
+ }
601
+ return {};
602
+ })()
603
+ ]);
604
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
605
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
606
+ additionalAttributes = {
607
+ ...additionalAttributes,
608
+ expiration: groupData.ephemeralDuration.toString()
609
+ };
610
+ }
611
+ if (isStatus && statusJidList) {
612
+ participantsList.push(...statusJidList);
613
+ }
614
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
615
+ devices.push(...additionalDevices);
616
+ if (isGroup) {
617
+ additionalAttributes = {
618
+ ...additionalAttributes,
619
+ addressing_mode: groupData?.addressingMode || 'lid'
620
+ };
621
+ }
622
+ const patched = await patchMessageBeforeSending(message);
623
+ if (Array.isArray(patched)) {
624
+ throw new Boom('Per-jid patching is not supported in groups');
625
+ }
626
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
627
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
628
+ let toEncode = patched;
629
+ if (config.inlineSenderKeyDistribution !== false && isGroup && !patched.senderKeyDistributionMessage) {
630
+ try {
631
+ if (await signalRepository.hasSenderKey({ group: destinationJid, meId: groupSenderIdentity })) {
632
+ const inlineSkdm = await signalRepository.getSenderKeyDistributionMessage({
633
+ group: destinationJid,
634
+ meId: groupSenderIdentity
635
+ });
636
+ toEncode = {
637
+ ...patched,
638
+ senderKeyDistributionMessage: {
639
+ groupId: destinationJid,
640
+ axolotlSenderKeyDistributionMessage: inlineSkdm
641
+ }
642
+ };
643
+ }
644
+ }
645
+ catch (err) {
646
+ logger.warn({ err, jid: destinationJid }, 'failed to inline the sender key distribution message');
647
+ }
648
+ }
649
+ const bytes = encodeWAMessage(toEncode);
650
+ reportingMessage = toEncode;
651
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
652
+ group: destinationJid,
653
+ data: bytes,
654
+ meId: groupSenderIdentity
655
+ });
656
+ const senderKeyRecipients = pickSenderKeyRecipients(devices, senderKeyMap, {
657
+ force: !!participant,
658
+ skip: device => isHostedLidUser(device.jid) || isHostedPnUser(device.jid) || device.device === 99
659
+ });
660
+ if (senderKeyRecipients.length) {
661
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
662
+ const senderKeyMsg = {
663
+ senderKeyDistributionMessage: {
664
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
665
+ groupId: destinationJid
666
+ }
667
+ };
668
+ const senderKeySessionTargets = senderKeyRecipients;
669
+ await assertSessions(senderKeySessionTargets);
670
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
671
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
672
+ participants.push(...result.nodes);
673
+ const { skipped } = commitSenderKeyDelivery(senderKeyMap, senderKeyRecipients, result.nodes);
674
+ if (skipped.length) {
675
+ logger.warn({ jid, skipped }, 'sender key did not reach every device, leaving them unmarked so the next send retries');
676
+ }
677
+ }
678
+ binaryNodeContent.push({
679
+ tag: 'enc',
680
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
681
+ content: ciphertext
682
+ });
683
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
684
+ }
685
+ else {
686
+
687
+ let ownId = meId;
688
+ if (isLid && meLid) {
689
+ ownId = meLid;
690
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
691
+ }
692
+ else {
693
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
694
+ }
695
+ const { user: ownUser } = jidDecode(ownId);
696
+ if (!participant) {
697
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
698
+ reportingMessage = Array.isArray(patchedForReporting)
699
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
700
+ : patchedForReporting;
701
+ }
702
+ if (!isRetryResend) {
703
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
704
+ devices.push({
705
+ user,
706
+ device: 0,
707
+ jid: jidEncode(user, targetUserServer, 0)
708
+ });
709
+ if (user !== ownUser) {
710
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
711
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
712
+ devices.push({
713
+ user: ownUserForAddressing,
714
+ device: 0,
715
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
716
+ });
717
+ }
718
+ if (additionalAttributes?.['category'] !== 'peer') {
719
+
720
+ devices.length = 0;
721
+
722
+ const senderIdentity = isLid && meLid
723
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
724
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
725
+
726
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
727
+ devices.push(...sessionDevices);
728
+ logger.debug({
729
+ deviceCount: devices.length,
730
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
731
+ }, 'Device enumeration complete with unified addressing');
732
+ }
733
+ }
734
+ const allRecipients = [];
735
+ const meRecipients = [];
736
+ const otherRecipients = [];
737
+ const { user: mePnUser } = jidDecode(meId);
738
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
739
+ for (const { user, jid } of devices) {
740
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
741
+ if (isExactSenderDevice) {
742
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
743
+ continue;
744
+ }
745
+
746
+ const isMe = user === mePnUser || user === meLidUser;
747
+ if (isMe) {
748
+ meRecipients.push(jid);
749
+ }
750
+ else {
751
+ otherRecipients.push(jid);
752
+ }
753
+ allRecipients.push(jid);
754
+ }
755
+ await assertSessions(allRecipients);
756
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
757
+
758
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
759
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
760
+ ]);
761
+ participants.push(...meNodes);
762
+ participants.push(...otherNodes);
763
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
764
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
765
+ }
766
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
767
+ }
768
+ if (isRetryResend) {
769
+ const isParticipantLid = isLidUser(participant.jid);
770
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
771
+ let messageToSend = message;
772
+ if (isGroupOrStatus) {
773
+ let groupSenderIdentity;
774
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
775
+ groupSenderIdentity = meLid;
776
+ }
777
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
778
+ groupSenderIdentity = meId;
779
+ }
780
+ if (groupSenderIdentity) {
781
+ try {
782
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
783
+ group: destinationJid,
784
+ meId: groupSenderIdentity
785
+ });
786
+ messageToSend = {
787
+ ...message,
788
+ senderKeyDistributionMessage: {
789
+ groupId: destinationJid,
790
+ axolotlSenderKeyDistributionMessage: skdm
791
+ }
792
+ };
793
+ }
794
+ catch (err) {
795
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
796
+ }
797
+ }
798
+ }
799
+ const encodedMessageToSend = isMe
800
+ ? encodeWAMessage({
801
+ deviceSentMessage: {
802
+ destinationJid,
803
+ message: messageToSend
804
+ }
805
+ })
806
+ : encodeWAMessage(messageToSend);
807
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
808
+ data: encodedMessageToSend,
809
+ jid: participant.jid
810
+ });
811
+ binaryNodeContent.push({
812
+ tag: 'enc',
813
+ attrs: {
814
+ v: '2',
815
+ type,
816
+ count: (participant.count || 0).toString()
817
+ },
818
+ content: encryptedContent
819
+ });
820
+ }
821
+ if (participants.length) {
822
+ if (additionalAttributes?.['category'] === 'peer') {
823
+ const peerNode = participants[0]?.content?.[0];
824
+ if (peerNode) {
825
+ binaryNodeContent.push(peerNode);
826
+ }
827
+ }
828
+ else {
829
+ binaryNodeContent.push({
830
+ tag: 'participants',
831
+ attrs: {},
832
+ content: participants
833
+ });
834
+ }
835
+ }
836
+ const stanza = {
837
+ tag: 'message',
838
+ attrs: {
839
+ id: msgId,
840
+ to: destinationJid,
841
+ type: getMessageType(innerMessage),
842
+ ...(additionalAttributes || {})
843
+ },
844
+ content: binaryNodeContent
845
+ };
846
+
847
+ if (participant) {
848
+ if (isJidGroup(destinationJid)) {
849
+ stanza.attrs.to = destinationJid;
850
+ stanza.attrs.participant = participant.jid;
851
+ }
852
+ else if (areJidsSameUser(participant.jid, meId)) {
853
+ stanza.attrs.to = participant.jid;
854
+ stanza.attrs.recipient = destinationJid;
855
+ }
856
+ else {
857
+ stanza.attrs.to = participant.jid;
858
+ }
859
+ }
860
+ else {
861
+ stanza.attrs.to = destinationJid;
862
+ }
863
+ if (shouldIncludeDeviceIdentity) {
864
+ ;
865
+ stanza.content.push({
866
+ tag: 'device-identity',
867
+ attrs: {},
868
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
869
+ });
870
+ logger.debug({ jid }, 'adding device identity');
871
+ }
872
+ if (!isNewsletter &&
873
+ !isRetryResend &&
874
+ reportingMessage?.messageContextInfo?.messageSecret &&
875
+ shouldIncludeReportingToken(reportingMessage)) {
876
+ try {
877
+ const encoded = proto.Message.encode(reportingMessage).finish();
878
+ const reportingKey = {
879
+ id: msgId,
880
+ fromMe: true,
881
+ remoteJid: destinationJid,
882
+ participant: participant?.jid
883
+ };
884
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
885
+ if (reportingNode) {
886
+ ;
887
+ stanza.content.push(reportingNode);
888
+ logger.trace({ jid }, 'added reporting token to message');
889
+ }
890
+ }
891
+ catch (error) {
892
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
893
+ }
894
+ }
895
+
896
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
897
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
898
+
899
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
900
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
901
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
902
+ let tcTokenBuffer = existingTokenEntry?.token;
903
+
904
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
905
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
906
+ tcTokenBuffer = undefined;
907
+
908
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
909
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
910
+ : null;
911
+ try {
912
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
913
+ }
914
+ catch (err) {
915
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
916
+ }
917
+ }
918
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
919
+ ;
920
+ stanza.content.push({
921
+ tag: 'tctoken',
922
+ attrs: {},
923
+ content: tcTokenBuffer
924
+ });
925
+ }
926
+ let alreadyHasBizNode = false;
927
+ if (additionalNodes && additionalNodes.length > 0) {
928
+ ;
929
+ stanza.content.push(...additionalNodes);
930
+ alreadyHasBizNode = !addBizAttributes &&
931
+ additionalNodes.some(node => node.tag === 'biz');
932
+ }
933
+
934
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
935
+ const bizNode = getBizBinaryNode(innerMessage);
936
+ stanza.content.push(bizNode);
937
+ }
938
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
939
+ await sendNode(stanza);
940
+
941
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
942
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
943
+ if (is1on1Send &&
944
+ !isProtocolMsg &&
945
+ !isBotOrPSA &&
946
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
947
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
948
+ inFlightTcTokenIssuance.add(tcTokenJid);
949
+ const issueTimestamp = unixTimestampSeconds();
950
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
951
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
952
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
953
+ .then(async (result) => {
954
+ await storeTcTokensFromIqResult({
955
+ result,
956
+ fallbackJid: tcTokenJid,
957
+ keys: authState.keys,
958
+ getLIDForPN
959
+ });
960
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
961
+ const currentEntry = currentData[tcTokenJid];
962
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
963
+ await authState.keys.set({
964
+ tctoken: {
965
+ [tcTokenJid]: {
966
+ token: Buffer.alloc(0),
967
+ ...currentEntry,
968
+ senderTimestamp: issueTimestamp
969
+ },
970
+ ...indexWrite
971
+ }
972
+ });
973
+ })
974
+ .catch(err => {
975
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
976
+ })
977
+ .finally(() => {
978
+ inFlightTcTokenIssuance.delete(tcTokenJid);
979
+ });
980
+ }
981
+
982
+ if (messageRetryManager && !participant) {
983
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
984
+ }
985
+ }, meId);
986
+ return msgId;
987
+ };
988
+ const getMessageType = (message) => {
989
+ if (!message)
990
+ return 'text';
991
+ if (message.reactionMessage || message.encReactionMessage) {
992
+ return 'reaction';
993
+ }
994
+ if (message.pollCreationMessage ||
995
+ message.pollCreationMessageV2 ||
996
+ message.pollCreationMessageV3 ||
997
+ message.pollCreationMessageV5 ||
998
+ message.pollCreationMessageV6 ||
999
+ message.pollResultSnapshotMessage ||
1000
+ message.pollResultSnapshotMessageV3 ||
1001
+ message.pollUpdateMessage) {
1002
+ return 'poll';
1003
+ }
1004
+ if (message.eventMessage) {
1005
+ return 'event';
1006
+ }
1007
+ if (getMediaType(message) !== '') {
1008
+ return 'media';
1009
+ }
1010
+ return 'text';
1011
+ };
1012
+ const getMediaType = (message) => {
1013
+ if (message.imageMessage) {
1014
+ return 'image';
1015
+ }
1016
+ else if (message.videoMessage) {
1017
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1018
+ }
1019
+ else if (message.stickerMessage) {
1020
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1021
+ }
1022
+ else if (message.audioMessage) {
1023
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1024
+ }
1025
+ else if (message.albumMessage) {
1026
+ return 'collection';
1027
+ }
1028
+ else if (message.contactMessage) {
1029
+ return 'vcard';
1030
+ }
1031
+ else if (message.documentMessage) {
1032
+ return 'document';
1033
+ }
1034
+ else if (message.contactsArrayMessage) {
1035
+ return 'contact_array';
1036
+ }
1037
+ else if (message.liveLocationMessage) {
1038
+ return 'livelocation';
1039
+ }
1040
+ else if (message.stickerPackMessage) {
1041
+ return 'sticker_pack';
1042
+ }
1043
+ else if (message.listMessage) {
1044
+ return 'list';
1045
+ }
1046
+ else if (message.listResponseMessage) {
1047
+ return 'list_response';
1048
+ }
1049
+ else if (message.buttonsResponseMessage) {
1050
+ return 'buttons_response';
1051
+ }
1052
+ else if (message.orderMessage) {
1053
+ return 'order';
1054
+ }
1055
+ else if (message.productMessage) {
1056
+ return 'product';
1057
+ }
1058
+ else if (message.interactiveResponseMessage) {
1059
+ return 'native_flow_response';
1060
+ }
1061
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1062
+ return 'url';
1063
+ }
1064
+
1065
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1066
+ return 'cataloglink';
1067
+ }
1068
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1069
+ return 'productlink';
1070
+ }
1071
+ return '';
1072
+ };
1073
+ const issuePrivacyTokens = async (jids, timestamp) => {
1074
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1075
+ const result = await query({
1076
+ tag: 'iq',
1077
+ attrs: {
1078
+ to: S_WHATSAPP_NET,
1079
+ type: 'set',
1080
+ xmlns: 'privacy'
1081
+ },
1082
+ content: [
1083
+ {
1084
+ tag: 'tokens',
1085
+ attrs: {},
1086
+ content: jids.map(jid => ({
1087
+ tag: 'token',
1088
+ attrs: {
1089
+ jid: jidNormalizedUser(jid),
1090
+ t,
1091
+ type: 'trusted_contact'
1092
+ }
1093
+ }))
1094
+ }
1095
+ ]
1096
+ });
1097
+ return result;
1098
+ };
1099
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1100
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1101
+ registerSocketEndHandler(() => {
1102
+ if (!config.userDevicesCache && userDevicesCache.close) {
1103
+ userDevicesCache.close();
1104
+ }
1105
+ mediaConn = undefined;
1106
+ if (messageRetryManager) {
1107
+ messageRetryManager.clear();
1108
+ }
1109
+ });
1110
+ const sendHD = async (jid, content, options = {}) => {
1111
+ const userJid = authState.creds.me.id;
1112
+ const isVideo = !!content.video;
1113
+ const media = isVideo ? content.video : content.image;
1114
+ if (!media) {
1115
+ throw new Boom('sendHD needs { image } or { video }', { statusCode: 400 });
1116
+ }
1117
+ const hdSource = (content.hd && content.hd !== true) ? content.hd : media;
1118
+ const parentContent = { ...content };
1119
+ delete parentContent.hd;
1120
+ const mediaKey = isVideo ? 'videoMessage' : 'imageMessage';
1121
+ const parentPaired = isVideo ? proto.ContextInfo.PairedMediaType.SD_VIDEO_PARENT : proto.ContextInfo.PairedMediaType.SD_IMAGE_PARENT;
1122
+ const childPaired = isVideo ? proto.ContextInfo.PairedMediaType.HD_VIDEO_CHILD : proto.ContextInfo.PairedMediaType.HD_IMAGE_CHILD;
1123
+ const association = isVideo ? AssociationType.HD_VIDEO_DUAL_UPLOAD : AssociationType.HD_IMAGE_DUAL_UPLOAD;
1124
+ const genOpts = {
1125
+ logger,
1126
+ userJid,
1127
+ upload: waUploadToServer,
1128
+ mediaCache: config.mediaCache,
1129
+ options: config.options,
1130
+ ...options
1131
+ };
1132
+ const relayOpts = {
1133
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1134
+ statusJidList: options.statusJidList,
1135
+ additionalAttributes: options.additionalAttributes,
1136
+ additionalNodes: options.additionalNodes
1137
+ };
1138
+ const emit = message => {
1139
+ if (config.emitOwnEvents) {
1140
+ process.nextTick(() => { messageMutex.mutex(() => upsertMessage(message, 'append')); });
1141
+ }
1142
+ };
1143
+ const parent = await generateWAMessage(jid, parentContent, { ...genOpts, messageId: generateMessageIDV2(userJid) });
1144
+ parent.message[mediaKey].contextInfo = { ...(parent.message[mediaKey].contextInfo || {}), pairedMediaType: parentPaired };
1145
+ await relayMessage(jid, parent.message, { messageId: parent.key.id, ...relayOpts });
1146
+ emit(parent);
1147
+ const child = await generateWAMessage(jid, isVideo ? { video: hdSource } : { image: hdSource }, { ...genOpts, messageId: generateMessageIDV2(userJid) });
1148
+ child.message[mediaKey].contextInfo = { ...(child.message[mediaKey].contextInfo || {}), pairedMediaType: childPaired };
1149
+ child.message.messageContextInfo = { ...(child.message.messageContextInfo || {}), messageAssociation: { parentMessageKey: parent.key, associationType: association } };
1150
+ await relayMessage(jid, child.message, { messageId: child.key.id, ...relayOpts });
1151
+ emit(child);
1152
+ return parent;
1153
+ };
1154
+ const sendImgVid = async (jid, content, options = {}) => {
1155
+ const userJid = authState.creds.me.id;
1156
+ const { image, video, caption } = content;
1157
+ if (!image || !video) {
1158
+ throw new Boom('sendImgVid needs { image, video }', { statusCode: 400 });
1159
+ }
1160
+ const genOpts = {
1161
+ logger,
1162
+ userJid,
1163
+ upload: waUploadToServer,
1164
+ mediaCache: config.mediaCache,
1165
+ options: config.options,
1166
+ ...options
1167
+ };
1168
+ const relayOpts = {
1169
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1170
+ statusJidList: options.statusJidList,
1171
+ additionalAttributes: options.additionalAttributes,
1172
+ additionalNodes: options.additionalNodes
1173
+ };
1174
+ const emit = message => {
1175
+ if (config.emitOwnEvents) {
1176
+ process.nextTick(() => { messageMutex.mutex(() => upsertMessage(message, 'append')); });
1177
+ }
1178
+ };
1179
+ const parent = await generateWAMessage(jid, { image, caption }, { ...genOpts, messageId: generateMessageIDV2(userJid) });
1180
+ await relayMessage(jid, parent.message, { messageId: parent.key.id, ...relayOpts });
1181
+ emit(parent);
1182
+ const child = await generateWAMessage(jid, { video }, { ...genOpts, messageId: generateMessageIDV2(userJid) });
1183
+ child.message.messageContextInfo = { ...(child.message.messageContextInfo || {}), messageAssociation: { associationType: AssociationType.MOTION_PHOTO, parentMessageKey: parent.key } };
1184
+ await relayMessage(jid, child.message, { messageId: child.key.id, ...relayOpts });
1185
+ emit(child);
1186
+ return parent;
1187
+ };
1188
+ return {
1189
+ ...sock,
1190
+ userDevicesCache,
1191
+ devicesMutex,
1192
+ issuePrivacyTokens,
1193
+ assertSessions,
1194
+ relayMessage,
1195
+ sendHD,
1196
+ sendImgVid,
1197
+ outboundResendCache,
1198
+ sendReceipt,
1199
+ sendReceipts,
1200
+ readMessages,
1201
+ refreshMediaConn,
1202
+
1203
+ getMediaHost: () => mediaHost,
1204
+ waUploadToServer,
1205
+ fetchPrivacySettings,
1206
+ sendPeerDataOperationMessage,
1207
+ createParticipantNodes,
1208
+ getUSyncDevices,
1209
+ messageRetryManager,
1210
+ resetGroupSenderKey: async (jid) => {
1211
+ if (!isJidGroup(jid)) {
1212
+ throw new Boom('resetGroupSenderKey needs a group jid', { statusCode: 400 });
1213
+ }
1214
+ const stored = await authState.keys.get('sender-key-memory', [jid]);
1215
+ const summary = senderKeyResetSummary(stored, jid);
1216
+ await authState.keys.set({ 'sender-key-memory': { [jid]: null } });
1217
+ logger.info(summary, 'cleared sender key memory, the next send redistributes the key');
1218
+ return summary;
1219
+ },
1220
+ updateMemberLabel,
1221
+ removeMemberLabel,
1222
+ updateMediaMessage: async (message) => {
1223
+ const content = assertMediaContent(message.message);
1224
+ const mediaKey = content.mediaKey;
1225
+ const meId = authState.creds.me.id;
1226
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1227
+ let error = undefined;
1228
+ await Promise.all([
1229
+ sendNode(node),
1230
+ waitForMsgMediaUpdate(async (update) => {
1231
+ const result = update.find(c => c.key.id === message.key.id);
1232
+ if (result) {
1233
+ if (result.error) {
1234
+ error = result.error;
1235
+ }
1236
+ else {
1237
+ try {
1238
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1239
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1240
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1241
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1242
+ data: media,
1243
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1244
+ });
1245
+ }
1246
+ content.directPath = media.directPath;
1247
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1248
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1249
+ }
1250
+ catch (err) {
1251
+ error = err;
1252
+ }
1253
+ }
1254
+ return true;
1255
+ }
1256
+ })
1257
+ ]);
1258
+ if (error) {
1259
+ throw error;
1260
+ }
1261
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1262
+ return message;
1263
+ },
1264
+
1265
+ sendMessage: async (jid, content, options = {}) => {
1266
+ const userJid = authState.creds.me.id;
1267
+
1268
+ if (content?.hd && (content.image || content.video) && !Array.isArray(jid)) {
1269
+ return sendHD(jid, content, options);
1270
+ }
1271
+
1272
+ if (content?.image && content?.video && !Array.isArray(jid)) {
1273
+ return sendImgVid(jid, content, options);
1274
+ }
1275
+
1276
+ if (Array.isArray(jid)) {
1277
+ const { delayMs = 1500 } = options;
1278
+ const allUsers = new Set();
1279
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1280
+ logger,
1281
+ userJid,
1282
+ upload: waUploadToServer,
1283
+ mediaCache: config.mediaCache,
1284
+ options: config.options,
1285
+ ...options,
1286
+ messageId: generateMessageIDV2(userJid)
1287
+ });
1288
+ for (const id of jid) {
1289
+ if (isJidGroup(id)) {
1290
+ try {
1291
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1292
+ for (const participant of groupData.participants) {
1293
+ if (allUsers.has(participant.id))
1294
+ continue;
1295
+ allUsers.add(participant.id);
1296
+ }
1297
+ }
1298
+ catch (error) {
1299
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1300
+ }
1301
+ }
1302
+ else if (!allUsers.has(id)) {
1303
+ allUsers.add(id);
1304
+ }
1305
+ }
1306
+ await relayMessage('status@broadcast', fullMsg.message, {
1307
+ messageId: fullMsg.key.id,
1308
+ statusJidList: Array.from(allUsers),
1309
+ additionalNodes: [
1310
+ {
1311
+ tag: 'meta',
1312
+ attrs: {},
1313
+ content: [
1314
+ {
1315
+ tag: 'mentioned_users',
1316
+ attrs: {},
1317
+ content: jid.map(id => ({
1318
+ tag: 'to',
1319
+ attrs: { jid: id },
1320
+ content: undefined
1321
+ }))
1322
+ }
1323
+ ]
1324
+ }
1325
+ ]
1326
+ });
1327
+ if (config.emitOwnEvents) {
1328
+ process.nextTick(async () => {
1329
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1330
+ });
1331
+ }
1332
+ for (const id of jid) {
1333
+ const isGroup = isJidGroup(id);
1334
+ const mentionMsg = generateWAMessageFromContent(id, {
1335
+ messageContextInfo: {
1336
+ messageSecret: randomBytes(32)
1337
+ },
1338
+ ...makeStatusMentionMessage({ key: fullMsg.key, group: isGroup })
1339
+ }, {
1340
+ userJid
1341
+ });
1342
+ await relayMessage(id, mentionMsg.message, {
1343
+ additionalNodes: [
1344
+ {
1345
+ tag: 'meta',
1346
+ attrs: isGroup ?
1347
+ { is_group_status_mention: 'true' } :
1348
+ { is_status_mention: 'true' },
1349
+ content: undefined
1350
+ }
1351
+ ]
1352
+ });
1353
+ if (config.emitOwnEvents) {
1354
+ process.nextTick(async () => {
1355
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1356
+ });
1357
+ }
1358
+ await delay(delayMs);
1359
+ }
1360
+ return fullMsg;
1361
+ }
1362
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1363
+ const { disappearingMessagesInChat } = content;
1364
+ const value = typeof disappearingMessagesInChat === 'boolean'
1365
+ ? disappearingMessagesInChat
1366
+ ? WA_DEFAULT_EPHEMERAL
1367
+ : 0
1368
+ : disappearingMessagesInChat;
1369
+ await groupToggleEphemeral(jid, value);
1370
+ }
1371
+ else {
1372
+ const isPollMsg = 'poll' in content && !!content.poll;
1373
+ const isQuizMsg = isPollMsg && !!content.poll.pollType;
1374
+ const isPhotoPollMsg = isPollMsg && Array.isArray(content.poll.values) && content.poll.values.some(value => value && typeof value === 'object' && value.image);
1375
+ const pollOptionImages = [];
1376
+ if (isPhotoPollMsg) {
1377
+ const preparedValues = [];
1378
+ for (const value of content.poll.values) {
1379
+ if (typeof value === 'string' || !value?.image) {
1380
+ preparedValues.push(value);
1381
+ continue;
1382
+ }
1383
+ const prepared = await prepareWAMessageMedia({ image: value.image }, {
1384
+ logger,
1385
+ upload: waUploadToServer,
1386
+ mediaCache: config.mediaCache,
1387
+ options: config.options,
1388
+ jid
1389
+ });
1390
+ preparedValues.push({
1391
+ name: value.name,
1392
+ optionHash: getPollOptionHash(value.name, prepared.imageMessage?.fileSha256)
1393
+ });
1394
+ pollOptionImages.push({ content: prepared });
1395
+ }
1396
+ content = { ...content, poll: { ...content.poll, values: preparedValues } };
1397
+ }
1398
+ const fullMsg = await generateWAMessage(jid, content, {
1399
+ logger,
1400
+ userJid,
1401
+ getUrlInfo: text => getUrlInfo(text, {
1402
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1403
+ fetchOpts: {
1404
+ timeout: 3000,
1405
+ ...(httpRequestOptions || {})
1406
+ },
1407
+ logger,
1408
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1409
+ }),
1410
+
1411
+ getProfilePicUrl: sock.profilePictureUrl,
1412
+ getCallLink: sock.createCallLink,
1413
+ upload: waUploadToServer,
1414
+ mediaCache: config.mediaCache,
1415
+ options: config.options,
1416
+ ...options,
1417
+ messageId: generateMessageIDV2(userJid)
1418
+ });
1419
+ const isNewsletter = isJidNewsletter(jid);
1420
+ const isEventMsg = 'event' in content && !!content.event;
1421
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1422
+ const isEditMsg = 'edit' in content && !!content.edit;
1423
+ const isPinMsg = 'pin' in content && !!content.pin;
1424
+ const isKeepMsg = 'keep' in content && !!content.keep;
1425
+ const isPollResultMsg = 'pollResult' in content && !!content.pollResult;
1426
+ const isAiMsg = 'ai' in content && !!content.ai;
1427
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1428
+ const additionalAttributes = options.additionalAttributes || {};
1429
+ const additionalNodes = options.additionalNodes || [];
1430
+
1431
+ if (isDeleteMsg || isKeepMsg) {
1432
+
1433
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1434
+ additionalAttributes.edit = '8';
1435
+ }
1436
+ else {
1437
+ additionalAttributes.edit = '7';
1438
+ }
1439
+ }
1440
+ else if (isEditMsg) {
1441
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1442
+ }
1443
+ else if (isPinMsg) {
1444
+ additionalAttributes.edit = '2';
1445
+ }
1446
+ else if (isPollMsg) {
1447
+ if (!isNewsletter && isQuizMsg) {
1448
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1449
+ }
1450
+ additionalNodes.push({
1451
+ tag: 'meta',
1452
+ attrs: {
1453
+
1454
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1455
+ contenttype: isPhotoPollMsg ? 'image' : isPollMsg && isNewsletter ? 'text' : undefined
1456
+ },
1457
+ content: undefined
1458
+ });
1459
+ }
1460
+ else if (isPollResultMsg) {
1461
+ additionalNodes.push({
1462
+ tag: 'meta',
1463
+ attrs: {
1464
+ polltype: 'result_snapshot'
1465
+ },
1466
+ content: undefined
1467
+ });
1468
+ }
1469
+ else if (isEventMsg) {
1470
+ additionalNodes.push({
1471
+ tag: 'meta',
1472
+ attrs: {
1473
+ event_type: 'creation'
1474
+ },
1475
+ content: undefined
1476
+ });
1477
+ }
1478
+
1479
+ else if (isAiMsg) {
1480
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1481
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1482
+ }
1483
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1484
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1485
+ }
1486
+ ;
1487
+ additionalNodes.push({
1488
+ tag: 'bot',
1489
+ attrs: {
1490
+ biz_bot: '1'
1491
+ },
1492
+ content: undefined
1493
+ });
1494
+ delete content.ai;
1495
+ }
1496
+ await relayMessage(jid, fullMsg.message, {
1497
+ messageId: fullMsg.key.id,
1498
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1499
+ addBizAttributes: isNeedBizAttrs,
1500
+ statusJidList: options.statusJidList,
1501
+ additionalAttributes,
1502
+ additionalNodes
1503
+ });
1504
+ if (config.emitOwnEvents) {
1505
+ process.nextTick(async () => {
1506
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1507
+ });
1508
+ }
1509
+ if (pollOptionImages.length) {
1510
+ for (const optionImage of pollOptionImages) {
1511
+ const optionMsg = generateWAMessageFromContent(jid, {
1512
+ pollCreationOptionImageMessage: { message: optionImage.content },
1513
+ messageContextInfo: {
1514
+ messageAssociation: {
1515
+ parentMessageKey: fullMsg.key,
1516
+ associationType: AssociationType.MEDIA_POLL
1517
+ }
1518
+ }
1519
+ }, { userJid, messageId: generateMessageIDV2(userJid) });
1520
+ await relayMessage(jid, optionMsg.message, {
1521
+ messageId: optionMsg.key.id,
1522
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1523
+ statusJidList: options.statusJidList,
1524
+ additionalAttributes,
1525
+ additionalNodes: [{
1526
+ tag: 'meta',
1527
+ attrs: { message_association_type: 'media_poll' },
1528
+ content: undefined
1529
+ }]
1530
+ });
1531
+ }
1532
+ }
1533
+ if ('album' in content) {
1534
+ const { delayMs = 1500 } = options;
1535
+ await delay(delayMs);
1536
+ for (const albumMedia of content.album) {
1537
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1538
+ logger,
1539
+ userJid,
1540
+ upload: waUploadToServer,
1541
+ mediaCache: config.mediaCache,
1542
+ options: config.options,
1543
+ ...options,
1544
+ messageId: generateMessageIDV2(userJid)
1545
+ });
1546
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1547
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
1548
+ }
1549
+ albumMsg.message.messageContextInfo ||= {};
1550
+ albumMsg.message.messageContextInfo.messageAssociation = {
1551
+ parentMessageKey: fullMsg.key,
1552
+ associationType: AssociationType.MEDIA_ALBUM
1553
+ };
1554
+ await relayMessage(jid, albumMsg.message, {
1555
+ messageId: albumMsg.key.id,
1556
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1557
+ addBizAttributes: isNeedBizAttrs,
1558
+ statusJidList: options.statusJidList,
1559
+ additionalAttributes,
1560
+ additionalNodes
1561
+ });
1562
+ if (config.emitOwnEvents) {
1563
+ process.nextTick(async () => {
1564
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1565
+ });
1566
+ }
1567
+ await delay(delayMs);
1568
+ }
1569
+ }
1570
+ return fullMsg;
1571
+ }
1572
+ }
1573
+ };
1574
+ };