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