@fer2809fl/baileys 7.0.0 → 7.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/README.md +259 -595
  2. package/WAProto/WAProto.proto +916 -360
  3. package/WAProto/fix-imports.js +18 -22
  4. package/WAProto/index.d.ts +15471 -8638
  5. package/WAProto/index.js +80576 -45941
  6. package/lib/Defaults/index.d.ts +14 -18
  7. package/lib/Defaults/index.d.ts.map +1 -1
  8. package/lib/Defaults/index.js +110 -115
  9. package/lib/Defaults/index.js.map +1 -1
  10. package/lib/Signal/Group/group_cipher.js.map +1 -1
  11. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  12. package/lib/Signal/Group/keyhelper.js.map +1 -1
  13. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  14. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  15. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  16. package/lib/Signal/libsignal.d.ts.map +1 -1
  17. package/lib/Signal/libsignal.js +17 -45
  18. package/lib/Signal/libsignal.js.map +1 -1
  19. package/lib/Signal/lid-mapping.d.ts +0 -4
  20. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  21. package/lib/Signal/lid-mapping.js +0 -6
  22. package/lib/Signal/lid-mapping.js.map +1 -1
  23. package/lib/Socket/business.d.ts +532 -280
  24. package/lib/Socket/business.d.ts.map +1 -1
  25. package/lib/Socket/business.js +401 -358
  26. package/lib/Socket/chats.d.ts +2 -22
  27. package/lib/Socket/chats.d.ts.map +1 -1
  28. package/lib/Socket/chats.js +43 -314
  29. package/lib/Socket/chats.js.map +1 -1
  30. package/lib/Socket/communities.d.ts +641 -336
  31. package/lib/Socket/communities.d.ts.map +1 -1
  32. package/lib/Socket/communities.js +3 -6
  33. package/lib/Socket/communities.js.map +1 -1
  34. package/lib/Socket/dugong.d.ts +130 -0
  35. package/lib/Socket/dugong.d.ts.map +1 -0
  36. package/lib/Socket/dugong.js +772 -0
  37. package/lib/Socket/dugong.js.map +1 -0
  38. package/lib/Socket/groups.d.ts +2 -23
  39. package/lib/Socket/groups.d.ts.map +1 -1
  40. package/lib/Socket/groups.js +8 -171
  41. package/lib/Socket/groups.js.map +1 -1
  42. package/lib/Socket/index.d.ts +631 -322
  43. package/lib/Socket/index.d.ts.map +1 -1
  44. package/lib/Socket/index.js +12 -9
  45. package/lib/Socket/index.js.map +1 -1
  46. package/lib/Socket/messages-recv.d.ts +52 -84
  47. package/lib/Socket/messages-recv.d.ts.map +1 -1
  48. package/lib/Socket/messages-recv.js +185 -686
  49. package/lib/Socket/messages-recv.js.map +1 -1
  50. package/lib/Socket/messages-send.d.ts +643 -262
  51. package/lib/Socket/messages-send.d.ts.map +1 -1
  52. package/lib/Socket/messages-send.js +1559 -1359
  53. package/lib/Socket/messages-send.js.map +1 -1
  54. package/lib/Socket/mex.d.ts +0 -1
  55. package/lib/Socket/mex.d.ts.map +1 -1
  56. package/lib/Socket/mex.js +8 -22
  57. package/lib/Socket/mex.js.map +1 -1
  58. package/lib/Socket/native-buttons.js +231 -0
  59. package/lib/Socket/newsletter.d.ts +27 -42
  60. package/lib/Socket/newsletter.d.ts.map +1 -1
  61. package/lib/Socket/newsletter.js +439 -402
  62. package/lib/Socket/newsletter.js.map +1 -1
  63. package/lib/Socket/socket.d.ts +2 -6
  64. package/lib/Socket/socket.d.ts.map +1 -1
  65. package/lib/Socket/socket.js +26 -62
  66. package/lib/Socket/socket.js.map +1 -1
  67. package/lib/Types/Auth.d.ts +0 -1
  68. package/lib/Types/Auth.d.ts.map +1 -1
  69. package/lib/Types/Bussines.d.ts +34 -22
  70. package/lib/Types/Call.d.ts +1 -1
  71. package/lib/Types/Call.d.ts.map +1 -1
  72. package/lib/Types/Chat.d.ts +0 -1
  73. package/lib/Types/Chat.d.ts.map +1 -1
  74. package/lib/Types/Contact.d.ts +0 -2
  75. package/lib/Types/Contact.d.ts.map +1 -1
  76. package/lib/Types/Events.d.ts +1 -20
  77. package/lib/Types/Events.d.ts.map +1 -1
  78. package/lib/Types/GroupMetadata.d.ts +1 -4
  79. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  80. package/lib/Types/Message.d.ts +348 -354
  81. package/lib/Types/Message.d.ts.map +1 -1
  82. package/lib/Types/Message.js +0 -4
  83. package/lib/Types/Message.js.map +1 -1
  84. package/lib/Types/{Mex.d.ts → Newsletter.d.ts} +7 -26
  85. package/lib/Types/Newsletter.d.ts.map +1 -0
  86. package/lib/Types/{Mex.js → Newsletter.js} +3 -11
  87. package/lib/Types/Newsletter.js.map +1 -0
  88. package/lib/Types/Signal.d.ts +1 -12
  89. package/lib/Types/Signal.d.ts.map +1 -1
  90. package/lib/Types/Socket.d.ts +148 -135
  91. package/lib/Types/Socket.d.ts.map +1 -1
  92. package/lib/Types/Socket.js.map +1 -1
  93. package/lib/Types/State.d.ts +0 -65
  94. package/lib/Types/State.d.ts.map +1 -1
  95. package/lib/Types/State.js +0 -43
  96. package/lib/Types/State.js.map +1 -1
  97. package/lib/Types/index.d.ts +52 -52
  98. package/lib/Types/index.d.ts.map +1 -1
  99. package/lib/Types/index.js +30 -23
  100. package/lib/Types/index.js.map +1 -1
  101. package/lib/Utils/auth-utils.d.ts +0 -5
  102. package/lib/Utils/auth-utils.d.ts.map +1 -1
  103. package/lib/Utils/auth-utils.js +0 -12
  104. package/lib/Utils/auth-utils.js.map +1 -1
  105. package/lib/Utils/browser-utils.d.ts.map +1 -1
  106. package/lib/Utils/browser-utils.js +0 -1
  107. package/lib/Utils/browser-utils.js.map +1 -1
  108. package/lib/Utils/chat-utils.d.ts +4 -34
  109. package/lib/Utils/chat-utils.d.ts.map +1 -1
  110. package/lib/Utils/chat-utils.js +20 -80
  111. package/lib/Utils/chat-utils.js.map +1 -1
  112. package/lib/Utils/crypto.d.ts +12 -12
  113. package/lib/Utils/crypto.d.ts.map +1 -1
  114. package/lib/Utils/crypto.js.map +1 -1
  115. package/lib/Utils/decode-wa-message.d.ts +0 -18
  116. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  117. package/lib/Utils/decode-wa-message.js +0 -34
  118. package/lib/Utils/decode-wa-message.js.map +1 -1
  119. package/lib/Utils/event-buffer.d.ts +0 -2
  120. package/lib/Utils/event-buffer.d.ts.map +1 -1
  121. package/lib/Utils/event-buffer.js +1 -49
  122. package/lib/Utils/event-buffer.js.map +1 -1
  123. package/lib/Utils/generics.d.ts +2 -3
  124. package/lib/Utils/generics.d.ts.map +1 -1
  125. package/lib/Utils/generics.js +1 -10
  126. package/lib/Utils/generics.js.map +1 -1
  127. package/lib/Utils/history.d.ts +0 -2
  128. package/lib/Utils/history.d.ts.map +1 -1
  129. package/lib/Utils/history.js +9 -12
  130. package/lib/Utils/history.js.map +1 -1
  131. package/lib/Utils/identity-change-handler.d.ts +0 -7
  132. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  133. package/lib/Utils/identity-change-handler.js +0 -1
  134. package/lib/Utils/identity-change-handler.js.map +1 -1
  135. package/lib/Utils/index.d.ts +23 -30
  136. package/lib/Utils/index.d.ts.map +1 -1
  137. package/lib/Utils/index.js +2 -9
  138. package/lib/Utils/index.js.map +1 -1
  139. package/lib/Utils/link-preview.js +2 -2
  140. package/lib/Utils/link-preview.js.map +1 -1
  141. package/lib/Utils/message-retry-manager.d.ts +0 -5
  142. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  143. package/lib/Utils/message-retry-manager.js +0 -40
  144. package/lib/Utils/message-retry-manager.js.map +1 -1
  145. package/lib/Utils/messages-media.d.ts +13 -45
  146. package/lib/Utils/messages-media.d.ts.map +1 -1
  147. package/lib/Utils/messages-media.js +98 -293
  148. package/lib/Utils/messages-media.js.map +1 -1
  149. package/lib/Utils/messages.d.ts +3 -16
  150. package/lib/Utils/messages.d.ts.map +1 -1
  151. package/lib/Utils/messages.js +1123 -1219
  152. package/lib/Utils/messages.js.map +1 -1
  153. package/lib/Utils/noise-handler.d.ts +1 -1
  154. package/lib/Utils/process-message.d.ts.map +1 -1
  155. package/lib/Utils/process-message.js +1 -103
  156. package/lib/Utils/process-message.js.map +1 -1
  157. package/lib/Utils/rich-messages.d.ts +277 -0
  158. package/lib/Utils/rich-messages.d.ts.map +1 -0
  159. package/lib/Utils/rich-messages.js +1144 -0
  160. package/lib/Utils/rich-messages.js.map +1 -0
  161. package/lib/Utils/signal.d.ts +0 -13
  162. package/lib/Utils/signal.d.ts.map +1 -1
  163. package/lib/Utils/signal.js +0 -42
  164. package/lib/Utils/signal.js.map +1 -1
  165. package/lib/Utils/sticker-pack.d.ts +10 -0
  166. package/lib/Utils/sticker-pack.js +111 -0
  167. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  168. package/lib/Utils/sync-action-utils.js +0 -1
  169. package/lib/Utils/sync-action-utils.js.map +1 -1
  170. package/lib/Utils/tc-token-utils.d.ts +1 -26
  171. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  172. package/lib/Utils/tc-token-utils.js +5 -151
  173. package/lib/Utils/tc-token-utils.js.map +1 -1
  174. package/lib/Utils/validate-connection.d.ts +0 -1
  175. package/lib/Utils/validate-connection.d.ts.map +1 -1
  176. package/lib/Utils/validate-connection.js +3 -13
  177. package/lib/Utils/validate-connection.js.map +1 -1
  178. package/lib/WABinary/decode.d.ts +1 -1
  179. package/lib/WABinary/decode.d.ts.map +1 -1
  180. package/lib/WABinary/generic-utils.d.ts +3 -1
  181. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  182. package/lib/WABinary/generic-utils.js +78 -0
  183. package/lib/WABinary/generic-utils.js.map +1 -1
  184. package/lib/WABinary/jid-utils.d.ts +0 -11
  185. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  186. package/lib/WABinary/jid-utils.js +0 -33
  187. package/lib/WABinary/jid-utils.js.map +1 -1
  188. package/lib/WAM/encode.d.ts +1 -1
  189. package/lib/WAM/encode.d.ts.map +1 -1
  190. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  191. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  192. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  193. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  194. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  195. package/lib/WAUSync/Protocols/index.js +0 -1
  196. package/lib/WAUSync/Protocols/index.js.map +1 -1
  197. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  198. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  199. package/lib/WAUSync/USyncQuery.js +2 -6
  200. package/lib/WAUSync/USyncQuery.js.map +1 -1
  201. package/lib/WAUSync/USyncUser.d.ts +0 -4
  202. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  203. package/lib/WAUSync/USyncUser.js +0 -8
  204. package/lib/WAUSync/USyncUser.js.map +1 -1
  205. package/lib/index.d.ts +1 -1
  206. package/lib/index.d.ts.map +1 -1
  207. package/lib/index.js +1 -4
  208. package/lib/index.js.map +1 -1
  209. package/package.json +30 -34
  210. package/LICENSE +0 -21
  211. package/engine-requirements.js +0 -10
  212. package/lib/Socket/smgss.d.ts +0 -119
  213. package/lib/Socket/smgss.d.ts.map +0 -1
  214. package/lib/Socket/smgss.js +0 -453
  215. package/lib/Socket/smgss.js.map +0 -1
  216. package/lib/Store/index.d.ts +0 -4
  217. package/lib/Store/index.d.ts.map +0 -1
  218. package/lib/Store/index.js +0 -4
  219. package/lib/Store/index.js.map +0 -1
  220. package/lib/Store/make-in-memory-store.d.ts +0 -132
  221. package/lib/Store/make-in-memory-store.d.ts.map +0 -1
  222. package/lib/Store/make-in-memory-store.js +0 -450
  223. package/lib/Store/make-in-memory-store.js.map +0 -1
  224. package/lib/Store/make-ordered-dictionary.d.ts +0 -14
  225. package/lib/Store/make-ordered-dictionary.d.ts.map +0 -1
  226. package/lib/Store/make-ordered-dictionary.js +0 -80
  227. package/lib/Store/make-ordered-dictionary.js.map +0 -1
  228. package/lib/Store/object-repository.d.ts +0 -13
  229. package/lib/Store/object-repository.d.ts.map +0 -1
  230. package/lib/Store/object-repository.js +0 -24
  231. package/lib/Store/object-repository.js.map +0 -1
  232. package/lib/Types/Mex.d.ts.map +0 -1
  233. package/lib/Types/Mex.js.map +0 -1
  234. package/lib/Utils/button-handler.d.ts +0 -28
  235. package/lib/Utils/button-handler.d.ts.map +0 -1
  236. package/lib/Utils/button-handler.js +0 -140
  237. package/lib/Utils/button-handler.js.map +0 -1
  238. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  239. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  240. package/lib/Utils/companion-reg-client-utils.js +0 -35
  241. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  242. package/lib/Utils/interactive.d.ts +0 -60
  243. package/lib/Utils/interactive.d.ts.map +0 -1
  244. package/lib/Utils/interactive.js +0 -224
  245. package/lib/Utils/interactive.js.map +0 -1
  246. package/lib/Utils/message-composer.d.ts +0 -93
  247. package/lib/Utils/message-composer.d.ts.map +0 -1
  248. package/lib/Utils/message-composer.js +0 -311
  249. package/lib/Utils/message-composer.js.map +0 -1
  250. package/lib/Utils/messages-newsletter.d.ts +0 -74
  251. package/lib/Utils/messages-newsletter.d.ts.map +0 -1
  252. package/lib/Utils/messages-newsletter.js +0 -128
  253. package/lib/Utils/messages-newsletter.js.map +0 -1
  254. package/lib/Utils/shortcake-crypto.d.ts +0 -36
  255. package/lib/Utils/shortcake-crypto.d.ts.map +0 -1
  256. package/lib/Utils/shortcake-crypto.js +0 -71
  257. package/lib/Utils/shortcake-crypto.js.map +0 -1
  258. package/lib/Utils/shortcake.d.ts +0 -36
  259. package/lib/Utils/shortcake.d.ts.map +0 -1
  260. package/lib/Utils/shortcake.js +0 -162
  261. package/lib/Utils/shortcake.js.map +0 -1
  262. package/lib/Utils/use-single-file-auth-state.d.ts +0 -6
  263. package/lib/Utils/use-single-file-auth-state.d.ts.map +0 -1
  264. package/lib/Utils/use-single-file-auth-state.js +0 -111
  265. package/lib/Utils/use-single-file-auth-state.js.map +0 -1
  266. package/lib/Utils/use-sqlite-auth-state.d.ts +0 -14
  267. package/lib/Utils/use-sqlite-auth-state.d.ts.map +0 -1
  268. package/lib/Utils/use-sqlite-auth-state.js +0 -107
  269. package/lib/Utils/use-sqlite-auth-state.js.map +0 -1
  270. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  271. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  272. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  273. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
