torbaileys 8.0.0
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/LICENSE +21 -0
- package/WAProto/WAProto.proto +5311 -0
- package/WAProto/index.js +94091 -0
- package/lib/Defaults/index.js +123 -0
- package/lib/KeyDB/BinarySearch.js +20 -0
- package/lib/KeyDB/KeyedDB.js +167 -0
- package/lib/KeyDB/index.js +4 -0
- package/lib/Signal/Group/ciphertext-message.js +13 -0
- package/lib/Signal/Group/group-session-builder.js +32 -0
- package/lib/Signal/Group/group_cipher.js +84 -0
- package/lib/Signal/Group/index.js +13 -0
- package/lib/Signal/Group/keyhelper.js +20 -0
- package/lib/Signal/Group/sender-chain-key.js +28 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
- package/lib/Signal/Group/sender-key-message.js +68 -0
- package/lib/Signal/Group/sender-key-name.js +52 -0
- package/lib/Signal/Group/sender-key-record.js +43 -0
- package/lib/Signal/Group/sender-key-state.js +86 -0
- package/lib/Signal/Group/sender-message-key.js +28 -0
- package/lib/Signal/libsignal.js +324 -0
- package/lib/Signal/lid-mapping.js +155 -0
- package/lib/Socket/Client/index.js +4 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.js +52 -0
- package/lib/Socket/Client/websocket.js.bak +53 -0
- package/lib/Socket/business.js +377 -0
- package/lib/Socket/chats.js +881 -0
- package/lib/Socket/communities.js +413 -0
- package/lib/Socket/groups.js +312 -0
- package/lib/Socket/index.js +16 -0
- package/lib/Socket/messages-recv.js +1163 -0
- package/lib/Socket/messages-send.js +1100 -0
- package/lib/Socket/mex.js +45 -0
- package/lib/Socket/newsletter.js +262 -0
- package/lib/Socket/socket.js +820 -0
- package/lib/Store/index.js +6 -0
- package/lib/Store/make-cache-manager-store.js +75 -0
- package/lib/Store/make-in-memory-store.js +290 -0
- package/lib/Store/make-ordered-dictionary.js +79 -0
- package/lib/Store/object-repository.js +25 -0
- package/lib/Types/Auth.js +3 -0
- package/lib/Types/Bussines.js +3 -0
- package/lib/Types/Call.js +3 -0
- package/lib/Types/Chat.js +9 -0
- package/lib/Types/Contact.js +3 -0
- package/lib/Types/Events.js +3 -0
- package/lib/Types/GroupMetadata.js +3 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +12 -0
- package/lib/Types/Newsletter.js +33 -0
- package/lib/Types/Newsletter.js.bak +33 -0
- package/lib/Types/Product.js +3 -0
- package/lib/Types/Signal.js +3 -0
- package/lib/Types/Socket.js +4 -0
- package/lib/Types/State.js +11 -0
- package/lib/Types/USync.js +3 -0
- package/lib/Types/index.js +28 -0
- package/lib/Utils/auth-utils.js +219 -0
- package/lib/Utils/baileys-event-stream.js +44 -0
- package/lib/Utils/browser-utils.js +25 -0
- package/lib/Utils/business.js +233 -0
- package/lib/Utils/chat-utils.js +752 -0
- package/lib/Utils/crypto.js +130 -0
- package/lib/Utils/decode-wa-message.js +267 -0
- package/lib/Utils/decode-wa-message.js.bak +267 -0
- package/lib/Utils/event-buffer.js +528 -0
- package/lib/Utils/generics.js +355 -0
- package/lib/Utils/history.js +87 -0
- package/lib/Utils/index.js +21 -0
- package/lib/Utils/link-preview.js +81 -0
- package/lib/Utils/logger.js +5 -0
- package/lib/Utils/lt-hash.js +45 -0
- package/lib/Utils/make-mutex.js +36 -0
- package/lib/Utils/message-retry-manager.js +113 -0
- package/lib/Utils/messages-media.js +601 -0
- package/lib/Utils/messages.js +907 -0
- package/lib/Utils/noise-handler.js +144 -0
- package/lib/Utils/pre-key-manager.js +85 -0
- package/lib/Utils/process-message.js +341 -0
- package/lib/Utils/signal.js +161 -0
- package/lib/Utils/use-multi-file-auth-state.js +111 -0
- package/lib/Utils/validate-connection.js +200 -0
- package/lib/WABinary/constants.js +1303 -0
- package/lib/WABinary/decode.js +240 -0
- package/lib/WABinary/encode.js +218 -0
- package/lib/WABinary/generic-utils.js +189 -0
- package/lib/WABinary/index.js +7 -0
- package/lib/WABinary/jid-utils.js +93 -0
- package/lib/WABinary/types.js +3 -0
- package/lib/WAM/BinaryInfo.js +11 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +154 -0
- package/lib/WAM/index.js +5 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
- package/lib/WAUSync/Protocols/index.js +6 -0
- package/lib/WAUSync/USyncQuery.js +90 -0
- package/lib/WAUSync/USyncUser.js +24 -0
- package/lib/WAUSync/index.js +5 -0
- package/lib/index.js +16 -0
- package/package.json +105 -0
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
import NodeCache from '@cacheable/node-cache';
|
|
2
|
+
import { Boom } from '@hapi/boom';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_CACHE_TTLS,
|
|
6
|
+
WA_DEFAULT_EPHEMERAL
|
|
7
|
+
} from '../Defaults/index.js';
|
|
8
|
+
import {
|
|
9
|
+
aggregateMessageKeysNotFromMe,
|
|
10
|
+
assertMediaContent,
|
|
11
|
+
bindWaitForEvent,
|
|
12
|
+
decryptMediaRetryData,
|
|
13
|
+
encodeNewsletterMessage,
|
|
14
|
+
encodeSignedDeviceIdentity,
|
|
15
|
+
encodeWAMessage,
|
|
16
|
+
encryptMediaRetryRequest,
|
|
17
|
+
extractDeviceJids,
|
|
18
|
+
generateMessageIDV2,
|
|
19
|
+
generateParticipantHashV2,
|
|
20
|
+
generateWAMessage,
|
|
21
|
+
getStatusCodeForMediaRetry,
|
|
22
|
+
getUrlFromDirectPath,
|
|
23
|
+
getWAUploadToServer,
|
|
24
|
+
MessageRetryManager,
|
|
25
|
+
normalizeMessageContent,
|
|
26
|
+
parseAndInjectE2ESessions,
|
|
27
|
+
unixTimestampSeconds
|
|
28
|
+
} from '../Utils/index.js';
|
|
29
|
+
import {
|
|
30
|
+
areJidsSameUser,
|
|
31
|
+
getBinaryNodeChild,
|
|
32
|
+
getBinaryNodeChildren,
|
|
33
|
+
getAdditionalNode,
|
|
34
|
+
getBinaryNodeFilter,
|
|
35
|
+
isHostedLidUser,
|
|
36
|
+
isHostedPnUser,
|
|
37
|
+
isJidGroup,
|
|
38
|
+
isLidUser,
|
|
39
|
+
isPnUser,
|
|
40
|
+
jidDecode,
|
|
41
|
+
jidEncode,
|
|
42
|
+
isJidNewsletter,
|
|
43
|
+
jidNormalizedUser,
|
|
44
|
+
S_WHATSAPP_NET
|
|
45
|
+
} from '../WABinary/index.js';
|
|
46
|
+
import { getUrlInfo } from '../Utils/link-preview.js';
|
|
47
|
+
import { makeKeyedMutex } from '../Utils/make-mutex.js';
|
|
48
|
+
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
|
|
49
|
+
import { makeNewsletterSocket } from './newsletter.js';
|
|
50
|
+
export const makeMessagesSocket = (config) => {
|
|
51
|
+
const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
|
|
52
|
+
const sock = makeNewsletterSocket(config);
|
|
53
|
+
const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
|
|
54
|
+
const userDevicesCache = config.userDevicesCache ||
|
|
55
|
+
new NodeCache({
|
|
56
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
|
57
|
+
useClones: false
|
|
58
|
+
});
|
|
59
|
+
const peerSessionsCache = new NodeCache({
|
|
60
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
61
|
+
useClones: false
|
|
62
|
+
});
|
|
63
|
+
// Initialize message retry manager if enabled
|
|
64
|
+
const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
|
|
65
|
+
// Prevent race conditions in Signal session encryption by user
|
|
66
|
+
const encryptionMutex = makeKeyedMutex();
|
|
67
|
+
let mediaConn;
|
|
68
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
69
|
+
const media = await mediaConn;
|
|
70
|
+
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
71
|
+
mediaConn = (async () => {
|
|
72
|
+
const result = await query({
|
|
73
|
+
tag: 'iq',
|
|
74
|
+
attrs: {
|
|
75
|
+
type: 'set',
|
|
76
|
+
xmlns: 'w:m',
|
|
77
|
+
to: S_WHATSAPP_NET
|
|
78
|
+
},
|
|
79
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
80
|
+
});
|
|
81
|
+
const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
|
|
82
|
+
// TODO: explore full length of data that whatsapp provides
|
|
83
|
+
const node = {
|
|
84
|
+
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
85
|
+
hostname: attrs.hostname,
|
|
86
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
87
|
+
})),
|
|
88
|
+
auth: mediaConnNode.attrs.auth,
|
|
89
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
90
|
+
fetchDate: new Date()
|
|
91
|
+
};
|
|
92
|
+
logger.debug('fetched media conn');
|
|
93
|
+
return node;
|
|
94
|
+
})();
|
|
95
|
+
}
|
|
96
|
+
return mediaConn;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* generic send receipt function
|
|
100
|
+
* used for receipts of phone call, read, delivery etc.
|
|
101
|
+
* */
|
|
102
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
103
|
+
if (!messageIds || messageIds.length === 0) {
|
|
104
|
+
throw new Boom('missing ids in receipt');
|
|
105
|
+
}
|
|
106
|
+
const node = {
|
|
107
|
+
tag: 'receipt',
|
|
108
|
+
attrs: {
|
|
109
|
+
id: messageIds[0]
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
113
|
+
if (isReadReceipt) {
|
|
114
|
+
node.attrs.t = unixTimestampSeconds().toString();
|
|
115
|
+
}
|
|
116
|
+
if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
|
|
117
|
+
node.attrs.recipient = jid;
|
|
118
|
+
node.attrs.to = participant;
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
node.attrs.to = jid;
|
|
122
|
+
if (participant) {
|
|
123
|
+
node.attrs.participant = participant;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (type) {
|
|
127
|
+
node.attrs.type = type;
|
|
128
|
+
}
|
|
129
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
130
|
+
if (remainingMessageIds.length) {
|
|
131
|
+
node.content = [
|
|
132
|
+
{
|
|
133
|
+
tag: 'list',
|
|
134
|
+
attrs: {},
|
|
135
|
+
content: remainingMessageIds.map(id => ({
|
|
136
|
+
tag: 'item',
|
|
137
|
+
attrs: { id }
|
|
138
|
+
}))
|
|
139
|
+
}
|
|
140
|
+
];
|
|
141
|
+
}
|
|
142
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
|
|
143
|
+
await sendNode(node);
|
|
144
|
+
};
|
|
145
|
+
/** Correctly bulk send receipts to multiple chats, participants */
|
|
146
|
+
const sendReceipts = async (keys, type) => {
|
|
147
|
+
const recps = aggregateMessageKeysNotFromMe(keys);
|
|
148
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
149
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
/** Bulk read messages. Keys can be from different chats & participants */
|
|
153
|
+
const readMessages = async (keys) => {
|
|
154
|
+
const privacySettings = await fetchPrivacySettings();
|
|
155
|
+
// based on privacy settings, we have to change the read type
|
|
156
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
157
|
+
await sendReceipts(keys, readType);
|
|
158
|
+
};
|
|
159
|
+
/** Fetch all the devices we've to send a message to */
|
|
160
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
161
|
+
const deviceResults = [];
|
|
162
|
+
if (!useCache) {
|
|
163
|
+
logger.debug('not using cache for devices');
|
|
164
|
+
}
|
|
165
|
+
const toFetch = [];
|
|
166
|
+
const jidsWithUser = jids
|
|
167
|
+
.map(jid => {
|
|
168
|
+
const decoded = jidDecode(jid);
|
|
169
|
+
const user = decoded?.user;
|
|
170
|
+
const device = decoded?.device;
|
|
171
|
+
const isExplicitDevice = typeof device === 'number' && device >= 0;
|
|
172
|
+
if (isExplicitDevice && user) {
|
|
173
|
+
deviceResults.push({
|
|
174
|
+
user,
|
|
175
|
+
device,
|
|
176
|
+
jid
|
|
177
|
+
});
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
jid = jidNormalizedUser(jid);
|
|
181
|
+
return { jid, user };
|
|
182
|
+
})
|
|
183
|
+
.filter(jid => jid !== null);
|
|
184
|
+
let mgetDevices;
|
|
185
|
+
if (useCache && userDevicesCache.mget) {
|
|
186
|
+
const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
|
|
187
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
188
|
+
}
|
|
189
|
+
for (const { jid, user } of jidsWithUser) {
|
|
190
|
+
if (useCache) {
|
|
191
|
+
const devices = mgetDevices?.[user] ||
|
|
192
|
+
(userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
|
|
193
|
+
if (devices) {
|
|
194
|
+
const devicesWithJid = devices.map(d => ({
|
|
195
|
+
...d,
|
|
196
|
+
jid: jidEncode(d.user, d.server, d.device)
|
|
197
|
+
}));
|
|
198
|
+
deviceResults.push(...devicesWithJid);
|
|
199
|
+
logger.trace({ user }, 'using cache for devices');
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
toFetch.push(jid);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
toFetch.push(jid);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (!toFetch.length) {
|
|
210
|
+
return deviceResults;
|
|
211
|
+
}
|
|
212
|
+
const requestedLidUsers = new Set();
|
|
213
|
+
for (const jid of toFetch) {
|
|
214
|
+
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
215
|
+
const user = jidDecode(jid)?.user;
|
|
216
|
+
if (user)
|
|
217
|
+
requestedLidUsers.add(user);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
|
|
221
|
+
for (const jid of toFetch) {
|
|
222
|
+
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
|
|
223
|
+
}
|
|
224
|
+
const result = await sock.executeUSyncQuery(query);
|
|
225
|
+
if (result) {
|
|
226
|
+
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
227
|
+
const lidResults = result.list.filter(a => !!a.lid);
|
|
228
|
+
if (lidResults.length > 0) {
|
|
229
|
+
logger.trace('Storing LID maps from device call');
|
|
230
|
+
await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
|
|
231
|
+
}
|
|
232
|
+
const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
|
|
233
|
+
const deviceMap = {};
|
|
234
|
+
for (const item of extracted) {
|
|
235
|
+
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
236
|
+
deviceMap[item.user]?.push(item);
|
|
237
|
+
}
|
|
238
|
+
// Process each user's devices as a group for bulk LID migration
|
|
239
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
240
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
241
|
+
// Process all devices for this user
|
|
242
|
+
for (const item of userDevices) {
|
|
243
|
+
const finalJid = isLidUser
|
|
244
|
+
? jidEncode(user, item.server, item.device)
|
|
245
|
+
: jidEncode(item.user, item.server, item.device);
|
|
246
|
+
deviceResults.push({
|
|
247
|
+
...item,
|
|
248
|
+
jid: finalJid
|
|
249
|
+
});
|
|
250
|
+
logger.debug({
|
|
251
|
+
user: item.user,
|
|
252
|
+
device: item.device,
|
|
253
|
+
finalJid,
|
|
254
|
+
usedLid: isLidUser
|
|
255
|
+
}, 'Processed device with LID priority');
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (userDevicesCache.mset) {
|
|
259
|
+
// if the cache supports mset, we can set all devices in one go
|
|
260
|
+
await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
for (const key in deviceMap) {
|
|
264
|
+
if (deviceMap[key])
|
|
265
|
+
await userDevicesCache.set(key, deviceMap[key]);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const userDeviceUpdates = {};
|
|
269
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
270
|
+
if (devices && devices.length > 0) {
|
|
271
|
+
userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
275
|
+
try {
|
|
276
|
+
await authState.keys.set({ 'device-list': userDeviceUpdates });
|
|
277
|
+
logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
logger.warn({ error }, 'failed to store user device lists');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return deviceResults;
|
|
285
|
+
};
|
|
286
|
+
const assertSessions = async (jids) => {
|
|
287
|
+
let didFetchNewSession = false;
|
|
288
|
+
const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
|
|
289
|
+
const jidsRequiringFetch = [];
|
|
290
|
+
logger.debug({ jids }, 'assertSessions call with jids');
|
|
291
|
+
// Check peerSessionsCache and validate sessions using libsignal loadSession
|
|
292
|
+
for (const jid of uniqueJids) {
|
|
293
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(jid);
|
|
294
|
+
const cachedSession = peerSessionsCache.get(signalId);
|
|
295
|
+
if (cachedSession !== undefined) {
|
|
296
|
+
if (cachedSession) {
|
|
297
|
+
continue; // Session exists in cache
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
else {
|
|
301
|
+
const sessionValidation = await signalRepository.validateSession(jid);
|
|
302
|
+
const hasSession = sessionValidation.exists;
|
|
303
|
+
peerSessionsCache.set(signalId, hasSession);
|
|
304
|
+
if (hasSession) {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
jidsRequiringFetch.push(jid);
|
|
309
|
+
}
|
|
310
|
+
if (jidsRequiringFetch.length) {
|
|
311
|
+
// LID if mapped, otherwise original
|
|
312
|
+
const wireJids = [
|
|
313
|
+
...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
314
|
+
...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
|
|
315
|
+
];
|
|
316
|
+
logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
|
|
317
|
+
const result = await query({
|
|
318
|
+
tag: 'iq',
|
|
319
|
+
attrs: {
|
|
320
|
+
xmlns: 'encrypt',
|
|
321
|
+
type: 'get',
|
|
322
|
+
to: S_WHATSAPP_NET
|
|
323
|
+
},
|
|
324
|
+
content: [
|
|
325
|
+
{
|
|
326
|
+
tag: 'key',
|
|
327
|
+
attrs: {},
|
|
328
|
+
content: wireJids.map(jid => ({
|
|
329
|
+
tag: 'user',
|
|
330
|
+
attrs: { jid }
|
|
331
|
+
}))
|
|
332
|
+
}
|
|
333
|
+
]
|
|
334
|
+
});
|
|
335
|
+
await parseAndInjectE2ESessions(result, signalRepository);
|
|
336
|
+
didFetchNewSession = true;
|
|
337
|
+
// Cache fetched sessions using wire JIDs
|
|
338
|
+
for (const wireJid of wireJids) {
|
|
339
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
|
|
340
|
+
peerSessionsCache.set(signalId, true);
|
|
341
|
+
}
|
|
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
|
+
if (!jid)
|
|
385
|
+
return null;
|
|
386
|
+
let msgToEncrypt = patchedMessage;
|
|
387
|
+
if (dsmMessage) {
|
|
388
|
+
const { user: targetUser } = jidDecode(jid);
|
|
389
|
+
const { user: ownPnUser } = jidDecode(meId);
|
|
390
|
+
const ownLidUser = meLidUser;
|
|
391
|
+
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
|
|
392
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
393
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
394
|
+
msgToEncrypt = dsmMessage;
|
|
395
|
+
logger.debug({ jid, targetUser }, 'Using DSM for own device');
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const bytes = encodeWAMessage(msgToEncrypt);
|
|
399
|
+
const mutexKey = jid;
|
|
400
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
401
|
+
const { type, ciphertext } = await signalRepository.encryptMessage({
|
|
402
|
+
jid,
|
|
403
|
+
data: bytes
|
|
404
|
+
});
|
|
405
|
+
if (type === 'pkmsg') {
|
|
406
|
+
shouldIncludeDeviceIdentity = true;
|
|
407
|
+
}
|
|
408
|
+
return {
|
|
409
|
+
tag: 'to',
|
|
410
|
+
attrs: { jid },
|
|
411
|
+
content: [
|
|
412
|
+
{
|
|
413
|
+
tag: 'enc',
|
|
414
|
+
attrs: {
|
|
415
|
+
v: '2',
|
|
416
|
+
type,
|
|
417
|
+
...(extraAttrs || {})
|
|
418
|
+
},
|
|
419
|
+
content: ciphertext
|
|
420
|
+
}
|
|
421
|
+
]
|
|
422
|
+
};
|
|
423
|
+
});
|
|
424
|
+
return node;
|
|
425
|
+
});
|
|
426
|
+
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
|
|
427
|
+
return { nodes, shouldIncludeDeviceIdentity };
|
|
428
|
+
};
|
|
429
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
|
|
430
|
+
// let shouldIncludeDeviceIdentity = false;
|
|
431
|
+
let didPushAdditional = false
|
|
432
|
+
const meId = authState.creds.me.id;
|
|
433
|
+
const meLid = authState.creds.me?.lid;
|
|
434
|
+
const isRetryResend = Boolean(participant?.jid);
|
|
435
|
+
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
436
|
+
const statusJid = 'status@broadcast';
|
|
437
|
+
const { user, server } = jidDecode(jid);
|
|
438
|
+
const isGroup = server === 'g.us';
|
|
439
|
+
const isStatus = jid === statusJid;
|
|
440
|
+
const isLid = server === 'lid';
|
|
441
|
+
const isNewsletter = server === 'newsletter';
|
|
442
|
+
const isPrivate = server === 's.whatsapp.net'
|
|
443
|
+
const finalJid = jid;
|
|
444
|
+
msgId = msgId || generateMessageIDV2(meId);
|
|
445
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
446
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
447
|
+
const participants = [];
|
|
448
|
+
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
449
|
+
const binaryNodeContent = [];
|
|
450
|
+
const devices = [];
|
|
451
|
+
const meMsg = {
|
|
452
|
+
deviceSentMessage: {
|
|
453
|
+
destinationJid,
|
|
454
|
+
message
|
|
455
|
+
},
|
|
456
|
+
messageContextInfo: message.messageContextInfo
|
|
457
|
+
};
|
|
458
|
+
const extraAttrs = {};
|
|
459
|
+
const messages = normalizeMessageContent(message)
|
|
460
|
+
const buttonType = getButtonType(messages);
|
|
461
|
+
if (participant) {
|
|
462
|
+
if (!isGroup && !isStatus) {
|
|
463
|
+
additionalAttributes = {
|
|
464
|
+
...additionalAttributes,
|
|
465
|
+
device_fanout: 'false'
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
const { user, device } = jidDecode(participant.jid);
|
|
469
|
+
devices.push({
|
|
470
|
+
user,
|
|
471
|
+
device,
|
|
472
|
+
jid: participant.jid
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
await authState.keys.transaction(async () => {
|
|
476
|
+
const mediaType = getMediaType(message);
|
|
477
|
+
if (mediaType) {
|
|
478
|
+
extraAttrs['mediatype'] = mediaType;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (isNewsletter) {
|
|
482
|
+
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
|
|
483
|
+
const bytes = encodeNewsletterMessage(patched);
|
|
484
|
+
binaryNodeContent.push({
|
|
485
|
+
tag: "plaintext",
|
|
486
|
+
attrs: mediaType ? { mediatype: mediaType } : {},
|
|
487
|
+
content: bytes
|
|
488
|
+
});
|
|
489
|
+
const stanza = {
|
|
490
|
+
tag: "message",
|
|
491
|
+
attrs: {
|
|
492
|
+
to: jid,
|
|
493
|
+
id: msgId,
|
|
494
|
+
type: getTypeMessage(message),
|
|
495
|
+
...(additionalAttributes || {})
|
|
496
|
+
},
|
|
497
|
+
content: binaryNodeContent
|
|
498
|
+
};
|
|
499
|
+
logger.debug({ msgId }, `sending newsletter message to ${jid}`);
|
|
500
|
+
await sendNode(stanza);
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
|
|
505
|
+
extraAttrs['decrypt-fail'] = 'hide'
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
|
|
509
|
+
extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if (isGroup || isStatus) {
|
|
513
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
514
|
+
(async () => {
|
|
515
|
+
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
|
|
516
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
517
|
+
logger.trace({
|
|
518
|
+
jid,
|
|
519
|
+
participants: groupData.participants.length
|
|
520
|
+
}, 'using cached group metadata');
|
|
521
|
+
}
|
|
522
|
+
else if (!isStatus) {
|
|
523
|
+
groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
524
|
+
}
|
|
525
|
+
return groupData;
|
|
526
|
+
})(),
|
|
527
|
+
(async () => {
|
|
528
|
+
if (!participant && !isStatus) {
|
|
529
|
+
// what if sender memory is less accurate than the cached metadata
|
|
530
|
+
// on participant change in group, we should do sender memory manipulation
|
|
531
|
+
const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
|
|
532
|
+
return result[jid] || {};
|
|
533
|
+
}
|
|
534
|
+
return {};
|
|
535
|
+
})()
|
|
536
|
+
]);
|
|
537
|
+
if (!participant) {
|
|
538
|
+
const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
|
|
539
|
+
if (isStatus && statusJidList) {
|
|
540
|
+
participantsList.push(...statusJidList);
|
|
541
|
+
}
|
|
542
|
+
// if (!isStatus) {
|
|
543
|
+
// additionalAttributes = {
|
|
544
|
+
// ...additionalAttributes,
|
|
545
|
+
// addressing_mode: groupData?.addressingMode || 'pn'
|
|
546
|
+
// };
|
|
547
|
+
// }
|
|
548
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
|
|
549
|
+
devices.push(...additionalDevices);
|
|
550
|
+
}
|
|
551
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
552
|
+
additionalAttributes = {
|
|
553
|
+
...additionalAttributes,
|
|
554
|
+
expiration: groupData.ephemeralDuration.toString()
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
const patched = await patchMessageBeforeSending(message);
|
|
558
|
+
if (Array.isArray(patched)) {
|
|
559
|
+
throw new Boom('Per-jid patching is not supported in groups');
|
|
560
|
+
}
|
|
561
|
+
const bytes = encodeWAMessage(patched);
|
|
562
|
+
const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
|
|
563
|
+
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
|
|
564
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
565
|
+
group: destinationJid,
|
|
566
|
+
data: bytes,
|
|
567
|
+
meId: groupSenderIdentity
|
|
568
|
+
});
|
|
569
|
+
const senderKeyRecipients = [];
|
|
570
|
+
for (const device of devices) {
|
|
571
|
+
const deviceJid = device.jid;
|
|
572
|
+
const hasKey = !!senderKeyMap[deviceJid];
|
|
573
|
+
if ((!hasKey || !!participant) &&
|
|
574
|
+
!isHostedLidUser(deviceJid) &&
|
|
575
|
+
!isHostedPnUser(deviceJid) &&
|
|
576
|
+
device.device !== 99) {
|
|
577
|
+
//todo: revamp all this logic
|
|
578
|
+
// the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
|
|
579
|
+
senderKeyRecipients.push(deviceJid);
|
|
580
|
+
senderKeyMap[deviceJid] = true;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
if (senderKeyRecipients.length) {
|
|
584
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
|
|
585
|
+
const senderKeyMsg = {
|
|
586
|
+
senderKeyDistributionMessage: {
|
|
587
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
588
|
+
groupId: destinationJid
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
const senderKeySessionTargets = senderKeyRecipients;
|
|
592
|
+
await assertSessions(senderKeySessionTargets);
|
|
593
|
+
const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
|
|
594
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
595
|
+
participants.push(...result.nodes);
|
|
596
|
+
}
|
|
597
|
+
if (isRetryResend) {
|
|
598
|
+
const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
|
|
599
|
+
data: bytes,
|
|
600
|
+
jid: participant?.jid
|
|
601
|
+
});
|
|
602
|
+
binaryNodeContent.push({
|
|
603
|
+
tag: 'enc',
|
|
604
|
+
attrs: {
|
|
605
|
+
v: '2',
|
|
606
|
+
type,
|
|
607
|
+
count: participant.count.toString()
|
|
608
|
+
},
|
|
609
|
+
content: encryptedContent
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
binaryNodeContent.push({
|
|
614
|
+
tag: 'enc',
|
|
615
|
+
attrs: {
|
|
616
|
+
v: '2',
|
|
617
|
+
type: 'skmsg',
|
|
618
|
+
...extraAttrs
|
|
619
|
+
},
|
|
620
|
+
content: ciphertext
|
|
621
|
+
});
|
|
622
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
627
|
+
// TODO: investigate if this is true
|
|
628
|
+
let ownId = meId;
|
|
629
|
+
if (isLid && meLid) {
|
|
630
|
+
ownId = meLid;
|
|
631
|
+
logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
|
|
632
|
+
}
|
|
633
|
+
else {
|
|
634
|
+
logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
|
|
635
|
+
}
|
|
636
|
+
const { user: ownUser } = jidDecode(ownId);
|
|
637
|
+
if (!participant) {
|
|
638
|
+
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
639
|
+
devices.push({
|
|
640
|
+
user,
|
|
641
|
+
device: 0,
|
|
642
|
+
jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
|
|
643
|
+
});
|
|
644
|
+
if (user !== ownUser) {
|
|
645
|
+
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
646
|
+
const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
|
|
647
|
+
devices.push({
|
|
648
|
+
user: ownUserForAddressing,
|
|
649
|
+
device: 0,
|
|
650
|
+
jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
654
|
+
// Clear placeholders and enumerate actual devices
|
|
655
|
+
devices.length = 0;
|
|
656
|
+
// Use conversation-appropriate sender identity
|
|
657
|
+
const senderIdentity = isLid && meLid
|
|
658
|
+
? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
|
|
659
|
+
: jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
|
|
660
|
+
// Enumerate devices for sender and target with consistent addressing
|
|
661
|
+
const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
|
|
662
|
+
devices.push(...sessionDevices);
|
|
663
|
+
logger.debug({
|
|
664
|
+
deviceCount: devices.length,
|
|
665
|
+
devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
|
|
666
|
+
}, 'Device enumeration complete with unified addressing');
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
const allRecipients = [];
|
|
670
|
+
const meRecipients = [];
|
|
671
|
+
const otherRecipients = [];
|
|
672
|
+
const { user: mePnUser } = jidDecode(meId);
|
|
673
|
+
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
|
|
674
|
+
for (const { user, jid } of devices) {
|
|
675
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
676
|
+
if (isExactSenderDevice) {
|
|
677
|
+
logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
// Check if this is our device (could match either PN or LID user)
|
|
681
|
+
const isMe = user === mePnUser || user === meLidUser;
|
|
682
|
+
if (isMe) {
|
|
683
|
+
meRecipients.push(jid);
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
otherRecipients.push(jid);
|
|
687
|
+
}
|
|
688
|
+
allRecipients.push(jid);
|
|
689
|
+
}
|
|
690
|
+
await assertSessions(allRecipients);
|
|
691
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
692
|
+
// For own devices: use DSM if available (1:1 chats only)
|
|
693
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
694
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
|
|
695
|
+
]);
|
|
696
|
+
participants.push(...meNodes);
|
|
697
|
+
participants.push(...otherNodes);
|
|
698
|
+
/* if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
699
|
+
extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
|
|
700
|
+
}*/
|
|
701
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
702
|
+
}
|
|
703
|
+
if (participants.length) {
|
|
704
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
705
|
+
const peerNode = participants[0]?.content?.[0];
|
|
706
|
+
if (peerNode) {
|
|
707
|
+
binaryNodeContent.push(peerNode); // push only enc
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
binaryNodeContent.push({
|
|
712
|
+
tag: 'participants',
|
|
713
|
+
attrs: {},
|
|
714
|
+
content: participants
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
const stanza = {
|
|
719
|
+
tag: 'message',
|
|
720
|
+
attrs: {
|
|
721
|
+
id: msgId,
|
|
722
|
+
to: destinationJid,
|
|
723
|
+
type: getTypeMessage(messages),
|
|
724
|
+
...(additionalAttributes || {})
|
|
725
|
+
},
|
|
726
|
+
content: binaryNodeContent
|
|
727
|
+
};
|
|
728
|
+
// if the participant to send to is explicitly specified (generally retry recp)
|
|
729
|
+
// ensure the message is only sent to that person
|
|
730
|
+
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
731
|
+
if (participant) {
|
|
732
|
+
if (isJidGroup(destinationJid)) {
|
|
733
|
+
stanza.attrs.to = destinationJid;
|
|
734
|
+
stanza.attrs.participant = participant.jid;
|
|
735
|
+
}
|
|
736
|
+
else if (areJidsSameUser(participant.jid, meId)) {
|
|
737
|
+
stanza.attrs.to = participant.jid;
|
|
738
|
+
stanza.attrs.recipient = destinationJid;
|
|
739
|
+
}
|
|
740
|
+
else {
|
|
741
|
+
stanza.attrs.to = participant.jid;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
else {
|
|
745
|
+
stanza.attrs.to = destinationJid;
|
|
746
|
+
}
|
|
747
|
+
if (shouldIncludeDeviceIdentity) {
|
|
748
|
+
;
|
|
749
|
+
stanza.content.push({
|
|
750
|
+
tag: 'device-identity',
|
|
751
|
+
attrs: {},
|
|
752
|
+
content: encodeSignedDeviceIdentity(authState.creds.account, true)
|
|
753
|
+
});
|
|
754
|
+
logger.debug({ jid }, 'adding device identity');
|
|
755
|
+
}
|
|
756
|
+
if (AI && isPrivate) {
|
|
757
|
+
const botNode = {
|
|
758
|
+
tag: 'bot',
|
|
759
|
+
attrs: {
|
|
760
|
+
biz_bot: '1'
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
|
|
765
|
+
|
|
766
|
+
if (filteredBizBot) {
|
|
767
|
+
stanza.content.push(...additionalNodes)
|
|
768
|
+
didPushAdditional = true
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
else {
|
|
772
|
+
stanza.content.push(botNode)
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
if(buttonType && !isStatus) {
|
|
777
|
+
const content = getAdditionalNode(buttonType)
|
|
778
|
+
const filteredNode = getBinaryNodeFilter(additionalNodes)
|
|
779
|
+
|
|
780
|
+
if (filteredNode) {
|
|
781
|
+
didPushAdditional = true
|
|
782
|
+
stanza.content.push(...additionalNodes)
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
stanza.content.push(...content)
|
|
786
|
+
}
|
|
787
|
+
logger.debug({ jid }, 'adding business node')
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
|
|
791
|
+
stanza.content.push(...additionalNodes);
|
|
792
|
+
}
|
|
793
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`);
|
|
794
|
+
await sendNode(stanza);
|
|
795
|
+
// Add message to retry cache if enabled
|
|
796
|
+
if (messageRetryManager && !participant) {
|
|
797
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
798
|
+
}
|
|
799
|
+
}, meId);
|
|
800
|
+
return msgId;
|
|
801
|
+
};
|
|
802
|
+
const getTypeMessage = (msg) => {
|
|
803
|
+
if (msg.viewOnceMessage) {
|
|
804
|
+
return getTypeMessage(msg.viewOnceMessage.message);
|
|
805
|
+
}
|
|
806
|
+
else if (msg.viewOnceMessageV2) {
|
|
807
|
+
return getTypeMessage(msg.viewOnceMessageV2.message);
|
|
808
|
+
}
|
|
809
|
+
else if (msg.viewOnceMessageV2Extension) {
|
|
810
|
+
return getTypeMessage(msg.viewOnceMessageV2Extension.message);
|
|
811
|
+
}
|
|
812
|
+
else if (msg.ephemeralMessage) {
|
|
813
|
+
return getTypeMessage(msg.ephemeralMessage.message);
|
|
814
|
+
}
|
|
815
|
+
else if (msg.documentWithCaptionMessage) {
|
|
816
|
+
return getTypeMessage(msg.documentWithCaptionMessage.message);
|
|
817
|
+
}
|
|
818
|
+
else if (msg.reactionMessage) {
|
|
819
|
+
return 'reaction';
|
|
820
|
+
}
|
|
821
|
+
else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
|
|
822
|
+
return 'poll';
|
|
823
|
+
}
|
|
824
|
+
else if (getMediaType(msg)) {
|
|
825
|
+
return 'media';
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
return 'text';
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
const getMediaType = (message) => {
|
|
832
|
+
if (message.imageMessage) {
|
|
833
|
+
return 'image'
|
|
834
|
+
}
|
|
835
|
+
else if (message.videoMessage) {
|
|
836
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
|
837
|
+
}
|
|
838
|
+
else if (message.audioMessage) {
|
|
839
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
|
840
|
+
}
|
|
841
|
+
else if (message.contactMessage) {
|
|
842
|
+
return 'vcard'
|
|
843
|
+
}
|
|
844
|
+
else if (message.documentMessage) {
|
|
845
|
+
return 'document'
|
|
846
|
+
}
|
|
847
|
+
else if (message.contactsArrayMessage) {
|
|
848
|
+
return 'contact_array'
|
|
849
|
+
}
|
|
850
|
+
else if (message.liveLocationMessage) {
|
|
851
|
+
return 'livelocation'
|
|
852
|
+
}
|
|
853
|
+
else if (message.stickerMessage) {
|
|
854
|
+
return 'sticker'
|
|
855
|
+
}
|
|
856
|
+
else if (message.listMessage) {
|
|
857
|
+
return 'list'
|
|
858
|
+
}
|
|
859
|
+
else if (message.listResponseMessage) {
|
|
860
|
+
return 'list_response'
|
|
861
|
+
}
|
|
862
|
+
else if (message.buttonsResponseMessage) {
|
|
863
|
+
return 'buttons_response'
|
|
864
|
+
}
|
|
865
|
+
else if (message.orderMessage) {
|
|
866
|
+
return 'order'
|
|
867
|
+
}
|
|
868
|
+
else if (message.productMessage) {
|
|
869
|
+
return 'product'
|
|
870
|
+
}
|
|
871
|
+
else if (message.interactiveResponseMessage) {
|
|
872
|
+
return 'native_flow_response'
|
|
873
|
+
}
|
|
874
|
+
else if (message.groupInviteMessage) {
|
|
875
|
+
return 'url'
|
|
876
|
+
}
|
|
877
|
+
else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
878
|
+
return 'productlink'
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
const getButtonType = (message) => {
|
|
882
|
+
if (message.listMessage) {
|
|
883
|
+
return 'list'
|
|
884
|
+
}
|
|
885
|
+
else if (message.buttonsMessage) {
|
|
886
|
+
return 'buttons'
|
|
887
|
+
}
|
|
888
|
+
else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
|
|
889
|
+
return 'review_and_pay'
|
|
890
|
+
}
|
|
891
|
+
else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
|
|
892
|
+
return 'review_order'
|
|
893
|
+
}
|
|
894
|
+
else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
|
|
895
|
+
return 'payment_info'
|
|
896
|
+
}
|
|
897
|
+
else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
|
|
898
|
+
return 'payment_status'
|
|
899
|
+
}
|
|
900
|
+
else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
|
|
901
|
+
return 'payment_method'
|
|
902
|
+
}
|
|
903
|
+
else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
|
|
904
|
+
return 'interactive'
|
|
905
|
+
}
|
|
906
|
+
else if (message.interactiveMessage?.nativeFlowMessage) {
|
|
907
|
+
return 'native_flow'
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
const getPrivacyTokens = async (jids) => {
|
|
911
|
+
const t = unixTimestampSeconds().toString();
|
|
912
|
+
const result = await query({
|
|
913
|
+
tag: 'iq',
|
|
914
|
+
attrs: {
|
|
915
|
+
to: S_WHATSAPP_NET,
|
|
916
|
+
type: 'set',
|
|
917
|
+
xmlns: 'privacy'
|
|
918
|
+
},
|
|
919
|
+
content: [
|
|
920
|
+
{
|
|
921
|
+
tag: 'tokens',
|
|
922
|
+
attrs: {},
|
|
923
|
+
content: jids.map(jid => ({
|
|
924
|
+
tag: 'token',
|
|
925
|
+
attrs: {
|
|
926
|
+
jid: jidNormalizedUser(jid),
|
|
927
|
+
t,
|
|
928
|
+
type: 'trusted_contact'
|
|
929
|
+
}
|
|
930
|
+
}))
|
|
931
|
+
}
|
|
932
|
+
]
|
|
933
|
+
});
|
|
934
|
+
return result;
|
|
935
|
+
};
|
|
936
|
+
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
|
|
937
|
+
const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
|
|
938
|
+
return {
|
|
939
|
+
...sock,
|
|
940
|
+
getPrivacyTokens,
|
|
941
|
+
assertSessions,
|
|
942
|
+
relayMessage,
|
|
943
|
+
sendReceipt,
|
|
944
|
+
sendReceipts,
|
|
945
|
+
readMessages,
|
|
946
|
+
refreshMediaConn,
|
|
947
|
+
waUploadToServer,
|
|
948
|
+
fetchPrivacySettings,
|
|
949
|
+
sendPeerDataOperationMessage,
|
|
950
|
+
createParticipantNodes,
|
|
951
|
+
getUSyncDevices,
|
|
952
|
+
messageRetryManager,
|
|
953
|
+
updateMediaMessage: async (message) => {
|
|
954
|
+
const content = assertMediaContent(message.message);
|
|
955
|
+
const mediaKey = content.mediaKey;
|
|
956
|
+
const meId = authState.creds.me.id;
|
|
957
|
+
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
|
|
958
|
+
let error = undefined;
|
|
959
|
+
await Promise.all([
|
|
960
|
+
sendNode(node),
|
|
961
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
962
|
+
const result = update.find(c => c.key.id === message.key.id);
|
|
963
|
+
if (result) {
|
|
964
|
+
if (result.error) {
|
|
965
|
+
error = result.error;
|
|
966
|
+
}
|
|
967
|
+
else {
|
|
968
|
+
try {
|
|
969
|
+
const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
|
|
970
|
+
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
971
|
+
const resultStr = proto.MediaRetryNotification.ResultType[media.result];
|
|
972
|
+
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
|
973
|
+
data: media,
|
|
974
|
+
statusCode: getStatusCodeForMediaRetry(media.result) || 404
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
content.directPath = media.directPath;
|
|
978
|
+
content.url = getUrlFromDirectPath(content.directPath);
|
|
979
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
|
|
980
|
+
}
|
|
981
|
+
catch (err) {
|
|
982
|
+
error = err;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return true;
|
|
986
|
+
}
|
|
987
|
+
})
|
|
988
|
+
]);
|
|
989
|
+
if (error) {
|
|
990
|
+
throw error;
|
|
991
|
+
}
|
|
992
|
+
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
|
|
993
|
+
return message;
|
|
994
|
+
},
|
|
995
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
996
|
+
const userJid = authState.creds.me.id;
|
|
997
|
+
if (typeof content === 'object' &&
|
|
998
|
+
'disappearingMessagesInChat' in content &&
|
|
999
|
+
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
|
1000
|
+
isJidGroup(jid)) {
|
|
1001
|
+
const { disappearingMessagesInChat } = content;
|
|
1002
|
+
const value = typeof disappearingMessagesInChat === 'boolean'
|
|
1003
|
+
? disappearingMessagesInChat
|
|
1004
|
+
? WA_DEFAULT_EPHEMERAL
|
|
1005
|
+
: 0
|
|
1006
|
+
: disappearingMessagesInChat;
|
|
1007
|
+
await groupToggleEphemeral(jid, value);
|
|
1008
|
+
}
|
|
1009
|
+
else {
|
|
1010
|
+
const fullMsg = await generateWAMessage(jid, content, {
|
|
1011
|
+
logger,
|
|
1012
|
+
userJid,
|
|
1013
|
+
getUrlInfo: text => getUrlInfo(text, {
|
|
1014
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1015
|
+
fetchOpts: {
|
|
1016
|
+
timeout: 3000,
|
|
1017
|
+
...(httpRequestOptions || {})
|
|
1018
|
+
},
|
|
1019
|
+
logger,
|
|
1020
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
1021
|
+
}),
|
|
1022
|
+
//TODO: CACHE
|
|
1023
|
+
getProfilePicUrl: sock.profilePictureUrl,
|
|
1024
|
+
getCallLink: sock.createCallLink,
|
|
1025
|
+
upload: async (readStream, opts) => {
|
|
1026
|
+
const up = await waUploadToServer(readStream, {
|
|
1027
|
+
...opts,
|
|
1028
|
+
newsletter: isJidNewsletter(jid)
|
|
1029
|
+
});
|
|
1030
|
+
return up;
|
|
1031
|
+
},
|
|
1032
|
+
mediaCache: config.mediaCache,
|
|
1033
|
+
options: config.options,
|
|
1034
|
+
messageId: generateMessageIDV2(sock.user?.id),
|
|
1035
|
+
...options
|
|
1036
|
+
});
|
|
1037
|
+
const isAiMsg = 'ai' in content && !!content.ai;
|
|
1038
|
+
const isEventMsg = 'event' in content && !!content.event;
|
|
1039
|
+
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
1040
|
+
const isEditMsg = 'edit' in content && !!content.edit;
|
|
1041
|
+
const isPinMsg = 'pin' in content && !!content.pin;
|
|
1042
|
+
const isPollMessage = 'poll' in content && !!content.poll;
|
|
1043
|
+
const additionalAttributes = {};
|
|
1044
|
+
const additionalNodes = [];
|
|
1045
|
+
// required for delete
|
|
1046
|
+
if (isDeleteMsg) {
|
|
1047
|
+
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
1048
|
+
if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
|
|
1049
|
+
additionalAttributes.edit = '8';
|
|
1050
|
+
}
|
|
1051
|
+
else {
|
|
1052
|
+
additionalAttributes.edit = '7';
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
else if (isEditMsg) {
|
|
1056
|
+
additionalAttributes.edit = '1';
|
|
1057
|
+
}
|
|
1058
|
+
else if (isAiMsg) {
|
|
1059
|
+
additionalNodes.push({
|
|
1060
|
+
attrs: {
|
|
1061
|
+
biz_bot: '1'
|
|
1062
|
+
}, tag: "bot"
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
else if (isPinMsg) {
|
|
1066
|
+
additionalAttributes.edit = '2';
|
|
1067
|
+
}
|
|
1068
|
+
else if (isPollMessage) {
|
|
1069
|
+
additionalNodes.push({
|
|
1070
|
+
tag: 'meta',
|
|
1071
|
+
attrs: {
|
|
1072
|
+
polltype: 'creation'
|
|
1073
|
+
}
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
else if (isEventMsg) {
|
|
1077
|
+
additionalNodes.push({
|
|
1078
|
+
tag: 'meta',
|
|
1079
|
+
attrs: {
|
|
1080
|
+
event_type: 'creation'
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
await relayMessage(jid, fullMsg.message, {
|
|
1085
|
+
messageId: fullMsg.key.id,
|
|
1086
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1087
|
+
additionalAttributes,
|
|
1088
|
+
statusJidList: options.statusJidList,
|
|
1089
|
+
additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
|
|
1090
|
+
});
|
|
1091
|
+
if (config.emitOwnEvents) {
|
|
1092
|
+
process.nextTick(() => {
|
|
1093
|
+
processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
return fullMsg;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
};
|