@vinzsocket/baileys 3.3.0 → 3.3.1

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