@badzz88/baileys 8.4.6 → 8.4.9

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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +850 -32
  4. package/WAProto/index.d.ts +4913 -25
  5. package/WAProto/index.js +14074 -98
  6. package/package.json +96 -131
  7. package/src/Defaults/index.js +201 -0
  8. package/src/Defaults/phonenumber-mcc.json +223 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +92 -0
  11. package/src/Signal/Group/group_cipher.js +89 -0
  12. package/src/Signal/Group/index.js +136 -0
  13. package/src/Signal/Group/keyhelper.js +73 -0
  14. package/src/Signal/Group/sender-chain-key.js +32 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +50 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +97 -0
  20. package/src/Signal/Group/sender-message-key.js +30 -0
  21. package/src/Signal/libsignal.js +470 -0
  22. package/src/Signal/lid-mapping.js +262 -0
  23. package/src/Socket/Client/index.js +30 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +62 -0
  26. package/src/Socket/aigroups.js +240 -0
  27. package/src/Socket/business.js +422 -0
  28. package/src/Socket/chats.js +2374 -0
  29. package/src/Socket/communities.js +580 -0
  30. package/src/Socket/graphql.js +915 -0
  31. package/src/Socket/groups.js +812 -0
  32. package/src/Socket/index.js +37 -0
  33. package/src/Socket/interactive-handler.js +579 -0
  34. package/src/Socket/interop.js +566 -0
  35. package/src/Socket/managed-account.js +214 -0
  36. package/src/Socket/messages-recv.js +3012 -0
  37. package/src/Socket/messages-send.js +2163 -0
  38. package/{lib → src}/Socket/mex.js +11 -5
  39. package/src/Socket/newsletter.js +1057 -0
  40. package/src/Socket/privacy.js +452 -0
  41. package/src/Socket/registration.js +434 -0
  42. package/src/Socket/socket.js +1079 -0
  43. package/src/Socket/text-router.js +67 -0
  44. package/src/Socket/username.js +234 -0
  45. package/src/Store/index.js +36 -0
  46. package/src/Store/make-cache-manager-store.js +90 -0
  47. package/src/Store/make-in-memory-store.js +506 -0
  48. package/src/Store/make-ordered-dictionary.js +81 -0
  49. package/src/Store/object-repository.js +29 -0
  50. package/src/Types/Auth.js +38 -0
  51. package/src/Types/Bussines.js +2 -0
  52. package/src/Types/Call.js +2 -0
  53. package/src/Types/Chat.js +4 -0
  54. package/src/Types/Contact.js +2 -0
  55. package/src/Types/Events.js +2 -0
  56. package/src/Types/GroupMetadata.js +2 -0
  57. package/src/Types/Label.js +27 -0
  58. package/src/Types/LabelAssociation.js +9 -0
  59. package/src/Types/Message.js +95 -0
  60. package/src/Types/Newsletter.js +152 -0
  61. package/src/Types/Product.js +2 -0
  62. package/src/Types/Signal.js +2 -0
  63. package/src/Types/Socket.js +2 -0
  64. package/src/Types/State.js +70 -0
  65. package/src/Types/USync.js +2 -0
  66. package/src/Types/index.js +54 -0
  67. package/src/Utils/auth-utils.js +306 -0
  68. package/src/Utils/browser-utils.js +114 -0
  69. package/src/Utils/business.js +247 -0
  70. package/src/Utils/chat-utils.js +1272 -0
  71. package/src/Utils/consumer-application.js +107 -0
  72. package/src/Utils/crypto.js +125 -0
  73. package/src/Utils/decode-wa-message.js +808 -0
  74. package/src/Utils/event-buffer.js +586 -0
  75. package/src/Utils/generics.js +640 -0
  76. package/src/Utils/group-history.js +60 -0
  77. package/src/Utils/history.js +244 -0
  78. package/src/Utils/identity-change-handler.js +52 -0
  79. package/src/Utils/index.js +53 -0
  80. package/src/Utils/jid-display-normalization.js +218 -0
  81. package/src/Utils/link-preview.js +143 -0
  82. package/src/Utils/logger.js +9 -0
  83. package/src/Utils/lt-hash.js +10 -0
  84. package/src/Utils/make-mutex.js +36 -0
  85. package/src/Utils/message-composer.js +479 -0
  86. package/src/Utils/message-inspect.js +400 -0
  87. package/src/Utils/message-retry-manager.js +231 -0
  88. package/src/Utils/messages-media.js +943 -0
  89. package/src/Utils/messages.js +2490 -0
  90. package/src/Utils/meta-ai-msmsg.js +133 -0
  91. package/src/Utils/noise-handler.js +194 -0
  92. package/src/Utils/offline-node-processor.js +42 -0
  93. package/src/Utils/pre-key-manager.js +107 -0
  94. package/src/Utils/process-message.js +1047 -0
  95. package/src/Utils/reporting-utils.js +262 -0
  96. package/src/Utils/signal.js +192 -0
  97. package/src/Utils/stanza-ack.js +74 -0
  98. package/src/Utils/sync-action-utils.js +54 -0
  99. package/src/Utils/tc-token-utils.js +161 -0
  100. package/src/Utils/use-multi-file-auth-state.js +121 -0
  101. package/src/Utils/validate-connection.js +248 -0
  102. package/src/Utils/voip-rekey.js +22 -0
  103. package/src/WABinary/constants.js +1304 -0
  104. package/src/WABinary/decode.js +377 -0
  105. package/src/WABinary/encode.js +58 -0
  106. package/src/WABinary/generic-utils.js +148 -0
  107. package/src/WABinary/index.js +33 -0
  108. package/src/WABinary/jid-utils.js +374 -0
  109. package/src/WABinary/types.js +2 -0
  110. package/src/WAM/BinaryInfo.js +13 -0
  111. package/src/WAM/constants.js +39486 -0
  112. package/src/WAM/encode.js +142 -0
  113. package/src/WAM/index.js +31 -0
  114. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  115. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  116. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  117. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  118. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  119. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  120. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  121. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  122. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  123. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  124. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  125. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  126. package/src/WAUSync/Protocols/index.js +40 -0
  127. package/src/WAUSync/USyncBackoff.js +31 -0
  128. package/src/WAUSync/USyncQuery.js +204 -0
  129. package/src/WAUSync/USyncUser.js +58 -0
  130. package/src/WAUSync/index.js +32 -0
  131. package/src/antiban.js +4726 -0
  132. package/{lib → src}/index.js +48 -16
  133. package/lib/Defaults/baileys-version.json +0 -3
  134. package/lib/Defaults/index.js +0 -137
  135. package/lib/Defaults/phonenumber-mcc.json +0 -223
  136. package/lib/Signal/Group/Protocols.js +0 -269
  137. package/lib/Signal/Group/ciphertext-message.js +0 -12
  138. package/lib/Signal/Group/group-session-builder.js +0 -30
  139. package/lib/Signal/Group/group_cipher.js +0 -82
  140. package/lib/Signal/Group/index.js +0 -12
  141. package/lib/Signal/Group/keyhelper.js +0 -18
  142. package/lib/Signal/Group/queue-job.js +0 -57
  143. package/lib/Signal/Group/sender-chain-key.js +0 -26
  144. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  145. package/lib/Signal/Group/sender-key-message.js +0 -66
  146. package/lib/Signal/Group/sender-key-name.js +0 -48
  147. package/lib/Signal/Group/sender-key-record.js +0 -41
  148. package/lib/Signal/Group/sender-key-state.js +0 -84
  149. package/lib/Signal/Group/sender-message-key.js +0 -26
  150. package/lib/Signal/libsignal.js +0 -432
  151. package/lib/Signal/lid-mapping.js +0 -277
  152. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  153. package/lib/Socket/Client/index.js +0 -3
  154. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  155. package/lib/Socket/Client/types.js +0 -11
  156. package/lib/Socket/Client/web-socket-client.js +0 -62
  157. package/lib/Socket/Client/websocket.js +0 -54
  158. package/lib/Socket/business.js +0 -379
  159. package/lib/Socket/chats.js +0 -1193
  160. package/lib/Socket/communities.js +0 -431
  161. package/lib/Socket/community.js +0 -392
  162. package/lib/Socket/dugong.js +0 -637
  163. package/lib/Socket/groups.js +0 -374
  164. package/lib/Socket/index.js +0 -12
  165. package/lib/Socket/luxu.js +0 -387
  166. package/lib/Socket/messages-recv.js +0 -1916
  167. package/lib/Socket/messages-send.js +0 -1459
  168. package/lib/Socket/newsletter.js +0 -253
  169. package/lib/Socket/registration.js +0 -167
  170. package/lib/Socket/socket.js +0 -950
  171. package/lib/Socket/username.js +0 -146
  172. package/lib/Socket/usync.js +0 -69
  173. package/lib/Store/index.js +0 -10
  174. package/lib/Store/keyed-db.js +0 -108
  175. package/lib/Store/make-cache-manager-store.js +0 -85
  176. package/lib/Store/make-in-memory-store.js +0 -198
  177. package/lib/Store/make-ordered-dictionary.js +0 -75
  178. package/lib/Store/object-repository.js +0 -32
  179. package/lib/Types/Auth.js +0 -2
  180. package/lib/Types/Bussines.js +0 -2
  181. package/lib/Types/Call.js +0 -2
  182. package/lib/Types/Chat.js +0 -8
  183. package/lib/Types/Contact.js +0 -2
  184. package/lib/Types/Events.js +0 -2
  185. package/lib/Types/GroupMetadata.js +0 -2
  186. package/lib/Types/Label.js +0 -25
  187. package/lib/Types/LabelAssociation.js +0 -7
  188. package/lib/Types/Message.js +0 -11
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Newsletter.js +0 -38
  191. package/lib/Types/Product.js +0 -2
  192. package/lib/Types/Signal.js +0 -2
  193. package/lib/Types/Socket.js +0 -3
  194. package/lib/Types/State.js +0 -56
  195. package/lib/Types/USync.js +0 -2
  196. package/lib/Types/index.js +0 -26
  197. package/lib/Utils/auth-utils.js +0 -302
  198. package/lib/Utils/baileys-event-stream.js +0 -63
  199. package/lib/Utils/browser-utils.js +0 -48
  200. package/lib/Utils/business.js +0 -231
  201. package/lib/Utils/chat-utils.js +0 -873
  202. package/lib/Utils/companion-reg-client-utils.js +0 -35
  203. package/lib/Utils/crypto.js +0 -118
  204. package/lib/Utils/decode-wa-message.js +0 -350
  205. package/lib/Utils/event-buffer.js +0 -622
  206. package/lib/Utils/generics.js +0 -399
  207. package/lib/Utils/history.js +0 -134
  208. package/lib/Utils/identity-change-handler.js +0 -50
  209. package/lib/Utils/index.js +0 -23
  210. package/lib/Utils/link-preview.js +0 -85
  211. package/lib/Utils/logger.js +0 -3
  212. package/lib/Utils/lt-hash.js +0 -8
  213. package/lib/Utils/make-mutex.js +0 -33
  214. package/lib/Utils/message-composer.js +0 -273
  215. package/lib/Utils/message-retry-manager.js +0 -265
  216. package/lib/Utils/messages-media.js +0 -788
  217. package/lib/Utils/messages.js +0 -1260
  218. package/lib/Utils/noise-handler.js +0 -201
  219. package/lib/Utils/offline-node-processor.js +0 -40
  220. package/lib/Utils/pre-key-manager.js +0 -106
  221. package/lib/Utils/process-message.js +0 -630
  222. package/lib/Utils/reporting-utils.js +0 -258
  223. package/lib/Utils/signal.js +0 -202
  224. package/lib/Utils/stanza-ack.js +0 -38
  225. package/lib/Utils/sync-action-utils.js +0 -49
  226. package/lib/Utils/tc-token-utils.js +0 -163
  227. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  228. package/lib/Utils/validate-connection.js +0 -204
  229. package/lib/WABinary/constants.js +0 -1301
  230. package/lib/WABinary/decode.js +0 -262
  231. package/lib/WABinary/encode.js +0 -220
  232. package/lib/WABinary/generic-utils.js +0 -204
  233. package/lib/WABinary/index.js +0 -6
  234. package/lib/WABinary/jid-utils.js +0 -98
  235. package/lib/WABinary/types.js +0 -2
  236. package/lib/WAM/BinaryInfo.js +0 -10
  237. package/lib/WAM/constants.js +0 -22853
  238. package/lib/WAM/encode.js +0 -150
  239. package/lib/WAM/index.js +0 -4
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  241. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  242. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  243. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  244. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  245. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  247. package/lib/WAUSync/Protocols/index.js +0 -6
  248. package/lib/WAUSync/USyncQuery.js +0 -98
  249. package/lib/WAUSync/USyncUser.js +0 -31
  250. package/lib/WAUSync/index.js +0 -4
