ruby-baileys 0.0.0-stage → 1.5.17

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