@@ -1,1413 +1,1613 @@
1
- import NodeCache from '@cacheable/node-cache';
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, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, compressMedia, convertMedia, captureUnifiedResponse, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateCodeBlockContent, generateLatexContent, generateListContent, generateMessageIDV2, generateParticipantHashV2, generateRichMessageContent, generateTableContent, generateUnifiedResponseContent, generateWAMessage, generateWAMessageFromContent, getMediaMetadata, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, imageToWebpSticker, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, resizeImage, unixTimestampSeconds } from '../Utils/index.js';
7
- import { getUrlInfo } from '../Utils/link-preview.js';
8
- import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
9
- import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
10
- import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
11
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, STORIES_JID } from '../WABinary/index.js';
12
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
- import { makeNewsletterSocket } from './newsletter.js';
14
- import { Smgss } from './smgss.js';
1
+ import NodeCache from "@cacheable/node-cache";
2
+ import { Boom } from "@hapi/boom";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from "../Defaults/index.js";
5
+ import {
6
+ aggregateMessageKeysNotFromMe,
7
+ assertMediaContent,
8
+ bindWaitForEvent,
9
+ decryptMediaRetryData,
10
+ encodeNewsletterMessage,
11
+ encodeSignedDeviceIdentity,
12
+ encodeWAMessage,
13
+ encryptMediaRetryRequest,
14
+ extractDeviceJids,
15
+ generateMessageIDV2,
16
+ generateParticipantHashV2,
17
+ generateWAMessage,
18
+ generateWAMessageFromContent,
19
+ getStatusCodeForMediaRetry,
20
+ getUrlFromDirectPath,
21
+ getWAUploadToServer,
22
+ MessageRetryManager,
23
+ normalizeMessageContent,
24
+ prepareWAMessageMedia,
25
+ parseAndInjectE2ESessions,
26
+ unixTimestampSeconds,
27
+ } from "../Utils/index.js";
28
+ import {
29
+ generateTableContent,
30
+ generateTableContentV2,
31
+ generateListContent,
32
+ generateCodeBlockContent,
33
+ generateCodeBlockContentV2,
34
+ generateLinkContent,
35
+ generateLinkContentV2,
36
+ generateRichMessageContent,
37
+ generateLatexContent,
38
+ generateLatexImageContent,
39
+ generateLatexInlineImageContent,
40
+ generateUnifiedResponseContent,
41
+ captureUnifiedResponse,
42
+ } from "../Utils/rich-messages.js";
43
+ import { getUrlInfo } from "../Utils/link-preview.js";
44
+ import { makeKeyedMutex } from "../Utils/make-mutex.js";
45
+ import {
46
+ getMessageReportingToken,
47
+ shouldIncludeReportingToken,
48
+ } from "../Utils/reporting-utils.js";
49
+ import {
50
+ areJidsSameUser,
51
+ getAdditionalNode,
52
+ getBinaryNodeChild,
53
+ getBinaryNodeChildren,
54
+ isHostedLidUser,
55
+ isHostedPnUser,
56
+ isJidGroup,
57
+ isJidNewsletter,
58
+ isLidUser,
59
+ isPnUser,
60
+ jidDecode,
61
+ jidEncode,
62
+ jidNormalizedUser,
63
+ S_WHATSAPP_NET,
64
+ } from "../WABinary/index.js";
65
+ import { USyncQuery, USyncUser } from "../WAUSync/index.js";
66
+ import { Dugong } from "./dugong.js";
67
+ import { makeNativeButtons } from "./native-buttons.js";
68
+ import { makeNewsletterSocket } from "./newsletter.js";
69
+ const NATIVE_FLOW_BUTTON_MAP = {
70
+ review_and_pay: "order_details",
71
+ review_order: "order_status",
72
+ payment_info: "payment_info",
73
+ payment_status: "payment_status",
74
+ payment_method: "payment_method",
75
+ };
76
+ const getButtonType = (message) => {
77
+ const msg = normalizeMessageContent(message) || message;
78
+ if (msg?.buttonsMessage || msg?.listMessage)
79
+ return msg.listMessage ? "list" : "buttons";
80
+ const vm = msg?.viewOnceMessage?.message || msg?.viewOnceMessageV2?.message;
81
+ const im = vm?.interactiveMessage || msg?.interactiveMessage;
82
+ if (!im?.nativeFlowMessage) return null;
83
+ const btnName = im.nativeFlowMessage?.buttons?.[0]?.name;
84
+ if (btnName && NATIVE_FLOW_BUTTON_MAP[btnName])
85
+ return NATIVE_FLOW_BUTTON_MAP[btnName];
86
+ return "interactive";
87
+ };
15
88
  export const makeMessagesSocket = (config) => {
16
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
17
- const sock = makeNewsletterSocket(config);
18
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
19
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
20
- /**
21
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
22
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
23
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
24
- */
25
- const inFlightTcTokenIssuance = new Set();
26
- const userDevicesCache = config.userDevicesCache ||
27
- new NodeCache({
28
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
29
- useClones: false
89
+ const {
90
+ logger,
91
+ linkPreviewImageThumbnailWidth,
92
+ generateHighQualityLinkPreview,
93
+ options: httpRequestOptions,
94
+ patchMessageBeforeSending,
95
+ cachedGroupMetadata,
96
+ enableRecentMessageCache,
97
+ maxMsgRetryCount,
98
+ } = config;
99
+ const sock = makeNewsletterSocket(config);
100
+ const {
101
+ ev,
102
+ authState,
103
+ messageMutex,
104
+ signalRepository,
105
+ upsertMessage,
106
+ query,
107
+ fetchPrivacySettings,
108
+ sendNode,
109
+ groupMetadata,
110
+ groupToggleEphemeral,
111
+ } = sock;
112
+ const userDevicesCache =
113
+ config.userDevicesCache ||
114
+ new NodeCache({
115
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
116
+ useClones: false,
117
+ });
118
+ const peerSessionsCache = new NodeCache({
119
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
120
+ useClones: false,
121
+ });
122
+ // Initialize message retry manager if enabled
123
+ const messageRetryManager = enableRecentMessageCache
124
+ ? new MessageRetryManager(logger, maxMsgRetryCount)
125
+ : null;
126
+ // Prevent race conditions in Signal session encryption by user
127
+ const encryptionMutex = makeKeyedMutex();
128
+ let mediaConn;
129
+ const refreshMediaConn = async (forceGet = false) => {
130
+ const media = await mediaConn;
131
+ if (
132
+ !media ||
133
+ forceGet ||
134
+ new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000
135
+ ) {
136
+ mediaConn = (async () => {
137
+ const result = await query({
138
+ tag: "iq",
139
+ attrs: {
140
+ type: "set",
141
+ xmlns: "w:m",
142
+ to: S_WHATSAPP_NET,
143
+ },
144
+ content: [{ tag: "media_conn", attrs: {} }],
30
145
  });
31
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
32
- const devicesMutex = makeMutex();
33
- // Initialize message retry manager if enabled
34
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
35
- // Prevent race conditions in Signal session encryption by user
36
- const encryptionMutex = makeKeyedMutex();
37
- let mediaConn;
38
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
39
- let mediaHost = DEF_MEDIA_HOST;
40
- const refreshMediaConn = async (forceGet = false) => {
41
- const media = await mediaConn;
42
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
43
- mediaConn = (async () => {
44
- const result = await query({
45
- tag: 'iq',
46
- attrs: {
47
- type: 'set',
48
- xmlns: 'w:m',
49
- to: S_WHATSAPP_NET
50
- },
51
- content: [{ tag: 'media_conn', attrs: {} }]
52
- });
53
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
54
- // TODO: explore full length of data that whatsapp provides
55
- const node = {
56
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
57
- hostname: attrs.hostname,
58
- maxContentLengthBytes: +attrs.maxContentLengthBytes
59
- })),
60
- auth: mediaConnNode.attrs.auth,
61
- ttl: +mediaConnNode.attrs.ttl,
62
- fetchDate: new Date()
63
- };
64
- logger.debug('fetched media conn');
65
- if (node.hosts[0]) {
66
- mediaHost = node.hosts[0].hostname;
67
- }
68
- return node;
69
- })();
70
- }
71
- return mediaConn;
72
- };
73
- /**
74
- * generic send receipt function
75
- * used for receipts of phone call, read, delivery etc.
76
- * */
77
- const sendReceipt = async (jid, participant, messageIds, type) => {
78
- if (!messageIds || messageIds.length === 0) {
79
- throw new Boom('missing ids in receipt');
80
- }
146
+ const mediaConnNode = getBinaryNodeChild(result, "media_conn");
147
+ // TODO: explore full length of data that whatsapp provides
81
148
  const node = {
82
- tag: 'receipt',
83
- attrs: {
84
- id: messageIds[0]
85
- }
149
+ hosts: getBinaryNodeChildren(mediaConnNode, "host").map(
150
+ ({ attrs }) => ({
151
+ hostname: attrs.hostname,
152
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
153
+ }),
154
+ ),
155
+ auth: mediaConnNode.attrs.auth,
156
+ ttl: +mediaConnNode.attrs.ttl,
157
+ fetchDate: new Date(),
86
158
  };
87
- const isReadReceipt = type === 'read' || type === 'read-self';
88
- if (isReadReceipt) {
89
- node.attrs.t = unixTimestampSeconds().toString();
90
- }
91
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
92
- node.attrs.recipient = jid;
93
- node.attrs.to = participant;
159
+ logger.debug("fetched media conn");
160
+ return node;
161
+ })();
162
+ }
163
+ return mediaConn;
164
+ };
165
+ /**
166
+ * generic send receipt function
167
+ * used for receipts of phone call, read, delivery etc.
168
+ * */
169
+ const sendReceipt = async (jid, participant, messageIds, type) => {
170
+ if (!messageIds || messageIds.length === 0) {
171
+ throw new Boom("missing ids in receipt");
172
+ }
173
+ const node = {
174
+ tag: "receipt",
175
+ attrs: {
176
+ id: messageIds[0],
177
+ },
178
+ };
179
+ const isReadReceipt = type === "read" || type === "read-self";
180
+ if (isReadReceipt) {
181
+ node.attrs.t = unixTimestampSeconds().toString();
182
+ }
183
+ if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
184
+ node.attrs.recipient = jid;
185
+ node.attrs.to = participant;
186
+ } else {
187
+ node.attrs.to = jid;
188
+ if (participant) {
189
+ node.attrs.participant = participant;
190
+ }
191
+ }
192
+ if (type) {
193
+ node.attrs.type = type;
194
+ }
195
+ const remainingMessageIds = messageIds.slice(1);
196
+ if (remainingMessageIds.length) {
197
+ node.content = [
198
+ {
199
+ tag: "list",
200
+ attrs: {},
201
+ content: remainingMessageIds.map((id) => ({
202
+ tag: "item",
203
+ attrs: { id },
204
+ })),
205
+ },
206
+ ];
207
+ }
208
+ logger.debug(
209
+ { attrs: node.attrs, messageIds },
210
+ "sending receipt for messages",
211
+ );
212
+ await sendNode(node);
213
+ };
214
+ /** Correctly bulk send receipts to multiple chats, participants */
215
+ const sendReceipts = async (keys, type) => {
216
+ const recps = aggregateMessageKeysNotFromMe(keys);
217
+ for (const { jid, participant, messageIds } of recps) {
218
+ await sendReceipt(jid, participant, messageIds, type);
219
+ }
220
+ };
221
+ /** Bulk read messages. Keys can be from different chats & participants */
222
+ const readMessages = async (keys) => {
223
+ const privacySettings = await fetchPrivacySettings();
224
+ // based on privacy settings, we have to change the read type
225
+ const readType =
226
+ privacySettings.readreceipts === "all" ? "read" : "read-self";
227
+ await sendReceipts(keys, readType);
228
+ };
229
+ /** Fetch all the devices we've to send a message to */
230
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
231
+ const deviceResults = [];
232
+ if (!useCache) {
233
+ logger.debug("not using cache for devices");
234
+ }
235
+ const toFetch = [];
236
+ const jidsWithUser = jids
237
+ .map((jid) => {
238
+ const decoded = jidDecode(jid);
239
+ const user = decoded?.user;
240
+ const device = decoded?.device;
241
+ const isExplicitDevice = typeof device === "number" && device >= 0;
242
+ if (isExplicitDevice && user) {
243
+ deviceResults.push({
244
+ user,
245
+ device,
246
+ jid,
247
+ });
248
+ return null;
94
249
  }
95
- else {
96
- node.attrs.to = jid;
97
- if (participant) {
98
- node.attrs.participant = participant;
99
- }
250
+ jid = jidNormalizedUser(jid);
251
+ return { jid, user };
252
+ })
253
+ .filter((jid) => jid !== null);
254
+ let mgetDevices;
255
+ if (useCache && userDevicesCache.mget) {
256
+ const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
257
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
258
+ }
259
+ for (const { jid, user } of jidsWithUser) {
260
+ if (useCache) {
261
+ const devices =
262
+ mgetDevices?.[user] ||
263
+ (userDevicesCache.mget
264
+ ? undefined
265
+ : await userDevicesCache.get(user));
266
+ if (devices) {
267
+ const devicesWithJid = devices.map((d) => ({
268
+ ...d,
269
+ jid: jidEncode(d.user, d.server, d.device),
270
+ }));
271
+ deviceResults.push(...devicesWithJid);
272
+ logger.trace({ user }, "using cache for devices");
273
+ } else {
274
+ toFetch.push(jid);
100
275
  }
101
- if (type) {
102
- node.attrs.type = type;
276
+ } else {
277
+ toFetch.push(jid);
278
+ }
279
+ }
280
+ if (!toFetch.length) {
281
+ return deviceResults;
282
+ }
283
+ const requestedLidUsers = new Set();
284
+ for (const jid of toFetch) {
285
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
286
+ const user = jidDecode(jid)?.user;
287
+ if (user) requestedLidUsers.add(user);
288
+ }
289
+ }
290
+ const query = new USyncQuery()
291
+ .withContext("message")
292
+ .withDeviceProtocol()
293
+ .withLIDProtocol();
294
+ for (const jid of toFetch) {
295
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
296
+ }
297
+ const result = await sock.executeUSyncQuery(query);
298
+ if (result) {
299
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
300
+ const lidResults = result.list.filter((a) => !!a.lid);
301
+ if (lidResults.length > 0) {
302
+ logger.trace("Storing LID maps from device call");
303
+ await signalRepository.lidMapping.storeLIDPNMappings(
304
+ lidResults.map((a) => ({ lid: a.lid, pn: a.id })),
305
+ );
306
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
307
+ try {
308
+ const lids = lidResults.map((a) => a.lid);
309
+ if (lids.length) {
310
+ await assertSessions(lids, true);
311
+ }
312
+ } catch (e) {
313
+ logger.warn(
314
+ { e, count: lidResults.length },
315
+ "failed to assert sessions for newly mapped LIDs",
316
+ );
103
317
  }
104
- const remainingMessageIds = messageIds.slice(1);
105
- if (remainingMessageIds.length) {
106
- node.content = [
107
- {
108
- tag: 'list',
109
- attrs: {},
110
- content: remainingMessageIds.map(id => ({
111
- tag: 'item',
112
- attrs: { id }
113
- }))
114
- }
115
- ];
318
+ }
319
+ const extracted = extractDeviceJids(
320
+ result?.list,
321
+ authState.creds.me.id,
322
+ authState.creds.me.lid,
323
+ ignoreZeroDevices,
324
+ );
325
+ const deviceMap = {};
326
+ for (const item of extracted) {
327
+ deviceMap[item.user] = deviceMap[item.user] || [];
328
+ deviceMap[item.user]?.push(item);
329
+ }
330
+ // Process each user's devices as a group for bulk LID migration
331
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
332
+ const isLidUser = requestedLidUsers.has(user);
333
+ // Process all devices for this user
334
+ for (const item of userDevices) {
335
+ const finalJid = isLidUser
336
+ ? jidEncode(user, item.server, item.device)
337
+ : jidEncode(item.user, item.server, item.device);
338
+ deviceResults.push({
339
+ ...item,
340
+ jid: finalJid,
341
+ });
342
+ logger.debug(
343
+ {
344
+ user: item.user,
345
+ device: item.device,
346
+ finalJid,
347
+ usedLid: isLidUser,
348
+ },
349
+ "Processed device with LID priority",
350
+ );
116
351
  }
117
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
118
- await sendNode(node);
119
- };
120
- /** Correctly bulk send receipts to multiple chats, participants */
121
- const sendReceipts = async (keys, type) => {
122
- const recps = aggregateMessageKeysNotFromMe(keys);
123
- for (const { jid, participant, messageIds } of recps) {
124
- await sendReceipt(jid, participant, messageIds, type);
352
+ }
353
+ if (userDevicesCache.mset) {
354
+ // if the cache supports mset, we can set all devices in one go
355
+ await userDevicesCache.mset(
356
+ Object.entries(deviceMap).map(([key, value]) => ({ key, value })),
357
+ );
358
+ } else {
359
+ for (const key in deviceMap) {
360
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
125
361
  }
126
- };
127
- /** Bulk read messages. Keys can be from different chats & participants */
128
- const readMessages = async (keys) => {
129
- const privacySettings = await fetchPrivacySettings();
130
- // based on privacy settings, we have to change the read type
131
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
132
- await sendReceipts(keys, readType);
133
- };
134
- /** Fetch all the devices we've to send a message to */
135
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
136
- const deviceResults = [];
137
- if (!useCache) {
138
- logger.debug('not using cache for devices');
362
+ }
363
+ const userDeviceUpdates = {};
364
+ for (const [userId, devices] of Object.entries(deviceMap)) {
365
+ if (devices && devices.length > 0) {
366
+ userDeviceUpdates[userId] = devices.map(
367
+ (d) => d.device?.toString() || "0",
368
+ );
139
369
  }
140
- const toFetch = [];
141
- const jidsWithUser = jids
142
- .map(jid => {
143
- const decoded = jidDecode(jid);
144
- const user = decoded?.user;
145
- const device = decoded?.device;
146
- const isExplicitDevice = typeof device === 'number' && device >= 0;
147
- if (isExplicitDevice && user) {
148
- deviceResults.push({
149
- user,
150
- device,
151
- jid
152
- });
153
- return null;
154
- }
155
- jid = jidNormalizedUser(jid);
156
- return { jid, user };
157
- })
158
- .filter(jid => jid !== null);
159
- let mgetDevices;
160
- if (useCache && userDevicesCache.mget) {
161
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
162
- mgetDevices = await userDevicesCache.mget(usersToFetch);
370
+ }
371
+ if (Object.keys(userDeviceUpdates).length > 0) {
372
+ try {
373
+ await authState.keys.set({ "device-list": userDeviceUpdates });
374
+ logger.debug(
375
+ { userCount: Object.keys(userDeviceUpdates).length },
376
+ "stored user device lists for bulk migration",
377
+ );
378
+ } catch (error) {
379
+ logger.warn({ error }, "failed to store user device lists");
163
380
  }
164
- for (const { jid, user } of jidsWithUser) {
165
- if (useCache) {
166
- const devices = mgetDevices?.[user] ||
167
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
168
- if (devices) {
169
- const devicesWithJid = devices.map(d => ({
170
- ...d,
171
- jid: jidEncode(d.user, d.server, d.device)
172
- }));
173
- deviceResults.push(...devicesWithJid);
174
- logger.trace({ user }, 'using cache for devices');
175
- }
176
- else {
177
- toFetch.push(jid);
178
- }
179
- }
180
- else {
181
- toFetch.push(jid);
182
- }
183
- }
184
- if (!toFetch.length) {
185
- return deviceResults;
186
- }
187
- const requestedLidUsers = new Set();
188
- for (const jid of toFetch) {
189
- if (isLidUser(jid) || isHostedLidUser(jid)) {
190
- const user = jidDecode(jid)?.user;
191
- if (user)
192
- requestedLidUsers.add(user);
193
- }
381
+ }
382
+ }
383
+ return deviceResults;
384
+ };
385
+ /**
386
+ * Update Member Label
387
+ */
388
+ const updateMemberLabel = (jid, memberLabel) => {
389
+ return relayMessage(
390
+ jid,
391
+ {
392
+ protocolMessage: {
393
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
394
+ memberLabel: {
395
+ label: memberLabel?.slice(0, 30),
396
+ labelTimestamp: unixTimestampSeconds(),
397
+ },
398
+ },
399
+ },
400
+ {
401
+ additionalNodes: [
402
+ {
403
+ tag: "meta",
404
+ attrs: {
405
+ tag_reason: "user_update",
406
+ appdata: "member_tag",
407
+ },
408
+ content: undefined,
409
+ },
410
+ ],
411
+ },
412
+ );
413
+ };
414
+ const assertSessions = async (jids, force) => {
415
+ let didFetchNewSession = false;
416
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
417
+ const jidsRequiringFetch = [];
418
+ logger.debug({ jids }, "assertSessions call with jids");
419
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
420
+ for (const jid of uniqueJids) {
421
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
422
+ const cachedSession = peerSessionsCache.get(signalId);
423
+ if (cachedSession !== undefined) {
424
+ if (cachedSession && !force) {
425
+ continue; // Session exists in cache
194
426
  }
195
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
196
- for (const jid of toFetch) {
197
- query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
427
+ } else {
428
+ const sessionValidation = await signalRepository.validateSession(jid);
429
+ const hasSession = sessionValidation.exists;
430
+ peerSessionsCache.set(signalId, hasSession);
431
+ if (hasSession && !force) {
432
+ continue;
198
433
  }
199
- const result = await sock.executeUSyncQuery(query);
200
- if (result) {
201
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
202
- const lidResults = result.list.filter(a => !!a.lid);
203
- if (lidResults.length > 0) {
204
- logger.trace('Storing LID maps from device call');
205
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
206
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
207
- try {
208
- const lids = lidResults.map(a => a.lid);
209
- if (lids.length) {
210
- await assertSessions(lids, true);
211
- }
212
- }
213
- catch (e) {
214
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
215
- }
216
- }
217
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
218
- const deviceMap = {};
219
- for (const item of extracted) {
220
- deviceMap[item.user] = deviceMap[item.user] || [];
221
- deviceMap[item.user]?.push(item);
222
- }
223
- // Process each user's devices as a group for bulk LID migration
224
- for (const [user, userDevices] of Object.entries(deviceMap)) {
225
- const isLidUser = requestedLidUsers.has(user);
226
- // Process all devices for this user
227
- for (const item of userDevices) {
228
- const finalJid = isLidUser
229
- ? jidEncode(user, item.server, item.device)
230
- : jidEncode(item.user, item.server, item.device);
231
- deviceResults.push({
232
- ...item,
233
- jid: finalJid
234
- });
235
- logger.debug({
236
- user: item.user,
237
- device: item.device,
238
- finalJid,
239
- usedLid: isLidUser
240
- }, 'Processed device with LID priority');
241
- }
434
+ }
435
+ jidsRequiringFetch.push(jid);
436
+ }
437
+ if (jidsRequiringFetch.length) {
438
+ // LID if mapped, otherwise original
439
+ const wireJids = [
440
+ ...jidsRequiringFetch.filter(
441
+ (jid) => !!isLidUser(jid) || !!isHostedLidUser(jid),
442
+ ),
443
+ ...(
444
+ (await signalRepository.lidMapping.getLIDsForPNs(
445
+ jidsRequiringFetch.filter(
446
+ (jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
447
+ ),
448
+ )) || []
449
+ ).map((a) => a.lid),
450
+ ];
451
+ logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
452
+ const result = await query({
453
+ tag: "iq",
454
+ attrs: {
455
+ xmlns: "encrypt",
456
+ type: "get",
457
+ to: S_WHATSAPP_NET,
458
+ },
459
+ content: [
460
+ {
461
+ tag: "key",
462
+ attrs: {},
463
+ content: wireJids.map((jid) => {
464
+ const attrs = { jid };
465
+ if (force) attrs.reason = "identity";
466
+ return { tag: "user", attrs };
467
+ }),
468
+ },
469
+ ],
470
+ });
471
+ await parseAndInjectE2ESessions(result, signalRepository);
472
+ didFetchNewSession = true;
473
+ // Cache fetched sessions using wire JIDs
474
+ for (const wireJid of wireJids) {
475
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
476
+ peerSessionsCache.set(signalId, true);
477
+ }
478
+ }
479
+ return didFetchNewSession;
480
+ };
481
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
482
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
483
+ if (!authState.creds.me?.id) {
484
+ throw new Boom("Not authenticated");
485
+ }
486
+ const protocolMessage = {
487
+ protocolMessage: {
488
+ peerDataOperationRequestMessage: pdoMessage,
489
+ type: proto.Message.ProtocolMessage.Type
490
+ .PEER_DATA_OPERATION_REQUEST_MESSAGE,
491
+ },
492
+ };
493
+ const meJid = jidNormalizedUser(authState.creds.me.id);
494
+ const msgId = await relayMessage(meJid, protocolMessage, {
495
+ additionalAttributes: {
496
+ category: "peer",
497
+ push_priority: "high_force",
498
+ },
499
+ additionalNodes: [
500
+ {
501
+ tag: "meta",
502
+ attrs: { appdata: "default" },
503
+ },
504
+ ],
505
+ });
506
+ return msgId;
507
+ };
508
+ const createParticipantNodes = async (
509
+ recipientJids,
510
+ message,
511
+ extraAttrs,
512
+ dsmMessage,
513
+ ) => {
514
+ if (!recipientJids.length) {
515
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
516
+ }
517
+ const patched = await patchMessageBeforeSending(message, recipientJids);
518
+ const patchedMessages = Array.isArray(patched)
519
+ ? patched
520
+ : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
521
+ let shouldIncludeDeviceIdentity = false;
522
+ const meId = authState.creds.me.id;
523
+ const meLid = authState.creds.me?.lid;
524
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
525
+ const encryptionPromises = patchedMessages.map(
526
+ async ({ recipientJid: jid, message: patchedMessage }) => {
527
+ try {
528
+ if (!jid) return null;
529
+ let msgToEncrypt = patchedMessage;
530
+ if (dsmMessage) {
531
+ const { user: targetUser } = jidDecode(jid);
532
+ const { user: ownPnUser } = jidDecode(meId);
533
+ const ownLidUser = meLidUser;
534
+ const isOwnUser =
535
+ targetUser === ownPnUser ||
536
+ (ownLidUser && targetUser === ownLidUser);
537
+ const isExactSenderDevice =
538
+ jid === meId || (meLid && jid === meLid);
539
+ if (isOwnUser && !isExactSenderDevice) {
540
+ msgToEncrypt = dsmMessage;
541
+ logger.debug({ jid, targetUser }, "Using DSM for own device");
242
542
  }
243
- await devicesMutex.mutex(async () => {
244
- if (userDevicesCache.mset) {
245
- // if the cache supports mset, we can set all devices in one go
246
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
247
- }
248
- else {
249
- for (const key in deviceMap) {
250
- if (deviceMap[key])
251
- await userDevicesCache.set(key, deviceMap[key]);
252
- }
253
- }
543
+ }
544
+ const bytes = encodeWAMessage(msgToEncrypt);
545
+ const mutexKey = jid;
546
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
547
+ const { type, ciphertext } = await signalRepository.encryptMessage({
548
+ jid,
549
+ data: bytes,
254
550
  });
255
- const userDeviceUpdates = {};
256
- for (const [userId, devices] of Object.entries(deviceMap)) {
257
- if (devices && devices.length > 0) {
258
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
259
- }
260
- }
261
- if (Object.keys(userDeviceUpdates).length > 0) {
262
- try {
263
- await authState.keys.set({ 'device-list': userDeviceUpdates });
264
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
265
- }
266
- catch (error) {
267
- logger.warn({ error }, 'failed to store user device lists');
268
- }
269
- }
270
- }
271
- return deviceResults;
272
- };
273
- /**
274
- * Update Member Label
275
- */
276
- const updateMemberLabel = (jid, memberLabel) => {
277
- return relayMessage(jid, {
278
- protocolMessage: {
279
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
280
- memberLabel: {
281
- label: memberLabel?.slice(0, 30),
282
- labelTimestamp: unixTimestampSeconds()
283
- }
551
+ if (type === "pkmsg") {
552
+ shouldIncludeDeviceIdentity = true;
284
553
  }
285
- }, {
286
- additionalNodes: [
554
+ return {
555
+ tag: "to",
556
+ attrs: { jid },
557
+ content: [
287
558
  {
288
- tag: 'meta',
289
- attrs: {
290
- tag_reason: 'user_update',
291
- appdata: 'member_tag'
292
- },
293
- content: undefined
294
- }
295
- ]
296
- });
297
- };
298
- const assertSessions = async (jids, force) => {
299
- let didFetchNewSession = false;
300
- const uniqueJids = [...new Set(jids)];
301
- const jidsRequiringFetch = [];
302
- logger.debug({ jids }, 'assertSessions call with jids');
303
- for (const jid of uniqueJids) {
304
- if (!force) {
305
- const sessionValidation = await signalRepository.validateSession(jid);
306
- if (sessionValidation.exists) {
307
- continue;
308
- }
309
- }
310
- jidsRequiringFetch.push(jid);
311
- }
312
- if (jidsRequiringFetch.length) {
313
- // LID if mapped, otherwise original
314
- const wireJids = [
315
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
316
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
317
- ];
318
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
319
- const result = await query({
320
- tag: 'iq',
321
- attrs: {
322
- xmlns: 'encrypt',
323
- type: 'get',
324
- to: S_WHATSAPP_NET
559
+ tag: "enc",
560
+ attrs: { v: "2", type, ...(extraAttrs || {}) },
561
+ content: ciphertext,
325
562
  },
326
- content: [
327
- {
328
- tag: 'key',
329
- attrs: {},
330
- content: wireJids.map(jid => {
331
- const attrs = { jid };
332
- if (force)
333
- attrs.reason = 'identity';
334
- return { tag: 'user', attrs };
335
- })
336
- }
337
- ]
338
- });
339
- await parseAndInjectE2ESessions(result, signalRepository);
340
- didFetchNewSession = true;
563
+ ],
564
+ };
565
+ });
566
+ return node;
567
+ } catch (err) {
568
+ logger.error({ jid, err }, "Failed to encrypt for recipient");
569
+ return null;
341
570
  }
342
- return didFetchNewSession;
571
+ },
572
+ );
573
+ const nodes = (await Promise.all(encryptionPromises)).filter(
574
+ (node) => node !== null,
575
+ );
576
+ if (recipientJids.length > 0 && nodes.length === 0) {
577
+ throw new Boom("All encryptions failed", { statusCode: 500 });
578
+ }
579
+ return { nodes, shouldIncludeDeviceIdentity };
580
+ };
581
+ const relayMessage = async (
582
+ jid,
583
+ message,
584
+ {
585
+ messageId: msgId,
586
+ participant,
587
+ additionalAttributes,
588
+ additionalNodes,
589
+ useUserDevicesCache,
590
+ useCachedGroupMetadata,
591
+ statusJidList,
592
+ },
593
+ ) => {
594
+ const meId = authState.creds.me.id;
595
+ const meLid = authState.creds.me?.lid;
596
+ const isRetryResend = Boolean(participant?.jid);
597
+ let shouldIncludeDeviceIdentity = isRetryResend;
598
+ const statusJid = "status@broadcast";
599
+ const { user, server } = jidDecode(jid);
600
+ const isGroup = server === "g.us";
601
+ const isStatus = jid === statusJid;
602
+ const isLid = server === "lid";
603
+ const isNewsletter = server === "newsletter";
604
+ const isGroupOrStatus = isGroup || isStatus;
605
+ const finalJid = jid;
606
+ msgId = msgId || generateMessageIDV2(meId);
607
+ useUserDevicesCache = useUserDevicesCache !== false;
608
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
609
+ const participants = [];
610
+ const destinationJid = !isStatus ? finalJid : statusJid;
611
+ const binaryNodeContent = [];
612
+ const devices = [];
613
+ let reportingMessage;
614
+ const meMsg = {
615
+ deviceSentMessage: {
616
+ destinationJid,
617
+ message,
618
+ },
619
+ messageContextInfo: message.messageContextInfo,
343
620
  };
344
- const sendPeerDataOperationMessage = async (pdoMessage) => {
345
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
346
- if (!authState.creds.me?.id) {
347
- throw new Boom('Not authenticated');
348
- }
349
- const protocolMessage = {
350
- protocolMessage: {
351
- peerDataOperationRequestMessage: pdoMessage,
352
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
353
- }
621
+ const extraAttrs = {};
622
+ if (participant) {
623
+ if (!isGroup && !isStatus) {
624
+ additionalAttributes = {
625
+ ...additionalAttributes,
626
+ device_fanout: "false",
354
627
  };
355
- const meJid = jidNormalizedUser(authState.creds.me.id);
356
- const msgId = await relayMessage(meJid, protocolMessage, {
357
- additionalAttributes: {
358
- category: 'peer',
359
- push_priority: 'high_force'
360
- },
361
- additionalNodes: [
362
- {
363
- tag: 'meta',
364
- attrs: { appdata: 'default' }
365
- }
366
- ]
628
+ }
629
+ const { user, device } = jidDecode(participant.jid);
630
+ devices.push({
631
+ user,
632
+ device,
633
+ jid: participant.jid,
634
+ });
635
+ }
636
+ await authState.keys.transaction(async () => {
637
+ const mediaType = getMediaType(
638
+ normalizeMessageContent(message) || message,
639
+ );
640
+ if (mediaType) {
641
+ extraAttrs["mediatype"] = mediaType;
642
+ }
643
+ if (isNewsletter) {
644
+ const patched = patchMessageBeforeSending
645
+ ? await patchMessageBeforeSending(message, [])
646
+ : message;
647
+ const bytes = encodeNewsletterMessage(patched);
648
+ binaryNodeContent.push({
649
+ tag: "plaintext",
650
+ attrs: extraAttrs || {},
651
+ content: bytes,
367
652
  });
368
- return msgId;
369
- };
370
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
371
- if (!recipientJids.length) {
372
- return { nodes: [], shouldIncludeDeviceIdentity: false };
373
- }
374
- const patched = await patchMessageBeforeSending(message, recipientJids);
375
- const patchedMessages = Array.isArray(patched)
376
- ? patched
377
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
378
- let shouldIncludeDeviceIdentity = false;
379
- const meId = authState.creds.me.id;
380
- const meLid = authState.creds.me?.lid;
381
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
382
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
383
- try {
384
- if (!jid)
385
- return null;
386
- let msgToEncrypt = patchedMessage;
387
- if (dsmMessage) {
388
- const { user: targetUser } = jidDecode(jid);
389
- const { user: ownPnUser } = jidDecode(meId);
390
- const ownLidUser = meLidUser;
391
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
392
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
393
- if (isOwnUser && !isExactSenderDevice) {
394
- msgToEncrypt = dsmMessage;
395
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
396
- }
397
- }
398
- const bytes = encodeWAMessage(msgToEncrypt);
399
- const mutexKey = jid;
400
- const node = await encryptionMutex.mutex(mutexKey, async () => {
401
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
402
- if (type === 'pkmsg') {
403
- shouldIncludeDeviceIdentity = true;
404
- }
405
- return {
406
- tag: 'to',
407
- attrs: { jid },
408
- content: [
409
- {
410
- tag: 'enc',
411
- attrs: { v: '2', type, ...(extraAttrs || {}) },
412
- content: ciphertext
413
- }
414
- ]
415
- };
416
- });
417
- return node;
418
- }
419
- catch (err) {
420
- logger.error({ jid, err }, 'Failed to encrypt for recipient');
421
- return null;
422
- }
423
- });
424
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
425
- if (recipientJids.length > 0 && nodes.length === 0) {
426
- throw new Boom('All encryptions failed', { statusCode: 500 });
427
- }
428
- return { nodes, shouldIncludeDeviceIdentity };
429
- };
430
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
431
- const meId = assertMeId(authState.creds);
432
- const meLid = authState.creds.me?.lid;
433
- const isRetryResend = Boolean(participant?.jid);
434
- let shouldIncludeDeviceIdentity = isRetryResend;
435
- const statusJid = 'status@broadcast';
436
- const { user, server } = jidDecode(jid);
437
- const isGroup = server === 'g.us';
438
- const isStatus = jid === statusJid;
439
- const isLid = server === 'lid';
440
- const isNewsletter = server === 'newsletter';
441
- const isGroupOrStatus = isGroup || isStatus;
442
- const finalJid = jid;
443
- msgId = msgId || generateMessageIDV2(meId);
444
- useUserDevicesCache = useUserDevicesCache !== false;
445
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
446
- const participants = [];
447
- const destinationJid = !isStatus ? finalJid : statusJid;
448
- const binaryNodeContent = [];
449
- const devices = [];
450
- let reportingMessage;
451
- const meMsg = {
452
- deviceSentMessage: {
453
- destinationJid,
454
- message
455
- },
456
- messageContextInfo: message.messageContextInfo
653
+ const stanza = {
654
+ tag: "message",
655
+ attrs: {
656
+ to: jid,
657
+ id: msgId,
658
+ type: getMessageType(message),
659
+ ...(additionalAttributes || {}),
660
+ },
661
+ content: binaryNodeContent,
457
662
  };
458
- const extraAttrs = {};
459
- if (participant) {
460
- if (!isGroup && !isStatus) {
461
- additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
663
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
664
+ await sendNode(stanza);
665
+ return;
666
+ }
667
+ if (
668
+ normalizeMessageContent(message)?.pinInChatMessage ||
669
+ normalizeMessageContent(message)?.reactionMessage
670
+ ) {
671
+ extraAttrs["decrypt-fail"] = "hide"; // todo: expand for reactions and other types
672
+ }
673
+ if (isGroupOrStatus && !isRetryResend) {
674
+ const [groupData, senderKeyMap] = await Promise.all([
675
+ (async () => {
676
+ let groupData =
677
+ useCachedGroupMetadata && cachedGroupMetadata
678
+ ? await cachedGroupMetadata(jid)
679
+ : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
680
+ if (groupData && Array.isArray(groupData?.participants)) {
681
+ logger.trace(
682
+ { jid, participants: groupData.participants.length },
683
+ "using cached group metadata",
684
+ );
685
+ } else if (!isStatus) {
686
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
462
687
  }
463
- const { user, device } = jidDecode(participant.jid);
464
- devices.push({
465
- user,
466
- device,
467
- jid: participant.jid
468
- });
469
- }
470
- await authState.keys.transaction(async () => {
471
- const mediaType = getMediaType(message);
472
- if (mediaType) {
473
- extraAttrs['mediatype'] = mediaType;
474
- }
475
- if (isNewsletter) {
476
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
477
- const bytes = encodeNewsletterMessage(patched);
478
- binaryNodeContent.push({
479
- tag: 'plaintext',
480
- attrs: {},
481
- content: bytes
482
- });
483
- const stanza = {
484
- tag: 'message',
485
- attrs: {
486
- to: jid,
487
- id: msgId,
488
- type: getMessageType(message),
489
- ...(additionalAttributes || {})
490
- },
491
- content: binaryNodeContent
492
- };
493
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
494
- await sendNode(stanza);
495
- return;
496
- }
497
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
498
- extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
499
- }
500
- if (isGroupOrStatus && !isRetryResend) {
501
- const [groupData, senderKeyMap] = await Promise.all([
502
- (async () => {
503
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
504
- if (groupData && Array.isArray(groupData?.participants)) {
505
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
506
- }
507
- else if (!isStatus) {
508
- groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
509
- }
510
- return groupData;
511
- })(),
512
- (async () => {
513
- if (!participant && !isStatus) {
514
- // what if sender memory is less accurate than the cached metadata
515
- // on participant change in group, we should do sender memory manipulation
516
- const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
517
- return result[jid] || {};
518
- }
519
- return {};
520
- })()
521
- ]);
522
- const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
523
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
524
- additionalAttributes = {
525
- ...additionalAttributes,
526
- expiration: groupData.ephemeralDuration.toString()
527
- };
528
- }
529
- if (isStatus && statusJidList) {
530
- participantsList.push(...statusJidList);
531
- }
532
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
533
- devices.push(...additionalDevices);
534
- if (isGroup) {
535
- additionalAttributes = {
536
- ...additionalAttributes,
537
- addressing_mode: groupData?.addressingMode || 'lid'
538
- };
539
- }
540
- const patched = await patchMessageBeforeSending(message);
541
- if (Array.isArray(patched)) {
542
- throw new Boom('Per-jid patching is not supported in groups');
543
- }
544
- const bytes = encodeWAMessage(patched);
545
- reportingMessage = patched;
546
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
547
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
548
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
549
- group: destinationJid,
550
- data: bytes,
551
- meId: groupSenderIdentity
552
- });
553
- const senderKeyRecipients = [];
554
- for (const device of devices) {
555
- const deviceJid = device.jid;
556
- const hasKey = !!senderKeyMap[deviceJid];
557
- if ((!hasKey || !!participant) &&
558
- !isHostedLidUser(deviceJid) &&
559
- !isHostedPnUser(deviceJid) &&
560
- device.device !== 99) {
561
- //todo: revamp all this logic
562
- // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
563
- senderKeyRecipients.push(deviceJid);
564
- senderKeyMap[deviceJid] = true;
565
- }
566
- }
567
- if (senderKeyRecipients.length) {
568
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
569
- const senderKeyMsg = {
570
- senderKeyDistributionMessage: {
571
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
572
- groupId: destinationJid
573
- }
574
- };
575
- const senderKeySessionTargets = senderKeyRecipients;
576
- await assertSessions(senderKeySessionTargets);
577
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
578
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
579
- participants.push(...result.nodes);
580
- }
581
- binaryNodeContent.push({
582
- tag: 'enc',
583
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
584
- content: ciphertext
585
- });
586
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
587
- }
588
- else {
589
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
590
- // TODO: investigate if this is true
591
- let ownId = meId;
592
- if (isLid && meLid) {
593
- ownId = meLid;
594
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
595
- }
596
- else {
597
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
598
- }
599
- const { user: ownUser } = jidDecode(ownId);
600
- if (!participant) {
601
- const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
602
- reportingMessage = Array.isArray(patchedForReporting)
603
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
604
- : patchedForReporting;
605
- }
606
- if (!isRetryResend) {
607
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
608
- devices.push({
609
- user,
610
- device: 0,
611
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
612
- });
613
- if (user !== ownUser) {
614
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
615
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
616
- devices.push({
617
- user: ownUserForAddressing,
618
- device: 0,
619
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
620
- });
621
- }
622
- if (additionalAttributes?.['category'] !== 'peer') {
623
- // Clear placeholders and enumerate actual devices
624
- devices.length = 0;
625
- // Use conversation-appropriate sender identity
626
- const senderIdentity = isLid && meLid
627
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
628
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
629
- // Enumerate devices for sender and target with consistent addressing
630
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
631
- devices.push(...sessionDevices);
632
- logger.debug({
633
- deviceCount: devices.length,
634
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
635
- }, 'Device enumeration complete with unified addressing');
636
- }
637
- }
638
- const allRecipients = [];
639
- const meRecipients = [];
640
- const otherRecipients = [];
641
- const { user: mePnUser } = jidDecode(meId);
642
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
643
- for (const { user, jid } of devices) {
644
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
645
- if (isExactSenderDevice) {
646
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
647
- continue;
648
- }
649
- // Check if this is our device (could match either PN or LID user)
650
- const isMe = user === mePnUser || user === meLidUser;
651
- if (isMe) {
652
- meRecipients.push(jid);
653
- }
654
- else {
655
- otherRecipients.push(jid);
656
- }
657
- allRecipients.push(jid);
658
- }
659
- await assertSessions(allRecipients);
660
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
661
- // For own devices: use DSM if available (1:1 chats only)
662
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
663
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
664
- ]);
665
- participants.push(...meNodes);
666
- participants.push(...otherNodes);
667
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
668
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
669
- }
670
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
671
- }
672
- if (isRetryResend) {
673
- const isParticipantLid = isLidUser(participant.jid);
674
- const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
675
- let messageToSend = message;
676
- if (isGroupOrStatus) {
677
- let groupSenderIdentity;
678
- if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
679
- groupSenderIdentity = meLid;
680
- }
681
- else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
682
- groupSenderIdentity = meId;
683
- }
684
- if (groupSenderIdentity) {
685
- try {
686
- const skdm = await signalRepository.getSenderKeyDistributionMessage({
687
- group: destinationJid,
688
- meId: groupSenderIdentity
689
- });
690
- messageToSend = {
691
- ...message,
692
- senderKeyDistributionMessage: {
693
- groupId: destinationJid,
694
- axolotlSenderKeyDistributionMessage: skdm
695
- }
696
- };
697
- }
698
- catch (err) {
699
- logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
700
- }
701
- }
702
- }
703
- const encodedMessageToSend = isMe
704
- ? encodeWAMessage({
705
- deviceSentMessage: {
706
- destinationJid,
707
- message: messageToSend
708
- }
709
- })
710
- : encodeWAMessage(messageToSend);
711
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
712
- data: encodedMessageToSend,
713
- jid: participant.jid
714
- });
715
- binaryNodeContent.push({
716
- tag: 'enc',
717
- attrs: {
718
- v: '2',
719
- type,
720
- count: participant.count.toString()
721
- },
722
- content: encryptedContent
723
- });
724
- }
725
- if (participants.length) {
726
- if (additionalAttributes?.['category'] === 'peer') {
727
- const peerNode = participants[0]?.content?.[0];
728
- if (peerNode) {
729
- binaryNodeContent.push(peerNode); // push only enc
730
- }
731
- }
732
- else {
733
- binaryNodeContent.push({
734
- tag: 'participants',
735
- attrs: {},
736
- content: participants
737
- });
738
- }
688
+ return groupData;
689
+ })(),
690
+ (async () => {
691
+ if (!participant && !isStatus) {
692
+ // what if sender memory is less accurate than the cached metadata
693
+ // on participant change in group, we should do sender memory manipulation
694
+ const result = await authState.keys.get("sender-key-memory", [
695
+ jid,
696
+ ]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
697
+ return result[jid] || {};
739
698
  }
740
- const stanza = {
741
- tag: 'message',
742
- attrs: {
743
- id: msgId,
744
- to: destinationJid,
745
- type: getMessageType(message),
746
- ...(additionalAttributes || {})
747
- },
748
- content: binaryNodeContent
749
- };
750
- // if the participant to send to is explicitly specified (generally retry recp)
751
- // ensure the message is only sent to that person
752
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
753
- if (participant) {
754
- if (isJidGroup(destinationJid)) {
755
- stanza.attrs.to = destinationJid;
756
- stanza.attrs.participant = participant.jid;
757
- }
758
- else if (areJidsSameUser(participant.jid, meId)) {
759
- stanza.attrs.to = participant.jid;
760
- stanza.attrs.recipient = destinationJid;
761
- }
762
- else {
763
- stanza.attrs.to = participant.jid;
764
- }
765
- }
766
- else {
767
- stanza.attrs.to = destinationJid;
768
- }
769
- if (shouldIncludeDeviceIdentity) {
770
- ;
771
- stanza.content.push({
772
- tag: 'device-identity',
773
- attrs: {},
774
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
775
- });
776
- logger.debug({ jid }, 'adding device identity');
777
- }
778
- if (!isNewsletter &&
779
- !isRetryResend &&
780
- reportingMessage?.messageContextInfo?.messageSecret &&
781
- shouldIncludeReportingToken(reportingMessage)) {
782
- try {
783
- const encoded = encodeWAMessage(reportingMessage);
784
- const reportingKey = {
785
- id: msgId,
786
- fromMe: true,
787
- remoteJid: destinationJid,
788
- participant: participant?.jid
789
- };
790
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
791
- if (reportingNode) {
792
- ;
793
- stanza.content.push(reportingNode);
794
- logger.trace({ jid }, 'added reporting token to message');
795
- }
796
- }
797
- catch (error) {
798
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
799
- }
800
- }
801
- // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
802
- const isPeerMessage = additionalAttributes?.['category'] === 'peer';
803
- const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
804
- // Resolve destination to LID for tctoken storage — matches Signal session key pattern
805
- const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
806
- const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
807
- const existingTokenEntry = contactTcTokenData[tcTokenJid];
808
- let tcTokenBuffer = existingTokenEntry?.token;
809
- // Treat expired tokens the same as missing — clear from cache
810
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
811
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
812
- tcTokenBuffer = undefined;
813
- // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
814
- const cleared = existingTokenEntry?.senderTimestamp !== undefined
815
- ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
816
- : null;
817
- try {
818
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
819
- }
820
- catch (err) {
821
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
822
- }
823
- }
824
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
825
- ;
826
- stanza.content.push({
827
- tag: 'tctoken',
828
- attrs: {},
829
- content: tcTokenBuffer
830
- });
831
- }
832
- if (additionalNodes && additionalNodes.length > 0) {
833
- ;
834
- stanza.content.push(...additionalNodes);
835
- }
836
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
837
- await sendNode(stanza);
838
- // Fire-and-forget: issue our token to the contact AFTER message send.
839
- // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
840
- const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
841
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
842
- if (is1on1Send &&
843
- !isProtocolMsg &&
844
- !isBotOrPSA &&
845
- shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
846
- !inFlightTcTokenIssuance.has(tcTokenJid)) {
847
- inFlightTcTokenIssuance.add(tcTokenJid);
848
- const issueTimestamp = unixTimestampSeconds();
849
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
850
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
851
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
852
- .then(async (result) => {
853
- await storeTcTokensFromIqResult({
854
- result,
855
- fallbackJid: tcTokenJid,
856
- keys: authState.keys,
857
- getLIDForPN
858
- });
859
- const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
860
- const currentEntry = currentData[tcTokenJid];
861
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
862
- await authState.keys.set({
863
- tctoken: {
864
- [tcTokenJid]: {
865
- token: Buffer.alloc(0),
866
- ...currentEntry,
867
- senderTimestamp: issueTimestamp
868
- },
869
- ...indexWrite
870
- }
871
- });
872
- })
873
- .catch(err => {
874
- logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
875
- })
876
- .finally(() => {
877
- inFlightTcTokenIssuance.delete(tcTokenJid);
878
- });
879
- }
880
- // Add message to retry cache if enabled
881
- if (messageRetryManager && !participant) {
882
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
883
- }
884
- }, meId);
885
- return msgId;
886
- };
887
- const getMessageType = (message) => {
888
- const normalizedMessage = normalizeMessageContent(message);
889
- if (!normalizedMessage)
890
- return 'text';
891
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
892
- return 'reaction';
893
- }
894
- if (normalizedMessage.pollCreationMessage ||
895
- normalizedMessage.pollCreationMessageV2 ||
896
- normalizedMessage.pollCreationMessageV3 ||
897
- normalizedMessage.pollUpdateMessage) {
898
- return 'poll';
899
- }
900
- if (normalizedMessage.eventMessage) {
901
- return 'event';
902
- }
903
- if (getMediaType(normalizedMessage) !== '') {
904
- return 'media';
905
- }
906
- return 'text';
907
- };
908
- const getMediaType = (message) => {
909
- if (message.imageMessage) {
910
- return 'image';
911
- }
912
- else if (message.videoMessage) {
913
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
914
- }
915
- else if (message.audioMessage) {
916
- return message.audioMessage.ptt ? 'ptt' : 'audio';
699
+ return {};
700
+ })(),
701
+ ]);
702
+ const participantsList = groupData
703
+ ? groupData.participants.map((p) => p.id)
704
+ : [];
705
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
706
+ additionalAttributes = {
707
+ ...additionalAttributes,
708
+ expiration: groupData.ephemeralDuration.toString(),
709
+ };
917
710
  }
918
- else if (message.contactMessage) {
919
- return 'vcard';
711
+ if (isStatus && statusJidList) {
712
+ participantsList.push(...statusJidList);
920
713
  }
921
- else if (message.documentMessage) {
922
- return 'document';
714
+ const additionalDevices = await getUSyncDevices(
715
+ participantsList,
716
+ !!useUserDevicesCache,
717
+ false,
718
+ );
719
+ devices.push(...additionalDevices);
720
+ if (isGroup) {
721
+ additionalAttributes = {
722
+ ...additionalAttributes,
723
+ addressing_mode: groupData?.addressingMode || "lid",
724
+ };
923
725
  }
924
- else if (message.contactsArrayMessage) {
925
- return 'contact_array';
726
+ const patched = await patchMessageBeforeSending(message);
727
+ if (Array.isArray(patched)) {
728
+ throw new Boom("Per-jid patching is not supported in groups");
926
729
  }
927
- else if (message.liveLocationMessage) {
928
- return 'livelocation';
730
+ const bytes = encodeWAMessage(patched);
731
+ reportingMessage = patched;
732
+ const groupAddressingMode =
733
+ additionalAttributes?.["addressing_mode"] ||
734
+ groupData?.addressingMode ||
735
+ "lid";
736
+ const groupSenderIdentity =
737
+ groupAddressingMode === "lid" && meLid ? meLid : meId;
738
+ const { ciphertext, senderKeyDistributionMessage } =
739
+ await signalRepository.encryptGroupMessage({
740
+ group: destinationJid,
741
+ data: bytes,
742
+ meId: groupSenderIdentity,
743
+ });
744
+ const senderKeyRecipients = [];
745
+ for (const device of devices) {
746
+ const deviceJid = device.jid;
747
+ const hasKey = !!senderKeyMap[deviceJid];
748
+ if (
749
+ (!hasKey || !!participant) &&
750
+ !isHostedLidUser(deviceJid) &&
751
+ !isHostedPnUser(deviceJid) &&
752
+ device.device !== 99
753
+ ) {
754
+ //todo: revamp all this logic
755
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
756
+ senderKeyRecipients.push(deviceJid);
757
+ senderKeyMap[deviceJid] = true;
758
+ }
929
759
  }
930
- else if (message.stickerMessage) {
931
- return 'sticker';
760
+ if (senderKeyRecipients.length) {
761
+ logger.debug(
762
+ { senderKeyJids: senderKeyRecipients },
763
+ "sending new sender key",
764
+ );
765
+ const senderKeyMsg = {
766
+ senderKeyDistributionMessage: {
767
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
768
+ groupId: destinationJid,
769
+ },
770
+ };
771
+ const senderKeySessionTargets = senderKeyRecipients;
772
+ await assertSessions(senderKeySessionTargets);
773
+ const result = await createParticipantNodes(
774
+ senderKeyRecipients,
775
+ senderKeyMsg,
776
+ extraAttrs,
777
+ );
778
+ shouldIncludeDeviceIdentity =
779
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
780
+ participants.push(...result.nodes);
932
781
  }
933
- else if (message.stickerPackMessage) {
934
- return 'sticker_pack';
782
+ binaryNodeContent.push({
783
+ tag: "enc",
784
+ attrs: { v: "2", type: "skmsg", ...extraAttrs },
785
+ content: ciphertext,
786
+ });
787
+ await authState.keys.set({
788
+ "sender-key-memory": { [jid]: senderKeyMap },
789
+ });
790
+ } else {
791
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
792
+ // TODO: investigate if this is true
793
+ let ownId = meId;
794
+ if (isLid && meLid) {
795
+ ownId = meLid;
796
+ logger.debug(
797
+ { to: jid, ownId },
798
+ "Using LID identity for @lid conversation",
799
+ );
800
+ } else {
801
+ logger.debug(
802
+ { to: jid, ownId },
803
+ "Using PN identity for @s.whatsapp.net conversation",
804
+ );
935
805
  }
936
- else if (message.listMessage) {
937
- return 'list';
806
+ const { user: ownUser } = jidDecode(ownId);
807
+ if (!participant) {
808
+ const patchedForReporting = await patchMessageBeforeSending(message, [
809
+ jid,
810
+ ]);
811
+ reportingMessage = Array.isArray(patchedForReporting)
812
+ ? patchedForReporting.find((item) => item.recipientJid === jid) ||
813
+ patchedForReporting[0]
814
+ : patchedForReporting;
938
815
  }
939
- else if (message.listResponseMessage) {
940
- return 'list_response';
816
+ if (!isRetryResend) {
817
+ const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
818
+ devices.push({
819
+ user,
820
+ device: 0,
821
+ jid: jidEncode(user, targetUserServer, 0), // rajeh, todo: this entire logic is convoluted and weird.
822
+ });
823
+ if (user !== ownUser) {
824
+ const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
825
+ const ownUserForAddressing =
826
+ isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
827
+ devices.push({
828
+ user: ownUserForAddressing,
829
+ device: 0,
830
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
831
+ });
832
+ }
833
+ if (additionalAttributes?.["category"] !== "peer") {
834
+ // Clear placeholders and enumerate actual devices
835
+ devices.length = 0;
836
+ // Use conversation-appropriate sender identity
837
+ const senderIdentity =
838
+ isLid && meLid
839
+ ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
840
+ : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
841
+ // Enumerate devices for sender and target with consistent addressing
842
+ const sessionDevices = await getUSyncDevices(
843
+ [senderIdentity, jid],
844
+ true,
845
+ false,
846
+ );
847
+ devices.push(...sessionDevices);
848
+ logger.debug(
849
+ {
850
+ deviceCount: devices.length,
851
+ devices: devices.map(
852
+ (d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`,
853
+ ),
854
+ },
855
+ "Device enumeration complete with unified addressing",
856
+ );
857
+ }
941
858
  }
942
- else if (message.buttonsResponseMessage) {
943
- return 'buttons_response';
859
+ const allRecipients = [];
860
+ const meRecipients = [];
861
+ const otherRecipients = [];
862
+ const { user: mePnUser } = jidDecode(meId);
863
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
864
+ for (const { user, jid } of devices) {
865
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
866
+ if (isExactSenderDevice) {
867
+ logger.debug(
868
+ { jid, meId, meLid },
869
+ "Skipping exact sender device (whatsmeow pattern)",
870
+ );
871
+ continue;
872
+ }
873
+ // Check if this is our device (could match either PN or LID user)
874
+ const isMe = user === mePnUser || user === meLidUser;
875
+ if (isMe) {
876
+ meRecipients.push(jid);
877
+ } else {
878
+ otherRecipients.push(jid);
879
+ }
880
+ allRecipients.push(jid);
944
881
  }
945
- else if (message.orderMessage) {
946
- return 'order';
882
+ await assertSessions(allRecipients);
883
+ const [
884
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
885
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
886
+ ] = await Promise.all([
887
+ // For own devices: use DSM if available (1:1 chats only)
888
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
889
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
890
+ ]);
891
+ participants.push(...meNodes);
892
+ participants.push(...otherNodes);
893
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
894
+ extraAttrs["phash"] = generateParticipantHashV2([
895
+ ...meRecipients,
896
+ ...otherRecipients,
897
+ ]);
947
898
  }
948
- else if (message.productMessage) {
949
- return 'product';
899
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
900
+ }
901
+ if (isRetryResend) {
902
+ const isParticipantLid = isLidUser(participant.jid);
903
+ const isMe = areJidsSameUser(
904
+ participant.jid,
905
+ isParticipantLid ? meLid : meId,
906
+ );
907
+ const encodedMessageToSend = isMe
908
+ ? encodeWAMessage({
909
+ deviceSentMessage: {
910
+ destinationJid,
911
+ message,
912
+ },
913
+ })
914
+ : encodeWAMessage(message);
915
+ const { type, ciphertext: encryptedContent } =
916
+ await signalRepository.encryptMessage({
917
+ data: encodedMessageToSend,
918
+ jid: participant.jid,
919
+ });
920
+ binaryNodeContent.push({
921
+ tag: "enc",
922
+ attrs: {
923
+ v: "2",
924
+ type,
925
+ count: participant.count.toString(),
926
+ },
927
+ content: encryptedContent,
928
+ });
929
+ }
930
+ if (participants.length) {
931
+ if (additionalAttributes?.["category"] === "peer") {
932
+ const peerNode = participants[0]?.content?.[0];
933
+ if (peerNode) {
934
+ binaryNodeContent.push(peerNode); // push only enc
935
+ }
936
+ } else {
937
+ binaryNodeContent.push({
938
+ tag: "participants",
939
+ attrs: {},
940
+ content: participants,
941
+ });
950
942
  }
951
- else if (message.interactiveResponseMessage) {
952
- return 'native_flow_response';
943
+ }
944
+ const stanza = {
945
+ tag: "message",
946
+ attrs: {
947
+ id: msgId,
948
+ to: destinationJid,
949
+ type: getMessageType(message),
950
+ ...(additionalAttributes || {}),
951
+ },
952
+ content: binaryNodeContent,
953
+ };
954
+ // if the participant to send to is explicitly specified (generally retry recp)
955
+ // ensure the message is only sent to that person
956
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
957
+ if (participant) {
958
+ if (isJidGroup(destinationJid)) {
959
+ stanza.attrs.to = destinationJid;
960
+ stanza.attrs.participant = participant.jid;
961
+ } else if (areJidsSameUser(participant.jid, meId)) {
962
+ stanza.attrs.to = participant.jid;
963
+ stanza.attrs.recipient = destinationJid;
964
+ } else {
965
+ stanza.attrs.to = participant.jid;
953
966
  }
954
- else if (message.groupInviteMessage) {
955
- return 'url';
967
+ } else {
968
+ stanza.attrs.to = destinationJid;
969
+ }
970
+ if (shouldIncludeDeviceIdentity) {
971
+ stanza.content.push({
972
+ tag: "device-identity",
973
+ attrs: {},
974
+ content: encodeSignedDeviceIdentity(authState.creds.account, true),
975
+ });
976
+ logger.debug({ jid }, "adding device identity");
977
+ }
978
+ if (
979
+ !isNewsletter &&
980
+ !isRetryResend &&
981
+ reportingMessage?.messageContextInfo?.messageSecret &&
982
+ shouldIncludeReportingToken(reportingMessage)
983
+ ) {
984
+ try {
985
+ const encoded = encodeWAMessage(reportingMessage);
986
+ const reportingKey = {
987
+ id: msgId,
988
+ fromMe: true,
989
+ remoteJid: destinationJid,
990
+ participant: participant?.jid,
991
+ };
992
+ const reportingNode = await getMessageReportingToken(
993
+ encoded,
994
+ reportingMessage,
995
+ reportingKey,
996
+ );
997
+ if (reportingNode) {
998
+ stanza.content.push(reportingNode);
999
+ logger.trace({ jid }, "added reporting token to message");
1000
+ }
1001
+ } catch (error) {
1002
+ logger.warn(
1003
+ { jid, trace: error?.stack },
1004
+ "failed to attach reporting token",
1005
+ );
956
1006
  }
957
- return '';
958
- };
959
- const issuePrivacyTokens = async (jids, timestamp) => {
960
- const t = (timestamp ?? unixTimestampSeconds()).toString();
961
- const result = await query({
962
- tag: 'iq',
1007
+ }
1008
+ const contactTcTokenData =
1009
+ !isGroup && !isRetryResend && !isStatus
1010
+ ? await authState.keys.get("tctoken", [destinationJid])
1011
+ : {};
1012
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
1013
+ if (tcTokenBuffer) {
1014
+ stanza.content.push({
1015
+ tag: "tctoken",
1016
+ attrs: {},
1017
+ content: tcTokenBuffer,
1018
+ });
1019
+ }
1020
+ if (additionalNodes && additionalNodes.length > 0) {
1021
+ stanza.content.push(...additionalNodes);
1022
+ }
1023
+ const buttonType = getButtonType(message);
1024
+ if (buttonType && !isNewsletter && !isStatus) {
1025
+ const bizNodes = getAdditionalNode(buttonType);
1026
+ stanza.content.push(...bizNodes);
1027
+ }
1028
+ logger.debug(
1029
+ { msgId },
1030
+ `sending message to ${participants.length} devices`,
1031
+ );
1032
+ await sendNode(stanza);
1033
+ // Add message to retry cache if enabled
1034
+ if (messageRetryManager && !participant) {
1035
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1036
+ }
1037
+ }, meId);
1038
+ return msgId;
1039
+ };
1040
+ const getMessageType = (message) => {
1041
+ const normalizedMessage = normalizeMessageContent(message);
1042
+ if (!normalizedMessage) return "text";
1043
+ if (
1044
+ normalizedMessage.reactionMessage ||
1045
+ normalizedMessage.encReactionMessage
1046
+ ) {
1047
+ return "reaction";
1048
+ }
1049
+ if (
1050
+ normalizedMessage.pollCreationMessage ||
1051
+ normalizedMessage.pollCreationMessageV2 ||
1052
+ normalizedMessage.pollCreationMessageV3 ||
1053
+ normalizedMessage.pollUpdateMessage
1054
+ ) {
1055
+ return "poll";
1056
+ }
1057
+ if (normalizedMessage.eventMessage) {
1058
+ return "event";
1059
+ }
1060
+ if (getMediaType(normalizedMessage) !== "") {
1061
+ return "media";
1062
+ }
1063
+ return "text";
1064
+ };
1065
+ const getMediaType = (message) => {
1066
+ if (message.imageMessage) {
1067
+ return "image";
1068
+ } else if (message.videoMessage) {
1069
+ return message.videoMessage.gifPlayback ? "gif" : "video";
1070
+ } else if (message.audioMessage) {
1071
+ return message.audioMessage.ptt ? "ptt" : "audio";
1072
+ } else if (message.contactMessage) {
1073
+ return "vcard";
1074
+ } else if (message.documentMessage) {
1075
+ return "document";
1076
+ } else if (message.contactsArrayMessage) {
1077
+ return "contact_array";
1078
+ } else if (message.liveLocationMessage) {
1079
+ return "livelocation";
1080
+ } else if (message.stickerMessage) {
1081
+ return message.stickerMessage.isLottie
1082
+ ? "1p_sticker"
1083
+ : message.stickerMessage.isAvatar
1084
+ ? "avatar_sticker"
1085
+ : "sticker";
1086
+ } else if (message.listMessage) {
1087
+ return "list";
1088
+ } else if (message.listResponseMessage) {
1089
+ return "list_response";
1090
+ } else if (message.buttonsResponseMessage) {
1091
+ return "buttons_response";
1092
+ } else if (message.orderMessage) {
1093
+ return "order";
1094
+ } else if (message.productMessage) {
1095
+ return "product";
1096
+ } else if (message.interactiveResponseMessage) {
1097
+ return "native_flow_response";
1098
+ } else if (message.groupInviteMessage) {
1099
+ return "url";
1100
+ }
1101
+ return "";
1102
+ };
1103
+ const getPrivacyTokens = async (jids) => {
1104
+ const t = unixTimestampSeconds().toString();
1105
+ const result = await query({
1106
+ tag: "iq",
1107
+ attrs: {
1108
+ to: S_WHATSAPP_NET,
1109
+ type: "set",
1110
+ xmlns: "privacy",
1111
+ },
1112
+ content: [
1113
+ {
1114
+ tag: "tokens",
1115
+ attrs: {},
1116
+ content: jids.map((jid) => ({
1117
+ tag: "token",
963
1118
  attrs: {
964
- to: S_WHATSAPP_NET,
965
- type: 'set',
966
- xmlns: 'privacy'
1119
+ jid: jidNormalizedUser(jid),
1120
+ t,
1121
+ type: "trusted_contact",
967
1122
  },
968
- content: [
969
- {
970
- tag: 'tokens',
971
- attrs: {},
972
- content: jids.map(jid => ({
973
- tag: 'token',
974
- attrs: {
975
- jid: jidNormalizedUser(jid),
976
- t,
977
- type: 'trusted_contact'
978
- }
979
- }))
980
- }
981
- ]
982
- });
983
- return result;
984
- };
985
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
986
- const smgss = new Smgss(waUploadToServer, relayMessage, config, sock);
987
- const getButtonType = (message) => {
988
- if (message.listMessage)
989
- return 'list';
990
- if (message.buttonsMessage)
991
- return 'buttons';
992
- if (message.templateMessage)
993
- return 'template';
994
- if (message.interactiveMessage?.nativeFlowMessage)
995
- return 'native_flow';
996
- if (message.interactiveMessage?.shopStorefrontMessage)
997
- return 'shop';
998
- if (message.interactiveMessage?.collectionMessage)
999
- return 'collection';
1000
- if (message.interactiveMessage?.carouselMessage)
1001
- return 'carousel';
1002
- if (message.interactiveMessage)
1003
- return 'interactive';
1004
- return null;
1005
- };
1006
- const getButtonArgs = (message) => {
1007
- const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
1008
- const firstButtonName = nativeFlow?.buttons?.[0]?.name;
1009
- const nativeFlowSpecials = [
1010
- 'mpm',
1011
- 'cta_catalog',
1012
- 'send_location',
1013
- 'call_permission_request',
1014
- 'wa_payment_transaction_details',
1015
- 'automated_greeting_message_view_catalog'
1016
- ];
1017
- const ts = unixTimestampSeconds().toString();
1018
- const bizBase = { actual_actors: '2', host_storage: '2', privacy_mode_ts: ts };
1019
- const qualityControl = { tag: 'quality_control', attrs: { source_type: 'third_party' } };
1020
- if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1021
- return {
1022
- tag: 'biz',
1023
- attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName }
1024
- };
1025
- }
1026
- else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1027
- return {
1028
- tag: 'biz',
1029
- attrs: bizBase,
1030
- content: [
1031
- {
1032
- tag: 'interactive',
1033
- attrs: { type: 'native_flow', v: '1' },
1034
- content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
1035
- },
1036
- qualityControl
1037
- ]
1038
- };
1039
- }
1040
- else if (nativeFlow || message.buttonsMessage || message.templateMessage || message.interactiveMessage) {
1041
- return {
1042
- tag: 'biz',
1043
- attrs: bizBase,
1044
- content: [
1123
+ })),
1124
+ },
1125
+ ],
1126
+ });
1127
+ return result;
1128
+ };
1129
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1130
+ const ourin = new Dugong(waUploadToServer, relayMessage, config, sock);
1131
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
1132
+ const fetchLinkPreview = (text) =>
1133
+ getUrlInfo(text, {
1134
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1135
+ fetchOpts: {
1136
+ timeout: 3000,
1137
+ ...(httpRequestOptions || {}),
1138
+ },
1139
+ logger,
1140
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined,
1141
+ });
1142
+ const socketWithMessages = {
1143
+ ...sock,
1144
+ getPrivacyTokens,
1145
+ assertSessions,
1146
+ relayMessage,
1147
+ sendReceipt,
1148
+ sendReceipts,
1149
+ ourin,
1150
+ readMessages,
1151
+ refreshMediaConn,
1152
+ waUploadToServer,
1153
+ fetchPrivacySettings,
1154
+ sendPeerDataOperationMessage,
1155
+ createParticipantNodes,
1156
+ getUSyncDevices,
1157
+ messageRetryManager,
1158
+ updateMemberLabel,
1159
+ updateMediaMessage: async (message) => {
1160
+ const content = assertMediaContent(message.message);
1161
+ const mediaKey = content.mediaKey;
1162
+ const meId = authState.creds.me.id;
1163
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1164
+ let error = undefined;
1165
+ await Promise.all([
1166
+ sendNode(node),
1167
+ waitForMsgMediaUpdate(async (update) => {
1168
+ const result = update.find((c) => c.key.id === message.key.id);
1169
+ if (result) {
1170
+ if (result.error) {
1171
+ error = result.error;
1172
+ } else {
1173
+ try {
1174
+ const media = decryptMediaRetryData(
1175
+ result.media,
1176
+ mediaKey,
1177
+ result.key.id,
1178
+ );
1179
+ if (
1180
+ media.result !==
1181
+ proto.MediaRetryNotification.ResultType.SUCCESS
1182
+ ) {
1183
+ const resultStr =
1184
+ proto.MediaRetryNotification.ResultType[media.result];
1185
+ throw new Boom(
1186
+ `Media re-upload failed by device (${resultStr})`,
1045
1187
  {
1046
- tag: 'interactive',
1047
- attrs: { type: 'native_flow', v: '1' },
1048
- content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
1188
+ data: media,
1189
+ statusCode:
1190
+ getStatusCodeForMediaRetry(media.result) || 404,
1049
1191
  },
1050
- qualityControl
1051
- ]
1052
- };
1053
- }
1054
- else if (message.listMessage) {
1055
- return {
1056
- tag: 'biz',
1057
- attrs: bizBase,
1058
- content: [{ tag: 'list', attrs: { v: '2', type: 'product_list' } }, qualityControl]
1059
- };
1060
- }
1061
- return { tag: 'biz', attrs: bizBase };
1062
- };
1063
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1064
- registerSocketEndHandler(() => {
1065
- if (!config.userDevicesCache && userDevicesCache.close) {
1066
- userDevicesCache.close();
1067
- }
1068
- mediaConn = undefined;
1069
- if (messageRetryManager) {
1070
- messageRetryManager.clear();
1071
- }
1072
- });
1073
- const sendStatusWhatsApp = async (content, jids = []) => {
1074
- const userJid = jidNormalizedUser(authState.creds.me.id);
1075
- const allUsers = new Set([userJid]);
1076
- for (const id of jids) {
1077
- if (isJidGroup(id)) {
1078
- try {
1079
- const metadata = await groupMetadata(id);
1080
- metadata.participants.forEach(p => allUsers.add(jidNormalizedUser(p.id)));
1081
- }
1082
- catch (error) {
1083
- logger.error(`Error getting metadata for group ${id}: ${error}`);
1192
+ );
1084
1193
  }
1194
+ content.directPath = media.directPath;
1195
+ content.url = getUrlFromDirectPath(content.directPath);
1196
+ logger.debug(
1197
+ { directPath: media.directPath, key: result.key },
1198
+ "media update successful",
1199
+ );
1200
+ } catch (err) {
1201
+ error = err;
1202
+ }
1085
1203
  }
1086
- else if (isPnUser(id)) {
1087
- allUsers.add(jidNormalizedUser(id));
1088
- }
1204
+ return true;
1205
+ }
1206
+ }),
1207
+ ]);
1208
+ if (error) {
1209
+ throw error;
1210
+ }
1211
+ ev.emit("messages.update", [
1212
+ { key: message.key, update: { message: message.message } },
1213
+ ]);
1214
+ return message;
1215
+ },
1216
+ sendStatusMention: async (content, jids = []) => {
1217
+ return await ourin.sendStatusWhatsApp(content, jids);
1218
+ },
1219
+ swgc: async (jid, content, options = {}) => {
1220
+ if (!isJidGroup(jid)) {
1221
+ throw new Boom("JID must be a group", { statusCode: 400 });
1222
+ }
1223
+ const storyContent = { groupStatusMessage: content };
1224
+ return await ourin.handleGroupStory(storyContent, jid, null);
1225
+ },
1226
+ sendPreview: async (jid, preview, options = {}) => {
1227
+ const extContent = {
1228
+ text: preview.caption || preview.text || "",
1229
+ matchedText: preview.matchedText || preview.url || "",
1230
+ previewType: preview.previewType ?? 0,
1231
+ };
1232
+ if (preview.title) extContent.title = preview.title;
1233
+ if (preview.description) extContent.description = preview.description;
1234
+ if (preview.inviteLinkGroupTypeV2)
1235
+ extContent.inviteLinkGroupTypeV2 = preview.inviteLinkGroupTypeV2;
1236
+ if (preview.image) {
1237
+ let imgBuf = preview.image;
1238
+ if (typeof imgBuf === "string" && imgBuf.startsWith("http")) {
1239
+ try {
1240
+ const resp = await fetch(imgBuf);
1241
+ imgBuf = Buffer.from(await resp.arrayBuffer());
1242
+ } catch {}
1089
1243
  }
1090
- const uniqueUsers = Array.from(allUsers);
1091
- const getRandomHexColor = () => '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
1092
- const isMedia = !!(content.image || content.video || content.audio);
1093
- const isAudio = !!content.audio;
1094
- const messageContent = { ...content };
1095
- if (isMedia && !isAudio) {
1096
- if (messageContent.text) {
1097
- messageContent.caption = messageContent.text;
1098
- delete messageContent.text;
1244
+ if (Buffer.isBuffer(imgBuf)) {
1245
+ try {
1246
+ const { imageMessage } = await prepareWAMessageMedia(
1247
+ { image: imgBuf },
1248
+ { upload: waUploadToServer, mediaTypeOverride: "thumbnail-link" },
1249
+ );
1250
+ if (imageMessage) {
1251
+ extContent.jpegThumbnail = imageMessage.jpegThumbnail;
1252
+ if (imageMessage.directPath)
1253
+ extContent.thumbnailDirectPath = imageMessage.directPath;
1254
+ if (imageMessage.mediaKey)
1255
+ extContent.mediaKey = imageMessage.mediaKey;
1256
+ if (imageMessage.mediaKeyTimestamp)
1257
+ extContent.mediaKeyTimestamp = imageMessage.mediaKeyTimestamp;
1258
+ if (imageMessage.fileSha256)
1259
+ extContent.thumbnailSha256 = imageMessage.fileSha256;
1260
+ if (imageMessage.fileEncSha256)
1261
+ extContent.thumbnailEncSha256 = imageMessage.fileEncSha256;
1262
+ if (imageMessage.width)
1263
+ extContent.thumbnailWidth = imageMessage.width;
1264
+ if (imageMessage.height)
1265
+ extContent.thumbnailHeight = imageMessage.height;
1099
1266
  }
1100
- delete messageContent.ptt;
1101
- delete messageContent.font;
1102
- delete messageContent.backgroundColor;
1103
- delete messageContent.textColor;
1267
+ } catch {
1268
+ extContent.jpegThumbnail = imgBuf;
1269
+ }
1270
+ } else {
1271
+ extContent.jpegThumbnail = imgBuf;
1104
1272
  }
1105
- if (isAudio) {
1106
- delete messageContent.text;
1107
- delete messageContent.caption;
1108
- delete messageContent.font;
1109
- delete messageContent.textColor;
1273
+ } else if (preview.jpegThumbnail) {
1274
+ extContent.jpegThumbnail = preview.jpegThumbnail;
1275
+ }
1276
+ if (preview.thumbnailHeight)
1277
+ extContent.thumbnailHeight = preview.thumbnailHeight;
1278
+ if (preview.thumbnailWidth)
1279
+ extContent.thumbnailWidth = preview.thumbnailWidth;
1280
+ if (options.quoted) {
1281
+ const participant = options.quoted.key.fromMe
1282
+ ? authState.creds.me.id
1283
+ : options.quoted.participant ||
1284
+ options.quoted.key.participant ||
1285
+ options.quoted.key.remoteJid;
1286
+ extContent.contextInfo = {
1287
+ stanzaId: options.quoted.key.id,
1288
+ participant,
1289
+ quotedMessage: options.quoted.message,
1290
+ };
1291
+ }
1292
+ if (options.contextInfo) {
1293
+ extContent.contextInfo = {
1294
+ ...extContent.contextInfo,
1295
+ ...options.contextInfo,
1296
+ };
1297
+ }
1298
+ const messageId = generateMessageIDV2(sock.user?.id);
1299
+ await relayMessage(
1300
+ jid,
1301
+ { extendedTextMessage: extContent },
1302
+ { messageId },
1303
+ );
1304
+ return messageId;
1305
+ },
1306
+ // Aku tau kamu pasti bakalan nyari ini, tapi gak papa deh
1307
+ // support ourin terus yahh kawan kawan
1308
+ // @Zann
1309
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1310
+ const { message, messageId } = generateTableContent(
1311
+ title,
1312
+ headers,
1313
+ rows,
1314
+ quoted,
1315
+ options,
1316
+ );
1317
+ await relayMessage(jid, message, { messageId });
1318
+ return { message, messageId };
1319
+ },
1320
+ sendTableV2: async (jid, table, quoted, options = {}) => {
1321
+ const { message, messageId } = generateTableContentV2(
1322
+ table,
1323
+ quoted,
1324
+ options,
1325
+ );
1326
+ await relayMessage(jid, message, { messageId });
1327
+ return { message, messageId };
1328
+ },
1329
+ sendList: async (jid, title, items, quoted, options = {}) => {
1330
+ const { message, messageId } = generateListContent(
1331
+ title,
1332
+ items,
1333
+ quoted,
1334
+ options,
1335
+ );
1336
+ await relayMessage(jid, message, { messageId });
1337
+ return { message, messageId };
1338
+ },
1339
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1340
+ const { message, messageId } = generateCodeBlockContent(
1341
+ code,
1342
+ quoted,
1343
+ options,
1344
+ );
1345
+ await relayMessage(jid, message, { messageId });
1346
+ return { message, messageId };
1347
+ },
1348
+ sendCodeBlockV2: async (jid, code, quoted, options = {}) => {
1349
+ const { message, messageId } = generateCodeBlockContentV2(
1350
+ code,
1351
+ quoted,
1352
+ options,
1353
+ );
1354
+ await relayMessage(jid, message, { messageId });
1355
+ return { message, messageId };
1356
+ },
1357
+ sendLink: async (jid, text, links, quoted, options = {}) => {
1358
+ const { message, messageId } = generateLinkContent(
1359
+ text,
1360
+ links,
1361
+ quoted,
1362
+ options,
1363
+ );
1364
+ await relayMessage(jid, message, { messageId });
1365
+ return { message, messageId };
1366
+ },
1367
+ sendLinkV2: async (jid, text, links, quoted, options = {}) => {
1368
+ const { message, messageId } = generateLinkContentV2(
1369
+ text,
1370
+ links,
1371
+ quoted,
1372
+ options,
1373
+ );
1374
+ await relayMessage(jid, message, { messageId });
1375
+ return { message, messageId };
1376
+ },
1377
+ sendLatex: async (jid, quoted, options) => {
1378
+ const { message, messageId } = generateLatexContent(quoted, options);
1379
+ await relayMessage(jid, message, { messageId });
1380
+ return { message, messageId };
1381
+ },
1382
+ sendLatexImage: async (
1383
+ jid,
1384
+ quoted,
1385
+ options,
1386
+ renderLatexToPng,
1387
+ uploadFn,
1388
+ ) => {
1389
+ const { message, messageId } = await generateLatexImageContent(
1390
+ quoted,
1391
+ options,
1392
+ uploadFn,
1393
+ renderLatexToPng,
1394
+ );
1395
+ await relayMessage(jid, message, { messageId });
1396
+ return { message, messageId };
1397
+ },
1398
+ sendLatexInlineImage: async (
1399
+ jid,
1400
+ quoted,
1401
+ options,
1402
+ renderLatexToPng,
1403
+ uploadFn,
1404
+ ) => {
1405
+ const { message, messageId } = await generateLatexInlineImageContent(
1406
+ quoted,
1407
+ options,
1408
+ uploadFn,
1409
+ renderLatexToPng,
1410
+ );
1411
+ await relayMessage(jid, message, { messageId });
1412
+ return { message, messageId };
1413
+ },
1414
+ captureUnifiedResponse,
1415
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1416
+ const { message, messageId } = generateUnifiedResponseContent(
1417
+ quoted,
1418
+ captured,
1419
+ );
1420
+ await relayMessage(jid, message, { messageId });
1421
+ return { message, messageId };
1422
+ },
1423
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1424
+ const { message, messageId } = generateRichMessageContent(
1425
+ submessages,
1426
+ quoted,
1427
+ );
1428
+ await relayMessage(jid, message, { messageId });
1429
+ return { message, messageId };
1430
+ },
1431
+ sendMessage: async (jid, content, options = {}) => {
1432
+ const userJid = authState.creds.me.id;
1433
+ const { quoted } = options;
1434
+ const messageType = ourin.detectType(content);
1435
+ if (
1436
+ typeof content === "object" &&
1437
+ "disappearingMessagesInChat" in content &&
1438
+ typeof content["disappearingMessagesInChat"] !== "undefined" &&
1439
+ isJidGroup(jid)
1440
+ ) {
1441
+ const { disappearingMessagesInChat } = content;
1442
+ const value =
1443
+ typeof disappearingMessagesInChat === "boolean"
1444
+ ? disappearingMessagesInChat
1445
+ ? WA_DEFAULT_EPHEMERAL
1446
+ : 0
1447
+ : disappearingMessagesInChat;
1448
+ await groupToggleEphemeral(jid, value);
1449
+ } else if (messageType) {
1450
+ switch (messageType) {
1451
+ case "PAYMENT": {
1452
+ const paymentContent = await ourin.handlePayment(content, quoted);
1453
+ return await relayMessage(jid, paymentContent, {
1454
+ messageId: generateMessageIDV2(userJid),
1455
+ });
1456
+ }
1457
+ case "PRODUCT": {
1458
+ const productContent = await ourin.handleProduct(
1459
+ content,
1460
+ jid,
1461
+ quoted,
1462
+ );
1463
+ const productMsg = await generateWAMessageFromContent(
1464
+ jid,
1465
+ productContent,
1466
+ { quoted, userJid },
1467
+ );
1468
+ return await relayMessage(jid, productMsg.message, {
1469
+ messageId: productMsg.key.id,
1470
+ });
1471
+ }
1472
+ case "CAROUSEL": {
1473
+ const carouselContent = await ourin.handleCarousel(
1474
+ content,
1475
+ jid,
1476
+ quoted,
1477
+ );
1478
+ const carouselMsg = await generateWAMessageFromContent(
1479
+ jid,
1480
+ carouselContent,
1481
+ { quoted, userJid },
1482
+ );
1483
+ return await relayMessage(jid, carouselMsg.message, {
1484
+ messageId: carouselMsg.key.id,
1485
+ });
1486
+ }
1487
+ case "INTERACTIVE": {
1488
+ const interactiveContent = await ourin.handleInteractive(
1489
+ content,
1490
+ jid,
1491
+ quoted,
1492
+ );
1493
+ const interactiveMsg = await generateWAMessageFromContent(
1494
+ jid,
1495
+ interactiveContent,
1496
+ { quoted, userJid },
1497
+ );
1498
+ return await relayMessage(jid, interactiveMsg.message, {
1499
+ messageId: interactiveMsg.key.id,
1500
+ });
1501
+ }
1502
+ case "INTERACTIVE_BUTTONS": {
1503
+ const ibContent = await ourin.handleInteractiveButtons(
1504
+ content,
1505
+ jid,
1506
+ quoted,
1507
+ );
1508
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, {
1509
+ quoted,
1510
+ userJid,
1511
+ });
1512
+ return await relayMessage(jid, ibMsg.message, {
1513
+ messageId: ibMsg.key.id,
1514
+ });
1515
+ }
1516
+ case "ALBUM":
1517
+ return await ourin.handleAlbum(content, jid, quoted);
1518
+ case "EVENT":
1519
+ return await ourin.handleEvent(content, jid, quoted);
1520
+ case "POLL_RESULT":
1521
+ return await ourin.handlePollResult(content, jid, quoted);
1522
+ case "GROUP_STORY":
1523
+ return await ourin.handleGroupStory(content, jid, quoted, options);
1110
1524
  }
1111
- const font = !isMedia ? messageContent.font ?? Math.floor(Math.random() * 9) : undefined;
1112
- const textColor = !isMedia ? messageContent.textColor ?? getRandomHexColor() : undefined;
1113
- const backgroundColor = !isMedia || isAudio ? messageContent.backgroundColor ?? getRandomHexColor() : undefined;
1114
- const ptt = isAudio ? (typeof messageContent.ptt === 'boolean' ? messageContent.ptt : true) : undefined;
1115
- const msg = await generateWAMessage(STORIES_JID, messageContent, {
1116
- logger,
1117
- userJid,
1118
- getUrlInfo: (text) => getUrlInfo(text, {
1119
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1120
- fetchOpts: { timeout: 3000, ...httpRequestOptions },
1121
- logger,
1122
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1525
+ } else {
1526
+ let mediaHandle;
1527
+ const fullMsg = await generateWAMessage(jid, content, {
1528
+ logger,
1529
+ userJid,
1530
+ getUrlInfo: (text) =>
1531
+ getUrlInfo(text, {
1532
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1533
+ fetchOpts: {
1534
+ timeout: 3000,
1535
+ ...(httpRequestOptions || {}),
1536
+ },
1537
+ logger,
1538
+ uploadImage: generateHighQualityLinkPreview
1539
+ ? waUploadToServer
1540
+ : undefined,
1123
1541
  }),
1124
- upload: waUploadToServer,
1125
- mediaCache: config.mediaCache,
1126
- options: config.options,
1127
- font,
1128
- textColor,
1129
- backgroundColor,
1130
- ptt
1131
- });
1132
- await relayMessage(STORIES_JID, msg.message, {
1133
- messageId: msg.key.id,
1134
- statusJidList: uniqueUsers,
1135
- additionalNodes: [
1136
- {
1137
- tag: 'meta',
1138
- attrs: {},
1139
- content: [
1140
- {
1141
- tag: 'mentioned_users',
1142
- attrs: {},
1143
- content: jids.map(jid => ({ tag: 'to', attrs: { jid: jidNormalizedUser(jid) } }))
1144
- }
1145
- ]
1146
- }
1147
- ]
1542
+ getProfilePicUrl: sock.profilePictureUrl,
1543
+ getCallLink: sock.createCallLink,
1544
+ upload: async (readStream, opts) => {
1545
+ const up = await waUploadToServer(readStream, {
1546
+ ...opts,
1547
+ newsletter: isJidNewsletter(jid),
1548
+ });
1549
+ return up;
1550
+ },
1551
+ mediaCache: config.mediaCache,
1552
+ options: config.options,
1553
+ messageId: generateMessageIDV2(sock.user?.id),
1554
+ ...options,
1148
1555
  });
1149
- for (const id of jids) {
1150
- try {
1151
- const normalizedId = jidNormalizedUser(id);
1152
- if (normalizedId === userJid)
1153
- continue;
1154
- const isPrivate = isPnUser(normalizedId);
1155
- const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
1156
- const protocolMessage = {
1157
- [type]: {
1158
- message: {
1159
- protocolMessage: {
1160
- key: msg.key,
1161
- type: 25
1162
- }
1163
- }
1164
- },
1165
- messageContextInfo: {
1166
- messageSecret: randomBytes(32)
1167
- }
1168
- };
1169
- const statusMsg = await generateWAMessageFromContent(normalizedId, protocolMessage, {
1170
- userJid
1171
- });
1172
- await relayMessage(normalizedId, statusMsg.message, {
1173
- additionalNodes: [
1174
- {
1175
- tag: 'meta',
1176
- attrs: isPrivate ? { is_status_mention: 'true' } : { is_group_status_mention: 'true' }
1177
- }
1178
- ]
1179
- });
1180
- await delay(2000);
1181
- }
1182
- catch (error) {
1183
- logger.error(`Error sending status mention to ${id}: ${error}`);
1184
- }
1556
+ const isEventMsg = "event" in content && !!content.event;
1557
+ const isDeleteMsg = "delete" in content && !!content.delete;
1558
+ const isEditMsg = "edit" in content && !!content.edit;
1559
+ const isPinMsg = "pin" in content && !!content.pin;
1560
+ const isPollMessage = "poll" in content && !!content.poll;
1561
+ const isAiMsg = "ai" in content && !!content.ai;
1562
+ const additionalAttributes = {};
1563
+ const additionalNodes = [];
1564
+ if (isDeleteMsg) {
1565
+ const fromMe = content.delete?.fromMe;
1566
+ const isGroup = isJidGroup(content.delete?.remoteJid);
1567
+ additionalAttributes.edit =
1568
+ (isGroup && !fromMe) || isJidNewsletter(jid) ? "8" : "7";
1569
+ } else if (isEditMsg) {
1570
+ additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
1571
+ } else if (isPinMsg) {
1572
+ additionalAttributes.edit = "2";
1573
+ } else if (isPollMessage) {
1574
+ additionalNodes.push({
1575
+ tag: "meta",
1576
+ attrs: { polltype: "creation" },
1577
+ });
1578
+ } else if (isEventMsg) {
1579
+ additionalNodes.push({
1580
+ tag: "meta",
1581
+ attrs: { event_type: "creation" },
1582
+ });
1583
+ } else if (isAiMsg) {
1584
+ additionalNodes.push({
1585
+ tag: "bot",
1586
+ attrs: { biz_bot: "1" },
1587
+ });
1185
1588
  }
1186
- return msg;
1187
- };
1188
- return {
1189
- ...sock,
1190
- userDevicesCache,
1191
- devicesMutex,
1192
- issuePrivacyTokens,
1193
- assertSessions,
1194
- relayMessage,
1195
- sendStatusWhatsApp,
1196
- sendReceipt,
1197
- sendReceipts,
1198
- readMessages,
1199
- refreshMediaConn,
1200
- resize: resizeImage,
1201
- convert: convertMedia,
1202
- toSticker: imageToWebpSticker,
1203
- compress: compressMedia,
1204
- metadata: getMediaMetadata,
1205
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1206
- getMediaHost: () => mediaHost,
1207
- waUploadToServer,
1208
- fetchPrivacySettings,
1209
- sendPeerDataOperationMessage,
1210
- createParticipantNodes,
1211
- getUSyncDevices,
1212
- messageRetryManager,
1213
- updateMemberLabel,
1214
- updateMediaMessage: async (message) => {
1215
- const content = assertMediaContent(message.message);
1216
- const mediaKey = content.mediaKey;
1217
- const meId = authState.creds.me.id;
1218
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1219
- let error = undefined;
1220
- await Promise.all([
1221
- sendNode(node),
1222
- waitForMsgMediaUpdate(async (update) => {
1223
- const result = update.find(c => c.key.id === message.key.id);
1224
- if (result) {
1225
- if (result.error) {
1226
- error = result.error;
1227
- }
1228
- else {
1229
- try {
1230
- const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1231
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1232
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1233
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1234
- data: media,
1235
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
1236
- });
1237
- }
1238
- content.directPath = media.directPath;
1239
- content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1240
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1241
- }
1242
- catch (err) {
1243
- error = err;
1244
- }
1245
- }
1246
- return true;
1247
- }
1248
- })
1249
- ]);
1250
- if (error) {
1251
- throw error;
1252
- }
1253
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1254
- return message;
1255
- },
1256
- captureUnifiedResponse,
1257
- sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1258
- const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1259
- await relayMessage(jid, message, { messageId });
1260
- return { message, messageId };
1261
- },
1262
- sendList: async (jid, title, items, quoted, options = {}) => {
1263
- const { message, messageId } = generateListContent(title, items, quoted, options);
1264
- await relayMessage(jid, message, { messageId });
1265
- return { message, messageId };
1266
- },
1267
- sendCodeBlock: async (jid, code, quoted, options = {}) => {
1268
- const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1269
- await relayMessage(jid, message, { messageId });
1270
- return { message, messageId };
1271
- },
1272
- sendLatex: async (jid, quoted, options) => {
1273
- const { message, messageId } = generateLatexContent(quoted, options);
1274
- await relayMessage(jid, message, { messageId });
1275
- return { message, messageId };
1276
- },
1277
- sendUnifiedResponse: async (jid, quoted, captured) => {
1278
- const { message, messageId } = generateUnifiedResponseContent(quoted, captured);
1279
- await relayMessage(jid, message, { messageId });
1280
- return { message, messageId };
1281
- },
1282
- sendRichMessage: async (jid, submessages, quoted) => {
1283
- const { message, messageId } = generateRichMessageContent(submessages, quoted);
1284
- await relayMessage(jid, message, { messageId });
1285
- return { message, messageId };
1286
- },
1287
- sendMessage: async (jid, content, options = {}) => {
1288
- const userJid = authState.creds.me.id;
1289
- const smgssType = smgss.detectType(content);
1290
- if (smgssType) {
1291
- const quoted = options?.quoted;
1292
- const built = await smgss.handle(smgssType, content, jid, quoted);
1293
- if (smgssType === 'ALBUM' || smgssType === 'EVENT' || smgssType === 'POLL_RESULT' || smgssType === 'GROUP_STORY') {
1294
- return built;
1295
- }
1296
- content = built;
1297
- }
1298
- if (typeof content === 'object' &&
1299
- 'disappearingMessagesInChat' in content &&
1300
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1301
- isJidGroup(jid)) {
1302
- const { disappearingMessagesInChat } = content;
1303
- const value = typeof disappearingMessagesInChat === 'boolean'
1304
- ? disappearingMessagesInChat
1305
- ? WA_DEFAULT_EPHEMERAL
1306
- : 0
1307
- : disappearingMessagesInChat;
1308
- await groupToggleEphemeral(jid, value);
1309
- }
1310
- else {
1311
- const fullMsg = await generateWAMessage(jid, content, {
1312
- logger,
1313
- userJid,
1314
- getUrlInfo: text => getUrlInfo(text, {
1315
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1316
- fetchOpts: {
1317
- timeout: 3000,
1318
- ...(httpRequestOptions || {})
1319
- },
1320
- logger,
1321
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1322
- }),
1323
- //TODO: CACHE
1324
- getProfilePicUrl: sock.profilePictureUrl,
1325
- getCallLink: sock.createCallLink,
1326
- upload: waUploadToServer,
1327
- mediaCache: config.mediaCache,
1328
- options: config.options,
1329
- messageId: generateMessageIDV2(sock.user?.id),
1330
- ...options
1331
- });
1332
- const isEventMsg = 'event' in content && !!content.event;
1333
- const isDeleteMsg = 'delete' in content && !!content.delete;
1334
- const isEditMsg = 'edit' in content && !!content.edit;
1335
- const isPinMsg = 'pin' in content && !!content.pin;
1336
- const isPollMessage = 'poll' in content && !!content.poll;
1337
- const isAiMsg = 'ai' in content && !!content.ai;
1338
- const additionalAttributes = {};
1339
- const additionalNodes = [];
1340
- // required for delete
1341
- if (isDeleteMsg) {
1342
- // if the chat is a group, and I am not the author, then delete the message as an admin
1343
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1344
- additionalAttributes.edit = '8';
1345
- }
1346
- else {
1347
- additionalAttributes.edit = '7';
1348
- }
1349
- }
1350
- else if (isEditMsg) {
1351
- additionalAttributes.edit = '1';
1352
- }
1353
- else if (isPinMsg) {
1354
- additionalAttributes.edit = '2';
1355
- }
1356
- else if (isPollMessage) {
1357
- additionalNodes.push({
1358
- tag: 'meta',
1359
- attrs: {
1360
- polltype: 'creation'
1361
- }
1362
- });
1363
- }
1364
- else if (isEventMsg) {
1365
- additionalNodes.push({
1366
- tag: 'meta',
1367
- attrs: {
1368
- event_type: 'creation'
1369
- }
1370
- });
1371
- }
1372
- else if (isAiMsg) {
1373
- if (!(isPnUser(jid) || isLidUser(jid))) {
1374
- throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1375
- }
1376
- if (fullMsg.message) {
1377
- fullMsg.message.messageContextInfo = {
1378
- ...(fullMsg.message.messageContextInfo || {}),
1379
- supportPayload: BIZ_BOT_SUPPORT_PAYLOAD
1380
- };
1381
- }
1382
- additionalNodes.push({
1383
- tag: 'bot',
1384
- attrs: {
1385
- biz_bot: '1'
1386
- }
1387
- });
1388
- delete content.ai;
1389
- }
1390
- const buttonType = getButtonType(fullMsg.message);
1391
- if (buttonType) {
1392
- const btnNode = getButtonArgs(fullMsg.message);
1393
- if (btnNode)
1394
- additionalNodes.push(btnNode);
1395
- }
1396
- await relayMessage(jid, fullMsg.message, {
1397
- messageId: fullMsg.key.id,
1398
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1399
- additionalAttributes,
1400
- statusJidList: options.statusJidList,
1401
- additionalNodes
1402
- });
1403
- if (config.emitOwnEvents) {
1404
- process.nextTick(async () => {
1405
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1406
- });
1407
- }
1408
- return fullMsg;
1409
- }
1589
+ await relayMessage(jid, fullMsg.message, {
1590
+ messageId: fullMsg.key.id,
1591
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1592
+ additionalAttributes,
1593
+ statusJidList: options.statusJidList,
1594
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
1595
+ });
1596
+ if (config.emitOwnEvents) {
1597
+ process.nextTick(async () => {
1598
+ await messageMutex.mutex(() => upsertMessage(fullMsg, "append"));
1599
+ });
1410
1600
  }
1411
- };
1601
+ return fullMsg;
1602
+ }
1603
+ },
1604
+ };
1605
+ return {
1606
+ ...socketWithMessages,
1607
+ // Botones nativos (quick reply, url, call, copy, reminder, listas) —
1608
+ // ver ./native-buttons.js. Se enganchan al final porque dependen de
1609
+ // sendMessage, que ya existe en socketWithMessages.
1610
+ ...makeNativeButtons(socketWithMessages, fetchLinkPreview),
1611
+ };
1412
1612
  };
1413
- //# sourceMappingURL=messages-send.js.map
1613
+ //# sourceMappingURL=messages-send.js.map