@@ -1,1459 +0,0 @@
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, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateIOSMessageID, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, setBotMessageSecret } 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, isJidNewsletter, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, getAdditionalNode, getBinaryNodeFilter, getBinaryFilteredBizBot, isInteropUser } from '../WABinary/index.js';
11
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
- import { makeUsernameSocket } from './username.js';
13
- import imup from './luxu.js';
14
- import * as Utils_1 from '../Utils/index.js';
15
- import { randomBytes } from 'crypto';
16
- export const makeMessagesSocket = (config) => {
17
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
18
- const sock = makeUsernameSocket(config);
19
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
20
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
21
- /**
22
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
23
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
24
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
25
- */
26
- const inFlightTcTokenIssuance = new Set();
27
- const userDevicesCache = config.userDevicesCache ||
28
- new NodeCache({
29
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
30
- useClones: false
31
- });
32
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
33
- const devicesMutex = makeMutex();
34
- // Initialize message retry manager if enabled
35
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
36
- // Prevent race conditions in Signal session encryption by user
37
- const encryptionMutex = makeKeyedMutex();
38
- let mediaConn;
39
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
40
- let mediaHost = DEF_MEDIA_HOST;
41
- const refreshMediaConn = async (forceGet = false) => {
42
- const media = await mediaConn;
43
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
44
- mediaConn = (async () => {
45
- const result = await query({
46
- tag: 'iq',
47
- attrs: {
48
- type: 'set',
49
- xmlns: 'w:m',
50
- to: S_WHATSAPP_NET
51
- },
52
- content: [{ tag: 'media_conn', attrs: {} }]
53
- });
54
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
55
- // TODO: explore full length of data that whatsapp provides
56
- const node = {
57
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
58
- hostname: attrs.hostname,
59
- maxContentLengthBytes: +attrs.maxContentLengthBytes
60
- })),
61
- auth: mediaConnNode.attrs.auth,
62
- ttl: +mediaConnNode.attrs.ttl,
63
- fetchDate: new Date()
64
- };
65
- logger.debug('fetched media conn');
66
- if (node.hosts[0]) {
67
- mediaHost = node.hosts[0].hostname;
68
- }
69
- return node;
70
- })();
71
- }
72
- return mediaConn;
73
- };
74
- /**
75
- * generic send receipt function
76
- * used for receipts of phone call, read, delivery etc.
77
- * */
78
- const sendReceipt = async (jid, participant, messageIds, type) => {
79
- if (!messageIds || messageIds.length === 0) {
80
- throw new Boom('missing ids in receipt');
81
- }
82
- const node = {
83
- tag: 'receipt',
84
- attrs: {
85
- id: messageIds[0]
86
- }
87
- };
88
- const isReadReceipt = type === 'read' || type === 'read-self';
89
- if (isReadReceipt) {
90
- node.attrs.t = unixTimestampSeconds().toString();
91
- }
92
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
93
- node.attrs.recipient = jid;
94
- node.attrs.to = participant;
95
- }
96
- else {
97
- node.attrs.to = jid;
98
- if (participant) {
99
- node.attrs.participant = participant;
100
- }
101
- }
102
- if (type) {
103
- node.attrs.type = type;
104
- }
105
- const remainingMessageIds = messageIds.slice(1);
106
- if (remainingMessageIds.length) {
107
- node.content = [
108
- {
109
- tag: 'list',
110
- attrs: {},
111
- content: remainingMessageIds.map(id => ({
112
- tag: 'item',
113
- attrs: { id }
114
- }))
115
- }
116
- ];
117
- }
118
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
119
- await sendNode(node);
120
- };
121
- /** Correctly bulk send receipts to multiple chats, participants */
122
- const sendReceipts = async (keys, type) => {
123
- const recps = aggregateMessageKeysNotFromMe(keys);
124
- for (const { jid, participant, messageIds } of recps) {
125
- await sendReceipt(jid, participant, messageIds, type);
126
- }
127
- };
128
- /** Bulk read messages. Keys can be from different chats & participants */
129
- const readMessages = async (keys) => {
130
- const privacySettings = await fetchPrivacySettings();
131
- // based on privacy settings, we have to change the read type
132
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
133
- await sendReceipts(keys, readType);
134
- };
135
- /** Fetch all the devices we've to send a message to */
136
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
137
- const deviceResults = [];
138
- if (!useCache) {
139
- logger.debug('not using cache for devices');
140
- }
141
- const toFetch = [];
142
- const jidsWithUser = jids
143
- .map(jid => {
144
- const decoded = jidDecode(jid);
145
- const user = decoded?.user;
146
- const device = decoded?.device;
147
- const isExplicitDevice = typeof device === 'number' && device >= 0;
148
- if (isExplicitDevice && user) {
149
- deviceResults.push({
150
- user,
151
- device,
152
- jid
153
- });
154
- return null;
155
- }
156
- jid = jidNormalizedUser(jid);
157
- return { jid, user };
158
- })
159
- .filter(jid => jid !== null);
160
- let mgetDevices;
161
- if (useCache && userDevicesCache.mget) {
162
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
163
- mgetDevices = await userDevicesCache.mget(usersToFetch);
164
- }
165
- for (const { jid, user } of jidsWithUser) {
166
- if (useCache) {
167
- const devices = mgetDevices?.[user] ||
168
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
169
- if (devices) {
170
- const devicesWithJid = devices.map(d => ({
171
- ...d,
172
- jid: jidEncode(d.user, d.server, d.device)
173
- }));
174
- deviceResults.push(...devicesWithJid);
175
- logger.trace({ user }, 'using cache for devices');
176
- }
177
- else {
178
- toFetch.push(jid);
179
- }
180
- }
181
- else {
182
- toFetch.push(jid);
183
- }
184
- }
185
- if (!toFetch.length) {
186
- return deviceResults;
187
- }
188
- const requestedLidUsers = new Set();
189
- for (const jid of toFetch) {
190
- if (isLidUser(jid) || isHostedLidUser(jid)) {
191
- const user = jidDecode(jid)?.user;
192
- if (user)
193
- requestedLidUsers.add(user);
194
- }
195
- }
196
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
197
- for (const jid of toFetch) {
198
- 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
199
- }
200
- const result = await sock.executeUSyncQuery(query);
201
- if (result) {
202
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
203
- const lidResults = result.list.filter(a => !!a.lid);
204
- if (lidResults.length > 0) {
205
- logger.trace('Storing LID maps from device call');
206
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
207
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
208
- try {
209
- const lids = lidResults.map(a => a.lid);
210
- if (lids.length) {
211
- await assertSessions(lids, true);
212
- }
213
- }
214
- catch (e) {
215
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
216
- }
217
- }
218
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
219
- const deviceMap = {};
220
- for (const item of extracted) {
221
- deviceMap[item.user] = deviceMap[item.user] || [];
222
- deviceMap[item.user]?.push(item);
223
- }
224
- // Process each user's devices as a group for bulk LID migration
225
- for (const [user, userDevices] of Object.entries(deviceMap)) {
226
- const isLidUser = requestedLidUsers.has(user);
227
- // Process all devices for this user
228
- for (const item of userDevices) {
229
- const finalJid = isLidUser
230
- ? jidEncode(user, item.server, item.device)
231
- : jidEncode(item.user, item.server, item.device);
232
- deviceResults.push({
233
- ...item,
234
- jid: finalJid
235
- });
236
- logger.debug({
237
- user: item.user,
238
- device: item.device,
239
- finalJid,
240
- usedLid: isLidUser
241
- }, 'Processed device with LID priority');
242
- }
243
- }
244
- await devicesMutex.mutex(async () => {
245
- if (userDevicesCache.mset) {
246
- // if the cache supports mset, we can set all devices in one go
247
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
248
- }
249
- else {
250
- for (const key in deviceMap) {
251
- if (deviceMap[key])
252
- await userDevicesCache.set(key, deviceMap[key]);
253
- }
254
- }
255
- });
256
- const userDeviceUpdates = {};
257
- for (const [userId, devices] of Object.entries(deviceMap)) {
258
- if (devices && devices.length > 0) {
259
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
260
- }
261
- }
262
- if (Object.keys(userDeviceUpdates).length > 0) {
263
- try {
264
- await authState.keys.set({ 'device-list': userDeviceUpdates });
265
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
266
- }
267
- catch (error) {
268
- logger.warn({ error }, 'failed to store user device lists');
269
- }
270
- }
271
- }
272
- return deviceResults;
273
- };
274
- /**
275
- * Update Member Label
276
- */
277
- const updateMemberLabel = (jid, memberLabel) => {
278
- return relayMessage(jid, {
279
- protocolMessage: {
280
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
281
- memberLabel: {
282
- label: memberLabel?.slice(0, 30),
283
- labelTimestamp: unixTimestampSeconds()
284
- }
285
- }
286
- }, {
287
- additionalNodes: [
288
- {
289
- tag: 'meta',
290
- attrs: {
291
- tag_reason: 'user_update',
292
- appdata: 'member_tag'
293
- },
294
- content: undefined
295
- }
296
- ]
297
- });
298
- };
299
- const assertSessions = async (jids, force) => {
300
- let didFetchNewSession = false;
301
- const uniqueJids = [...new Set(jids)];
302
- const jidsRequiringFetch = [];
303
- logger.debug({ jids }, 'assertSessions call with jids');
304
- for (const jid of uniqueJids) {
305
- if (!force) {
306
- const sessionValidation = await signalRepository.validateSession(jid);
307
- if (sessionValidation.exists) {
308
- continue;
309
- }
310
- }
311
- jidsRequiringFetch.push(jid);
312
- }
313
- if (jidsRequiringFetch.length) {
314
- // LID if mapped, otherwise original
315
- const wireJids = [
316
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
317
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
318
- ];
319
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
320
- const result = await query({
321
- tag: 'iq',
322
- attrs: {
323
- xmlns: 'encrypt',
324
- type: 'get',
325
- to: S_WHATSAPP_NET
326
- },
327
- content: [
328
- {
329
- tag: 'key',
330
- attrs: {},
331
- content: wireJids.map(jid => {
332
- const attrs = { jid };
333
- if (force)
334
- attrs.reason = 'identity';
335
- return { tag: 'user', attrs };
336
- })
337
- }
338
- ]
339
- });
340
- await parseAndInjectE2ESessions(result, signalRepository);
341
- didFetchNewSession = true;
342
- }
343
- return didFetchNewSession;
344
- };
345
- const sendPeerDataOperationMessage = async (pdoMessage) => {
346
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
347
- if (!authState.creds.me?.id) {
348
- throw new Boom('Not authenticated');
349
- }
350
- const protocolMessage = {
351
- protocolMessage: {
352
- peerDataOperationRequestMessage: pdoMessage,
353
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
354
- }
355
- };
356
- const meJid = jidNormalizedUser(authState.creds.me.id);
357
- const msgId = await relayMessage(meJid, protocolMessage, {
358
- additionalAttributes: {
359
- category: 'peer',
360
- push_priority: 'high_force'
361
- },
362
- additionalNodes: [
363
- {
364
- tag: 'meta',
365
- attrs: { appdata: 'default' }
366
- }
367
- ]
368
- });
369
- return msgId;
370
- };
371
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
372
- if (!recipientJids.length) {
373
- return { nodes: [], shouldIncludeDeviceIdentity: false };
374
- }
375
- const patched = await patchMessageBeforeSending(message, recipientJids);
376
- const patchedMessages = Array.isArray(patched)
377
- ? patched
378
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
379
- let shouldIncludeDeviceIdentity = false;
380
- const meId = authState.creds.me.id;
381
- const meLid = authState.creds.me?.lid;
382
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
383
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
384
- try {
385
- if (!jid)
386
- return null;
387
- let msgToEncrypt = patchedMessage;
388
- if (dsmMessage) {
389
- const { user: targetUser } = jidDecode(jid);
390
- const { user: ownPnUser } = jidDecode(meId);
391
- const ownLidUser = meLidUser;
392
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
393
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
394
- if (isOwnUser && !isExactSenderDevice) {
395
- msgToEncrypt = dsmMessage;
396
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
397
- }
398
- }
399
- const bytes = encodeWAMessage(msgToEncrypt);
400
- const mutexKey = jid;
401
- const node = await encryptionMutex.mutex(mutexKey, async () => {
402
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
403
- if (type === 'pkmsg') {
404
- shouldIncludeDeviceIdentity = true;
405
- }
406
- return {
407
- tag: 'to',
408
- attrs: { jid },
409
- content: [
410
- {
411
- tag: 'enc',
412
- attrs: { v: '2', type, ...(extraAttrs || {}) },
413
- content: ciphertext
414
- }
415
- ]
416
- };
417
- });
418
- return node;
419
- }
420
- catch (err) {
421
- logger.error({ jid, err }, 'Failed to encrypt for recipient');
422
- return null;
423
- }
424
- });
425
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
426
- if (recipientJids.length > 0 && nodes.length === 0) {
427
- throw new Boom('All encryptions failed', { statusCode: 500 });
428
- }
429
- return { nodes, shouldIncludeDeviceIdentity };
430
- };
431
-
432
- const profilePictureUrl = async (jid) => {
433
- if (isJidNewsletter(jid)) {
434
- const metadata = await sock.newsletterMetadata("JID", jid);
435
- return getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || "");
436
- } else {
437
- const result = await query({
438
- tag: "iq",
439
- attrs: {
440
- target: jidNormalizedUser(jid),
441
- to: S_WHATSAPP_NET,
442
- type: "get",
443
- xmlns: "w:profile:picture",
444
- },
445
- content: [{ tag: "picture", attrs: { type: "image", query: "url" } }],
446
- });
447
- const child = getBinaryNodeChild(result, "picture");
448
- return child?.attrs?.url || null;
449
- }
450
- };
451
-
452
- const relayMessage = async (
453
- jid,
454
- message,
455
- {
456
- messageId: msgId,
457
- participant = false,
458
- additionalAttributes,
459
- additionalNodes,
460
- useUserDevicesCache,
461
- useCachedGroupMetadata,
462
- statusJidList
463
- }
464
- ) => {
465
- const meId = authState.creds.me.id
466
- const meLid = authState.creds.me?.lid
467
- const isRetryResend = Boolean(participant?.jid)
468
- let shouldIncludeDeviceIdentity = isRetryResend
469
- const statusJid = 'status@broadcast'
470
- const { user, server } = jidDecode(jid)
471
- const isGroup = server === 'g.us'
472
- const isStatus = jid === statusJid
473
- const isLid = server === 'lid'
474
- const isNewsletter = server === 'newsletter'
475
- const isInterop = isInteropUser(jid)
476
- const isGroupOrStatus = isGroup || isStatus
477
- const finalJid = jid
478
- const iosBros = config.browser[0] === "iOS" || config.browser[1] === "Safari";
479
- msgId = iosBros ? generateIOSMessageID() : msgId ?? generateMessageIDV2(meId)
480
- useUserDevicesCache = useUserDevicesCache!== false
481
- useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
482
- const participants = []
483
- const destinationJid =!isStatus? finalJid : statusJid
484
- const binaryNodeContent = []
485
- const devices = []
486
- let reportingMessage
487
- const meMsg = {
488
- deviceSentMessage: { destinationJid, message },
489
- messageContextInfo: message.messageContextInfo
490
- }
491
- const extraAttrs = {}
492
- const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
493
- const messages = normalizeMessageContent(message)
494
- const buttonType = getButtonType(messages)
495
- const pollMessage =
496
- messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
497
- await authState.keys.transaction(async () => {
498
- const mediaType = getMediaType(message)
499
- if (mediaType) extraAttrs.mediatype = mediaType
500
- if (isNewsletter) {
501
- const patched = patchMessageBeforeSending? await patchMessageBeforeSending(message, []) : message
502
- const bytes = encodeNewsletterMessage(patched)
503
- binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes })
504
- const stanza = {
505
- tag: 'message',
506
- attrs: {
507
- to: jid,
508
- id: msgId,
509
- type: getMessageType(message),
510
- ...(additionalAttributes || {})
511
- },
512
- content: binaryNodeContent
513
- }
514
- logger.debug({ msgId }, `sending newsletter message to ${jid}`)
515
- await sendNode(stanza)
516
- return
517
- }
518
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
519
- extraAttrs['decrypt-fail'] = 'hide'
520
- }
521
- if (isGroupOrStatus &&!isRetryResend) {
522
- const [groupData, senderKeyMap] = await Promise.all([
523
- (async () => {
524
- let groupData = useCachedGroupMetadata && cachedGroupMetadata? await cachedGroupMetadata(jid) : undefined
525
- if (groupData && Array.isArray(groupData?.participants)) {
526
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
527
- } else if (!isStatus) {
528
- groupData = await groupMetadata(jid)
529
- }
530
- return groupData
531
- })(),
532
- (async () => {
533
- if (!participant &&!isStatus) {
534
- const result = await authState.keys.get('sender-key-memory', [jid])
535
- return result[jid] || {}
536
- }
537
- return {}
538
- })()
539
- ])
540
- const participantsList = groupData? groupData.participants.map(p => p.id) : []
541
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
542
- additionalAttributes = {...additionalAttributes, expiration: groupData.ephemeralDuration.toString() }
543
- }
544
- if (isStatus && statusJidList) participantsList.push(...statusJidList)
545
- const additionalDevices = await getUSyncDevices(participantsList,!!useUserDevicesCache, false)
546
- devices.push(...additionalDevices)
547
- if (isGroup) {
548
- additionalAttributes = {
549
- ...additionalAttributes,
550
- addressing_mode: groupData?.addressingMode || 'lid'
551
- }
552
- }
553
- if (message?.groupStatusMessageV2 &&!message?.messageContextInfo?.messageSecret) {
554
- message = {
555
- ...message,
556
- messageContextInfo: {
557
- ...(message.messageContextInfo || {}),
558
- messageSecret: randomBytes(32)
559
- },
560
- groupStatusMessageV2: {
561
- ...message.groupStatusMessageV2,
562
- message: {
563
- ...(message.groupStatusMessageV2.message || {}),
564
- messageContextInfo: {
565
- ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
566
- messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
567
- }
568
- }
569
- }
570
- }
571
- }
572
- // list/buttons/template -> interactiveMessage
573
- if (message.listMessage) {
574
- const list = message.listMessage
575
- message = {
576
- interactiveMessage: {
577
- nativeFlowMessage: {
578
- buttons: [
579
- {
580
- name: 'single_select',
581
- buttonParamsJson: JSON.stringify({
582
- title: list.buttonText || 'Select',
583
- sections: (list.sections || []).map(section => ({
584
- title: section.title || '',
585
- highlight_label: '',
586
- rows: (section.rows || []).map(row => ({
587
- header: '',
588
- title: row.title || '',
589
- description: row.description || '',
590
- id: row.rowId || row.id || ''
591
- }))
592
- }))
593
- })
594
- }
595
- ],
596
- messageParamsJson: '',
597
- messageVersion: 1
598
- },
599
- body: { text: list.description || '' },
600
- footer: list.footerText? { text: list.footerText } : undefined,
601
- header: list.title? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
602
- contextInfo: list.contextInfo
603
- }
604
- }
605
- } else if (message.buttonsMessage) {
606
- const bMsg = message.buttonsMessage
607
- const buttons = (bMsg.buttons || []).map(btn => ({
608
- name: 'quick_reply',
609
- buttonParamsJson: JSON.stringify({
610
- display_text: btn.buttonText?.displayText || btn.buttonText || '',
611
- id: btn.buttonId || btn.buttonText?.displayText || ''
612
- })
613
- }))
614
- message = {
615
- interactiveMessage: {
616
- nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
617
- body: { text: bMsg.contentText || bMsg.text || '' },
618
- footer: bMsg.footerText? { text: bMsg.footerText } : undefined,
619
- header: bMsg.text
620
- ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
621
- : bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
622
- ? { hasMediaAttachment: true,...(bMsg.imageMessage? { imageMessage: bMsg.imageMessage } : {}),...(bMsg.videoMessage? { videoMessage: bMsg.videoMessage } : {}) }
623
- : undefined,
624
- contextInfo: bMsg.contextInfo
625
- }
626
- }
627
- } else if (message.templateMessage) {
628
- const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate
629
- if (tmpl) {
630
- const buttons = (tmpl.hydratedButtons || [])
631
- .map(hBtn => {
632
- if (hBtn.quickReplyButton) {
633
- return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: hBtn.quickReplyButton.displayText || '', id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || '' }) }
634
- } else if (hBtn.urlButton) {
635
- return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: hBtn.urlButton.displayText || '', url: hBtn.urlButton.url || '', merchant_url: hBtn.urlButton.url || '' }) }
636
- } else if (hBtn.callButton) {
637
- return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: hBtn.callButton.displayText || '', phone_number: hBtn.callButton.phoneNumber || '' }) }
638
- }
639
- return null
640
- })
641
- .filter(Boolean)
642
- message = {
643
- interactiveMessage: {
644
- nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
645
- body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
646
- footer: tmpl.hydratedFooterText? { text: tmpl.hydratedFooterText } : undefined,
647
- header: tmpl.hydratedTitleText
648
- ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
649
- : tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
650
- ? { hasMediaAttachment: true,...(tmpl.imageMessage? { imageMessage: tmpl.imageMessage } : {}),...(tmpl.videoMessage? { videoMessage: tmpl.videoMessage } : {}) }
651
- : undefined,
652
- contextInfo: tmpl.contextInfo
653
- }
654
- }
655
- }
656
- }
657
-
658
- const patched = await patchMessageBeforeSending(message)
659
- if (Array.isArray(patched)) throw new Boom('Per-jid patching is not supported in groups')
660
- const bytes = encodeWAMessage(patched)
661
- reportingMessage = patched
662
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
663
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid? meLid : meId
664
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
665
- group: destinationJid,
666
- data: bytes,
667
- meId: groupSenderIdentity
668
- })
669
- const senderKeyRecipients = []
670
- for (const device of devices) {
671
- const deviceJid = device.jid
672
- const hasKey =!!senderKeyMap[deviceJid]
673
- if (!hasKey ||!!participant &&!isHostedLidUser(deviceJid) &&!isHostedPnUser(deviceJid) && device.device!== 99) {
674
- senderKeyRecipients.push(deviceJid)
675
- senderKeyMap[deviceJid] = true
676
- }
677
- }
678
- if (senderKeyRecipients.length) {
679
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
680
- const senderKeyMsg = {
681
- senderKeyDistributionMessage: {
682
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
683
- groupId: destinationJid
684
- }
685
- }
686
- await assertSessions(senderKeyRecipients)
687
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
688
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
689
- participants.push(...result.nodes)
690
- }
691
- binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg',...extraAttrs }, content: ciphertext })
692
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
693
- } else {
694
- let ownId = meId
695
- if (isLid && meLid) {
696
- ownId = meLid
697
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
698
- } else {
699
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
700
- }
701
- const { user: ownUser } = jidDecode(ownId)
702
- if (!participant) {
703
- const patchedForReporting = await patchMessageBeforeSending(message, [jid])
704
- reportingMessage = Array.isArray(patchedForReporting)
705
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
706
- : patchedForReporting
707
- }
708
- if (!isRetryResend) {
709
- const targetUserServer = isLid? 'lid' : isInterop? 'interop' : 's.whatsapp.net'
710
- devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) })
711
- if (user!== ownUser &&!isInterop) {
712
- const ownUserServer = isLid? 'lid' : 's.whatsapp.net'
713
- const ownUserForAddressing = isLid && meLid? jidDecode(meLid).user : jidDecode(meId).user
714
- devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) })
715
- }
716
- if (additionalAttributes?.['category']!== 'peer' &&!isInterop) {
717
- devices.length = 0
718
- const senderIdentity = isLid && meLid
719
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
720
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
721
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
722
- devices.push(...sessionDevices)
723
- logger.debug({ deviceCount: devices.length, devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`) }, 'Device enumeration complete with unified addressing')
724
- }
725
- }
726
- const allRecipients = []
727
- const meRecipients = []
728
- const otherRecipients = []
729
- const { user: mePnUser } = jidDecode(meId)
730
- const { user: meLidUser } = meLid? jidDecode(meLid) : { user: null }
731
- for (const { user, jid } of devices) {
732
- /** participant method by Xzc || Tsm, who's delete the credits = love BBC */
733
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
734
- if (isExactSenderDevice) {
735
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
736
- continue
737
- }
738
- const isMe = user === mePnUser || user === meLidUser
739
- let ptcp = false
740
- if (participant) {
741
- if (!isJidGroup(jid) && !isStatus) {
742
- if (!(!isMe)) ptcp = true
743
- } else {
744
- ptcp = false
745
- }
746
- }
747
- if (!ptcp) {
748
- if (isMe) {
749
- meRecipients.push(jid)
750
- } else {
751
- otherRecipients.push(jid)
752
- }
753
- allRecipients.push(jid)
754
- }
755
- }
756
- await assertSessions(allRecipients)
757
- const [
758
- { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
759
- { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
760
- ] = await Promise.all([
761
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
762
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
763
- ])
764
- participants.push(...meNodes,...otherNodes)
765
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
766
- extraAttrs.phash = generateParticipantHashV2([...meRecipients,...otherRecipients])
767
- }
768
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
769
- }
770
- if (isRetryResend) {
771
- const isParticipantLid = jidDecode(participant.jid).server === 'lid'
772
- const isMe = areJidsSameUser(participant.jid, isParticipantLid? meLid : meId)
773
- const encodedMessageToSend = isMe
774
- ? encodeWAMessage({ deviceSentMessage: { destinationJid, message } })
775
- : encodeWAMessage(message)
776
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
777
- data: encodedMessageToSend,
778
- jid: participant.jid
779
- })
780
- binaryNodeContent.push({
781
- tag: 'enc',
782
- attrs: { v: '2', type, count: (participant.count?? 0).toString() },
783
- content: encryptedContent
784
- })
785
- }
786
- if (participants.length) {
787
- if (additionalAttributes?.['category'] === 'peer') {
788
- const peerNode = participants[0]?.content?.[0]
789
- if (peerNode) binaryNodeContent.push(peerNode)
790
- } else if (isInterop) {
791
- const recipientNode = participants.find(p => isInteropUser(p?.attrs?.jid))
792
- const encNode = (recipientNode?? participants[0])?.content?.[0]
793
- if (encNode) binaryNodeContent.push(encNode)
794
- } else {
795
- binaryNodeContent.push({ tag: 'participants', attrs: {}, content: participants })
796
- }
797
- }
798
- const stanza = {
799
- tag: 'message',
800
- attrs: { id: msgId, to: destinationJid, type: getMessageType(message),...(additionalAttributes || {}) },
801
- content: binaryNodeContent
802
- }
803
- if (shouldIncludeDeviceIdentity) {
804
- stanza.content.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
805
- logger.debug({ jid }, 'adding device identity')
806
- }
807
-
808
- if (isGroup && regexGroupOld.test(jid) &&!message.reactionMessage) {
809
- stanza.content.push({ tag: 'multicast', attrs: {} })
810
- }
811
- if (pollMessage || messages.eventMessage) {
812
- stanza.content.push({
813
- tag: 'meta',
814
- attrs: messages.eventMessage
815
- ? { event_type: 'creation' }
816
- : isNewsletter
817
- ? { polltype: 'creation', contenttype: pollMessage?.pollContentType === 2? 'image' : 'text' }
818
- : { polltype: 'creation' }
819
- })
820
- }
821
- if (!isNewsletter &&!isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
822
- try {
823
- const encoded = encodeWAMessage(reportingMessage)
824
- const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: participant?.jid }
825
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
826
- if (reportingNode) {
827
- stanza.content.push(reportingNode)
828
- logger.trace({ jid }, 'added reporting token to message')
829
- }
830
- } catch (error) {
831
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
832
- }
833
- }
834
- let didPushAdditional = false
835
- if (!isNewsletter && buttonType) {
836
- const buttonsNode = getButtonArgs(messages)
837
- const filteredButtons = getBinaryNodeFilter(additionalNodes? additionalNodes : [])
838
- if (filteredButtons) {
839
- stanza.content.push(...additionalNodes)
840
- didPushAdditional = true
841
- } else {
842
- stanza.content.push(buttonsNode)
843
- }
844
- }
845
- if (!aiLabel && isPnUser(destinationJid)) {
846
- const alreadyHasBizBot = getBinaryFilteredBizBot(additionalNodes || []) || getBinaryFilteredBizBot(stanza.content)
847
- if (!alreadyHasBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
848
- } else if (aiLabel &&!isGroup &&!isStatus &&!isNewsletter) {
849
- const existingBizBot = getBinaryFilteredBizBot(additionalNodes || [])
850
- if (!existingBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
851
- }
852
- const isPeerMessage = additionalAttributes?.['category'] === 'peer'
853
- const is1on1Send =!isGroup &&!isRetryResend &&!isStatus &&!isNewsletter &&!isPeerMessage
854
- const tcTokenJid = is1on1Send? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid
855
- const contactTcTokenData = is1on1Send? await authState.keys.get('tctoken', [tcTokenJid]) : {}
856
- const existingTokenEntry = contactTcTokenData[tcTokenJid]
857
- let tcTokenBuffer = existingTokenEntry?.token
858
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
859
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
860
- tcTokenBuffer = undefined
861
- const cleared = existingTokenEntry?.senderTimestamp!== undefined? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp } : null
862
- try {
863
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
864
- } catch (err) {
865
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
866
- }
867
- }
868
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
869
- stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
870
- }
871
- if (additionalNodes && additionalNodes.length > 0 &&!didPushAdditional) {
872
- stanza.content.push(...additionalNodes)
873
- }
874
- logger.debug({ msgId }, `sending message to ${participants.length} devices`)
875
- await sendNode(stanza)
876
- if (message.messageContextInfo?.messageSecret) {
877
- setBotMessageSecret(msgId, message.messageContextInfo.messageSecret, destinationJid)
878
- }
879
- const isProtocolMsg =!!normalizeMessageContent(message)?.protocolMessage
880
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid)
881
- if (is1on1Send &&!isProtocolMsg &&!isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&!inFlightTcTokenIssuance.has(tcTokenJid)) {
882
- inFlightTcTokenIssuance.add(tcTokenJid)
883
- const issueTimestamp = unixTimestampSeconds()
884
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
885
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
886
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
887
- .then(async result => {
888
- await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN })
889
- const currentData = await authState.keys.get('tctoken', [tcTokenJid])
890
- const currentEntry = currentData[tcTokenJid]
891
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
892
- await authState.keys.set({
893
- tctoken: {
894
- [tcTokenJid]: { token: Buffer.alloc(0),...currentEntry, senderTimestamp: issueTimestamp },
895
- ...indexWrite
896
- }
897
- })
898
- })
899
- .catch(err => logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed'))
900
- .finally(() => inFlightTcTokenIssuance.delete(tcTokenJid))
901
- }
902
- if (messageRetryManager &&!participant) {
903
- messageRetryManager.addRecentMessage(destinationJid, msgId, message)
904
- }
905
- if (isInterop &&!isRetryResend) {
906
- await trustInteropContact(destinationJid).catch(err => logger.debug({ err, jid: destinationJid }, 'failed to trust interop contact'))
907
- }
908
- }, meId)
909
- return msgId
910
- }
911
- const getMessageType = (message) => {
912
- const normalizedMessage = normalizeMessageContent(message);
913
- if (!normalizedMessage)
914
- return 'text';
915
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
916
- return 'reaction';
917
- }
918
- if (normalizedMessage.pollCreationMessage ||
919
- normalizedMessage.pollCreationMessageV2 ||
920
- normalizedMessage.pollCreationMessageV3 ||
921
- normalizedMessage.pollCreationMessageV4 ||
922
- normalizedMessage.pollCreationMessageV5 ||
923
- normalizedMessage.pollUpdateMessage) {
924
- return 'poll';
925
- }
926
- if (normalizedMessage.eventMessage) {
927
- return 'event';
928
- }
929
- if (getMediaType(normalizedMessage) !== '') {
930
- return 'media';
931
- }
932
- return 'text';
933
- };
934
- const getMediaType = (message) => {
935
- if (message.imageMessage) {
936
- return 'image';
937
- }
938
- else if (message.videoMessage) {
939
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
940
- }
941
- else if (message.audioMessage) {
942
- return message.audioMessage.ptt ? 'ptt' : 'audio';
943
- }
944
- else if (message.contactMessage) {
945
- return 'vcard';
946
- }
947
- else if (message.documentMessage) {
948
- return 'document';
949
- }
950
- else if (message.contactsArrayMessage) {
951
- return 'contact_array';
952
- }
953
- else if (message.liveLocationMessage) {
954
- return 'livelocation';
955
- }
956
- else if (message.stickerMessage) {
957
- return 'sticker';
958
- }
959
- else if (message.listMessage) {
960
- return 'list';
961
- }
962
- else if (message.listResponseMessage) {
963
- return 'list_response';
964
- }
965
- else if (message.buttonsResponseMessage) {
966
- return 'buttons_response';
967
- }
968
- else if (message.orderMessage) {
969
- return 'order';
970
- }
971
- else if (message.productMessage) {
972
- return 'product';
973
- }
974
- else if (message.interactiveResponseMessage) {
975
- return 'native_flow_response';
976
- }
977
- else if (message.groupInviteMessage) {
978
- return 'url';
979
- }
980
- return '';
981
- };
982
- const getButtonType = (message) => {
983
- if (message.listMessage) {
984
- return 'list'
985
- }
986
- else if (message.buttonsMessage) {
987
- return 'buttons'
988
- }
989
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
990
- return 'review_and_pay'
991
- }
992
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
993
- return 'review_order'
994
- }
995
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
996
- return 'payment_info'
997
- } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
998
- return 'payment_key_info'
999
- } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
1000
- return 'payment_status'
1001
- }
1002
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
1003
- return 'payment_method'
1004
- }
1005
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'catalog_message') {
1006
- return 'catalog_message'
1007
- }
1008
- else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
1009
- return 'interactive'
1010
- }
1011
- else if (message.interactiveMessage?.nativeFlowMessage) {
1012
- return 'native_flow'
1013
- }
1014
- };
1015
- const getButtonArgs = (message) => {
1016
- const nativeFlow = message.interactiveMessage?.nativeFlowMessage
1017
- const firstButtonName = nativeFlow?.buttons?.[0]?.name
1018
- const nativeFlowSpecials = [
1019
- 'mpm',
1020
- 'cta_catalog',
1021
- 'send_location',
1022
- 'call_permission_request',
1023
- 'wa_payment_transaction_details',
1024
- 'automated_greeting_message_view_catalog'
1025
- ]
1026
-
1027
- if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1028
- return {
1029
- tag: 'biz',
1030
- attrs: {
1031
- native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
1032
- }
1033
- }
1034
- } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1035
- // Only works for WhatsApp Original, not WhatsApp Business
1036
- return {
1037
- tag: 'biz',
1038
- attrs: {
1039
- actual_actors: '2',
1040
- host_storage: '2',
1041
- privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1042
- },
1043
- content: [
1044
- {
1045
- tag: 'interactive',
1046
- attrs: {
1047
- type: 'native_flow',
1048
- v: '1'
1049
- },
1050
- content: [
1051
- {
1052
- tag: 'native_flow',
1053
- attrs: {
1054
- v: '2',
1055
- name: firstButtonName
1056
- }
1057
- }
1058
- ]
1059
- },
1060
- {
1061
- tag: 'quality_control',
1062
- attrs: {
1063
- source_type: 'third_party'
1064
- }
1065
- }
1066
- ]
1067
- }
1068
- } else if (nativeFlow || message.buttonsMessage) {
1069
- // It works for whatsapp original and whatsapp business
1070
- return {
1071
- tag: 'biz',
1072
- attrs: {
1073
- actual_actors: '2',
1074
- host_storage: '2',
1075
- privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1076
- },
1077
- content: [
1078
- {
1079
- tag: 'interactive',
1080
- attrs: {
1081
- type: 'native_flow',
1082
- v: '1'
1083
- },
1084
- content: [
1085
- {
1086
- tag: 'native_flow',
1087
- attrs: {
1088
- v: '9',
1089
- name: 'mixed'
1090
- }
1091
- }
1092
- ]
1093
- },
1094
- {
1095
- tag: 'quality_control',
1096
- attrs: {
1097
- source_type: 'third_party'
1098
- }
1099
- }
1100
- ]
1101
- }
1102
- } else if (message.listMessage) {
1103
- return {
1104
- tag: 'biz',
1105
- attrs: {
1106
- actual_actors: '2',
1107
- host_storage: '2',
1108
- privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1109
- },
1110
- content: [
1111
- {
1112
- tag: 'list',
1113
- attrs: {
1114
- v: '2',
1115
- type: 'product_list'
1116
- }
1117
- },
1118
- {
1119
- tag: 'quality_control',
1120
- attrs: {
1121
- source_type: 'third_party'
1122
- }
1123
- }
1124
- ]
1125
- }
1126
- } else {
1127
- return {
1128
- tag: 'biz',
1129
- attrs: {
1130
- actual_actors: '2',
1131
- host_storage: '2',
1132
- privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1133
- }
1134
- }
1135
- }
1136
- }
1137
- const issuePrivacyTokens = async (jids, timestamp) => {
1138
- const t = (timestamp ?? unixTimestampSeconds()).toString();
1139
- const result = await query({
1140
- tag: 'iq',
1141
- attrs: {
1142
- to: S_WHATSAPP_NET,
1143
- type: 'set',
1144
- xmlns: 'privacy'
1145
- },
1146
- content: [
1147
- {
1148
- tag: 'tokens',
1149
- attrs: {},
1150
- content: jids.map(jid => ({
1151
- tag: 'token',
1152
- attrs: {
1153
- jid: jidNormalizedUser(jid),
1154
- t,
1155
- type: 'trusted_contact'
1156
- }
1157
- }))
1158
- }
1159
- ]
1160
- });
1161
- return result;
1162
- };
1163
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1164
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1165
- registerSocketEndHandler(() => {
1166
- if (!config.userDevicesCache && userDevicesCache.close) {
1167
- userDevicesCache.close();
1168
- }
1169
- mediaConn = undefined;
1170
- if (messageRetryManager) {
1171
- messageRetryManager.clear();
1172
- }
1173
- });
1174
-
1175
- return {
1176
- ...sock,
1177
- userDevicesCache,
1178
- devicesMutex,
1179
- issuePrivacyTokens,
1180
- assertSessions,
1181
- profilePictureUrl,
1182
- relayMessage,
1183
- sendReceipt,
1184
- sendReceipts,
1185
- readMessages,
1186
- refreshMediaConn,
1187
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1188
- getMediaHost: () => mediaHost,
1189
- waUploadToServer,
1190
- fetchPrivacySettings,
1191
- sendPeerDataOperationMessage,
1192
- createParticipantNodes,
1193
- getUSyncDevices,
1194
- messageRetryManager,
1195
- updateMemberLabel,
1196
- updateMediaMessage: async (message) => {
1197
- const content = assertMediaContent(message.message);
1198
- const mediaKey = content.mediaKey;
1199
- const meId = authState.creds.me.id;
1200
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1201
- let error = undefined;
1202
- await Promise.all([
1203
- sendNode(node),
1204
- waitForMsgMediaUpdate(async (update) => {
1205
- const result = update.find(c => c.key.id === message.key.id);
1206
- if (result) {
1207
- if (result.error) {
1208
- error = result.error;
1209
- }
1210
- else {
1211
- try {
1212
- const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1213
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1214
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1215
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1216
- data: media,
1217
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
1218
- });
1219
- }
1220
- content.directPath = media.directPath;
1221
- content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1222
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1223
- }
1224
- catch (err) {
1225
- error = err;
1226
- }
1227
- }
1228
- return true;
1229
- }
1230
- })
1231
- ]);
1232
- if (error) {
1233
- throw error;
1234
- }
1235
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1236
- return message;
1237
- },
1238
- sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1239
- const { message, messageId } = Utils_1.generateTableContent(title, headers, rows, quoted, options)
1240
- await relayMessage(jid, message, { messageId })
1241
- return { message, messageId }
1242
- },
1243
- sendList: async (jid, title, items, quoted, options = {}) => {
1244
- const { message, messageId } = Utils_1.generateListContent(title, items, quoted, options)
1245
- await relayMessage(jid, message, { messageId })
1246
- return { message, messageId }
1247
- },
1248
- sendCodeBlock: async (jid, code, quoted, options = {}) => {
1249
- const { message, messageId } = Utils_1.generateCodeBlockContent(code, quoted, options)
1250
- await relayMessage(jid, message, { messageId })
1251
- return { message, messageId }
1252
- },
1253
- sendLatex: async (jid, quoted, options) => {
1254
- const { message, messageId } = Utils_1.generateLatexContent(quoted, options)
1255
- await relayMessage(jid, message, { messageId })
1256
- return { message, messageId }
1257
- },
1258
- sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1259
- const { message, messageId } = await Utils_1.generateLatexImageContent(
1260
- quoted,
1261
- options,
1262
- uploadFn,
1263
- renderLatexToPng
1264
- )
1265
- await relayMessage(jid, message, { messageId })
1266
- return { message, messageId }
1267
- },
1268
- sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1269
- const { message, messageId } = await Utils_1.generateLatexInlineImageContent(
1270
- quoted,
1271
- options,
1272
- uploadFn,
1273
- renderLatexToPng
1274
- )
1275
- await relayMessage(jid, message, { messageId })
1276
- return { message, messageId }
1277
- },
1278
- captureUnifiedResponse: Utils_1.captureUnifiedResponse,
1279
- sendUnifiedResponse: async (jid, quoted, captured) => {
1280
- const { message, messageId } = Utils_1.generateUnifiedResponseContent(quoted, captured)
1281
- await relayMessage(jid, message, { messageId })
1282
- return { message, messageId }
1283
- },
1284
- sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1285
- const { message, messageId } = Utils_1.generateRichMessageContent(submessages, quoted, options)
1286
- await relayMessage(jid, message, { messageId })
1287
- return { message, messageId }
1288
- },
1289
- sendMessage: async (jid, content, options = {}) => {
1290
- const userJid = authState.creds.me.id;
1291
- const luki = new imup(Utils_1, waUploadToServer, relayMessage)
1292
- const { quoted, participant = false } = options;
1293
- const messageType = luki.detectType(content);
1294
- if (typeof content === 'object' &&
1295
- 'disappearingMessagesInChat' in content &&
1296
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1297
- isJidGroup(jid)) {
1298
- const { disappearingMessagesInChat } = content;
1299
- const value = typeof disappearingMessagesInChat === 'boolean'
1300
- ? disappearingMessagesInChat
1301
- ? WA_DEFAULT_EPHEMERAL
1302
- : 0
1303
- : disappearingMessagesInChat;
1304
- await groupToggleEphemeral(jid, value);
1305
- }
1306
- else {
1307
- if (messageType) {
1308
- switch(messageType) {
1309
- case 'PAYMENT':
1310
- const paymentContent = await luki.handlePayment(content, quoted);
1311
- return await relayMessage(jid, paymentContent, {
1312
- messageId: Utils_1.generateMessageID()
1313
- });
1314
- case 'PRODUCT':
1315
- const productContent = await luki.handleProduct(content, jid, quoted);
1316
- const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
1317
- return await relayMessage(jid, productMsg.message, {
1318
- messageId: productMsg.key.id,
1319
- });
1320
-
1321
- case 'ALBUM':
1322
- return await luki.handleAlbum(content, jid, quoted)
1323
- case 'EVENT':
1324
- return await luki.handleEvent(content, jid, quoted)
1325
- case 'POLL_RESULT':
1326
- return await luki.handlePollResult(content, jid, quoted)
1327
- case 'ORDER':
1328
- return await luki.handleOrderMessage(content, jid, quoted)
1329
- case 'GROUP_STATUS':
1330
- return await luki.handleGroupStory(content, jid, quoted)
1331
- case 'GROUP_LABEL':
1332
- return await luki.handleGbLabel(content, jid)
1333
- }
1334
- }
1335
- const fullMsg = await generateWAMessage(jid, content, {
1336
- logger,
1337
- userJid,
1338
- getUrlInfo: text => getUrlInfo(text, {
1339
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1340
- fetchOpts: {
1341
- timeout: 3000,
1342
- ...(httpRequestOptions || {})
1343
- },
1344
- logger,
1345
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1346
- }),
1347
- //TODO: CACHE
1348
- getProfilePicUrl: profilePictureUrl,
1349
- getCallLink: sock.createCallLink,
1350
- upload: waUploadToServer,
1351
- mediaCache: config.mediaCache,
1352
- options: config.options,
1353
- messageId: generateMessageIDV2(sock.user?.id),
1354
- ...options
1355
- });
1356
- const isEventMsg = 'event' in content && !!content.event;
1357
- const isDeleteMsg = 'delete' in content && !!content.delete;
1358
- const isEditMsg = 'edit' in content && !!content.edit;
1359
- const isPinMsg = 'pin' in content && !!content.pin;
1360
- const isPollMessage = 'poll' in content && !!content.poll;
1361
- const additionalAttributes = {};
1362
- const additionalNodes = [];
1363
- // required for delete
1364
- if (isDeleteMsg) {
1365
- // if the chat is a group, and I am not the author, then delete the message as an admin
1366
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1367
- additionalAttributes.edit = '8';
1368
- }
1369
- else {
1370
- additionalAttributes.edit = '7';
1371
- }
1372
- }
1373
- else if (isEditMsg) {
1374
- additionalAttributes.edit = '1';
1375
- }
1376
- else if (isPinMsg) {
1377
- additionalAttributes.edit = '2';
1378
- }
1379
- else if (isPollMessage) {
1380
- additionalNodes.push({
1381
- tag: 'meta',
1382
- attrs: {
1383
- polltype: 'creation'
1384
- }
1385
- });
1386
- }
1387
- else if (isEventMsg) {
1388
- additionalNodes.push({
1389
- tag: 'meta',
1390
- attrs: {
1391
- event_type: 'creation'
1392
- }
1393
- });
1394
- }
1395
- await relayMessage(jid, fullMsg.message, {
1396
- messageId: fullMsg.key.id,
1397
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1398
- additionalAttributes,
1399
- statusJidList: options.statusJidList,
1400
- additionalNodes: aiLabel ? additionalNodes : options.additionalNodes,
1401
- participant
1402
- });
1403
- if (config.emitOwnEvents) {
1404
- process.nextTick(async () => {
1405
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1406
- });
1407
- }
1408
- return fullMsg;
1409
- }
1410
- },
1411
- sendMessageMembers: async (jid, message, options = {}) => {
1412
- const {
1413
- messageId: idm,
1414
- quoted,
1415
- delayMs = 1500,
1416
- useUserDevicesCache = true,
1417
- cachedGroupMetadata,
1418
- onlyMember = true
1419
- } = options;
1420
- const { server } = jidDecode(jid);
1421
- if (server !== "g.us") throw new Error("@g.us server required");
1422
- const meId = authState.creds.me.id;
1423
- const messages = Utils_1.normalizeMessageContent(message);
1424
- const groupData = cachedGroupMetadata? await cachedGroupMetadata(jid) : await groupMetadata(jid);
1425
- const isLid = groupData.addressingMode === "lid";
1426
- const isAdmin = groupData.participants.filter((x) => x.admin !== null).map((y) => y.id)
1427
- let participantJids = groupData.participants.map(z => z.id);
1428
- if (onlyMember) {
1429
- participantJids = isAdmin ? isAdmin : participantJids;
1430
- }
1431
- logger.info(`Sending message to ${participantJids.length} members from ${jid}`);
1432
- for (let i = 0; i < participantJids.length; i++) {
1433
- const jid = participantJids[i];
1434
- if (areJidsSameUser(jid, meId)) continue;
1435
- try {
1436
- const msgId = `${idm || Utils_1.generateMessageID()}_${i}`;
1437
- const fullMsg = await Utils_1.generateWAMessageFromContent(jid, message, {
1438
- messageId: msgId,
1439
- quoted
1440
- })
1441
- await relayMessage(jid, fullMsg.message, {
1442
- messageId: fullMsg.key.id
1443
- });
1444
- logger.debug(`Message successfully sent to ${jid}`);
1445
- if (delayMs && i < participantJids.length - 1) {
1446
- await new Promise(z => setTimeout(z, delayMs));
1447
- }
1448
- } catch (e) {
1449
- logger.error({ jid, e }, "Error sending message to");
1450
- }
1451
- }
1452
- return JSON.stringify({
1453
- members_total: participantJids.length,
1454
- message
1455
- }, null, 4);
1456
- }
1457
- };
1458
- };
1459
- //# sourceMappingURL=messages-send.js.map