zeroz-baileys 0.0.1-security → 1.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.
Potentially problematic release.
This version of zeroz-baileys might be problematic. Click here for more details.
- package/LICENSE +21 -0
- package/WAProto/index.js +169661 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/constants.js +1 -0
- package/lib/Defaults/index.js +149 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.js +64 -0
- package/lib/Signal/Group/group_cipher.js +96 -0
- package/lib/Signal/Group/index.js +57 -0
- package/lib/Signal/Group/keyhelper.js +55 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Signal/Group/sender-chain-key.js +34 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.js +51 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-state.js +99 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.js +174 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.js +19 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/web-socket-client.js +62 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.js +1002 -0
- package/lib/Socket/dugong.js +776 -0
- package/lib/Socket/groups.js +317 -0
- package/lib/Socket/index.js +11 -0
- package/lib/Socket/messages-recv.js +1104 -0
- package/lib/Socket/messages-send.js +1022 -0
- package/lib/Socket/newsletter.js +441 -0
- package/lib/Socket/registration.js +166 -0
- package/lib/Socket/socket.js +665 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.js +427 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Newsletter.js +38 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +42 -0
- package/lib/Utils/auth-utils.js +206 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.js +729 -0
- package/lib/Utils/crypto.js +167 -0
- package/lib/Utils/decode-wa-message.js +199 -0
- package/lib/Utils/event-buffer.js +514 -0
- package/lib/Utils/generics.js +498 -0
- package/lib/Utils/history.js +96 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.js +93 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.js +43 -0
- package/lib/Utils/messages-media.js +865 -0
- package/lib/Utils/messages.js +960 -0
- package/lib/Utils/noise-handler.js +155 -0
- package/lib/Utils/process-message.js +321 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.js +119 -0
- package/lib/Utils/validate-connection.js +229 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.js +252 -0
- package/lib/WABinary/encode.js +265 -0
- package/lib/WABinary/generic-utils.js +198 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.js +89 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.js +65 -0
- package/package.json +103 -4
- package/README.md +0 -5
|
@@ -0,0 +1,1022 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.makeMessagesSocket = void 0;
|
|
7
|
+
const boom_1 = require("@hapi/boom");
|
|
8
|
+
const node_cache_1 = __importDefault(require("node-cache"));
|
|
9
|
+
const WAProto_1 = require("../../WAProto");
|
|
10
|
+
const Defaults_1 = require("../Defaults");
|
|
11
|
+
const Types_1 = require("../Types");
|
|
12
|
+
const Utils_1 = require("../Utils");
|
|
13
|
+
const link_preview_1 = require("../Utils/link-preview");
|
|
14
|
+
const WABinary_1 = require("../WABinary");
|
|
15
|
+
const newsletter_1 = require("./newsletter");
|
|
16
|
+
const WAUSync_1 = require("../WAUSync");
|
|
17
|
+
const Z = require('./dugong');
|
|
18
|
+
const makeMessagesSocket = (config) => {
|
|
19
|
+
const {
|
|
20
|
+
logger,
|
|
21
|
+
linkPreviewImageThumbnailWidth,
|
|
22
|
+
generateHighQualityLinkPreview,
|
|
23
|
+
options: axiosOptions,
|
|
24
|
+
patchMessageBeforeSending
|
|
25
|
+
} = config;
|
|
26
|
+
const sock = (0, newsletter_1.makeNewsletterSocket)(config);
|
|
27
|
+
const {
|
|
28
|
+
ev,
|
|
29
|
+
authState,
|
|
30
|
+
processingMutex,
|
|
31
|
+
signalRepository,
|
|
32
|
+
upsertMessage,
|
|
33
|
+
query,
|
|
34
|
+
fetchPrivacySettings,
|
|
35
|
+
sendNode,
|
|
36
|
+
groupMetadata,
|
|
37
|
+
groupToggleEphemeral,
|
|
38
|
+
executeUSyncQuery
|
|
39
|
+
} = sock;
|
|
40
|
+
const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
|
|
41
|
+
stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
42
|
+
useClones: false
|
|
43
|
+
});
|
|
44
|
+
let mediaConn;
|
|
45
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
46
|
+
const media = await mediaConn;
|
|
47
|
+
if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
|
|
48
|
+
mediaConn = (async () => {
|
|
49
|
+
const result = await query({
|
|
50
|
+
tag: 'iq',
|
|
51
|
+
attrs: {
|
|
52
|
+
type: 'set',
|
|
53
|
+
xmlns: 'w:m',
|
|
54
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
55
|
+
},
|
|
56
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
57
|
+
});
|
|
58
|
+
const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
|
|
59
|
+
const node = {
|
|
60
|
+
hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
61
|
+
hostname: attrs.hostname,
|
|
62
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes,
|
|
63
|
+
})),
|
|
64
|
+
auth: mediaConnNode.attrs.auth,
|
|
65
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
66
|
+
fetchDate: new Date()
|
|
67
|
+
};
|
|
68
|
+
logger.debug('fetched media conn');
|
|
69
|
+
return node;
|
|
70
|
+
})();
|
|
71
|
+
}
|
|
72
|
+
return mediaConn;
|
|
73
|
+
};
|
|
74
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
75
|
+
const node = {
|
|
76
|
+
tag: 'receipt',
|
|
77
|
+
attrs: {
|
|
78
|
+
id: messageIds[0],
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
82
|
+
if (isReadReceipt) {
|
|
83
|
+
node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
|
|
84
|
+
}
|
|
85
|
+
if (type === 'sender' && WABinary_1.isJidUser(jid)) {
|
|
86
|
+
node.attrs.recipient = jid;
|
|
87
|
+
node.attrs.to = participant;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
node.attrs.to = jid;
|
|
91
|
+
if (participant) {
|
|
92
|
+
node.attrs.participant = participant;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (type) {
|
|
96
|
+
node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
|
|
97
|
+
}
|
|
98
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
99
|
+
if (remainingMessageIds.length) {
|
|
100
|
+
node.content = [
|
|
101
|
+
{
|
|
102
|
+
tag: 'list',
|
|
103
|
+
attrs: {},
|
|
104
|
+
content: remainingMessageIds.map(id => ({
|
|
105
|
+
tag: 'item',
|
|
106
|
+
attrs: { id }
|
|
107
|
+
}))
|
|
108
|
+
}
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
|
|
112
|
+
await sendNode(node);
|
|
113
|
+
};
|
|
114
|
+
const sendReceipts = async (keys, type) => {
|
|
115
|
+
const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
|
|
116
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
117
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const readMessages = async (keys) => {
|
|
121
|
+
const privacySettings = await fetchPrivacySettings();
|
|
122
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
123
|
+
await sendReceipts(keys, readType);
|
|
124
|
+
};
|
|
125
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
126
|
+
const deviceResults = []
|
|
127
|
+
if (!useCache) {
|
|
128
|
+
logger.debug('not using cache for devices')
|
|
129
|
+
}
|
|
130
|
+
const toFetch = []
|
|
131
|
+
jids = Array.from(new Set(jids))
|
|
132
|
+
for (let jid of jids) {
|
|
133
|
+
const user = WABinary_1.jidDecode(jid)?.user
|
|
134
|
+
jid = WABinary_1.jidNormalizedUser(jid)
|
|
135
|
+
if (useCache) {
|
|
136
|
+
const devices = userDevicesCache.get(user)
|
|
137
|
+
if (devices) {
|
|
138
|
+
deviceResults.push(...devices)
|
|
139
|
+
logger.trace({ user }, 'using cache for devices')
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
toFetch.push(jid)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
toFetch.push(jid)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!toFetch.length) {
|
|
150
|
+
return deviceResults
|
|
151
|
+
}
|
|
152
|
+
const query = new WAUSync_1.USyncQuery()
|
|
153
|
+
.withContext('message')
|
|
154
|
+
.withDeviceProtocol()
|
|
155
|
+
for (const jid of toFetch) {
|
|
156
|
+
query.withUser(new WAUSync_1.USyncUser().withId(jid))
|
|
157
|
+
}
|
|
158
|
+
const result = await executeUSyncQuery(query)
|
|
159
|
+
if (result) {
|
|
160
|
+
const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
|
|
161
|
+
const deviceMap = {}
|
|
162
|
+
for (const item of extracted) {
|
|
163
|
+
deviceMap[item.user] = deviceMap[item.user] || []
|
|
164
|
+
deviceMap[item.user].push(item)
|
|
165
|
+
deviceResults.push(item)
|
|
166
|
+
}
|
|
167
|
+
for (const key in deviceMap) {
|
|
168
|
+
userDevicesCache.set(key, deviceMap[key])
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return deviceResults
|
|
172
|
+
}
|
|
173
|
+
const assertSessions = async (jids, force) => {
|
|
174
|
+
let didFetchNewSession = false;
|
|
175
|
+
let jidsRequiringFetch = [];
|
|
176
|
+
if (force) {
|
|
177
|
+
jidsRequiringFetch = jids;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const addrs = jids.map(jid => (signalRepository
|
|
181
|
+
.jidToSignalProtocolAddress(jid)));
|
|
182
|
+
const sessions = await authState.keys.get('session', addrs);
|
|
183
|
+
for (const jid of jids) {
|
|
184
|
+
const signalId = signalRepository
|
|
185
|
+
.jidToSignalProtocolAddress(jid);
|
|
186
|
+
if (!sessions[signalId]) {
|
|
187
|
+
jidsRequiringFetch.push(jid);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (jidsRequiringFetch.length) {
|
|
192
|
+
logger.debug({ jidsRequiringFetch }, 'fetching sessions');
|
|
193
|
+
const result = await query({
|
|
194
|
+
tag: 'iq',
|
|
195
|
+
attrs: {
|
|
196
|
+
xmlns: 'encrypt',
|
|
197
|
+
type: 'get',
|
|
198
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
199
|
+
},
|
|
200
|
+
content: [
|
|
201
|
+
{
|
|
202
|
+
tag: 'key',
|
|
203
|
+
attrs: {},
|
|
204
|
+
content: jidsRequiringFetch.map(jid => ({
|
|
205
|
+
tag: 'user',
|
|
206
|
+
attrs: { jid },
|
|
207
|
+
}))
|
|
208
|
+
}
|
|
209
|
+
]
|
|
210
|
+
});
|
|
211
|
+
await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
|
|
212
|
+
didFetchNewSession = true;
|
|
213
|
+
}
|
|
214
|
+
return didFetchNewSession;
|
|
215
|
+
};
|
|
216
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
217
|
+
if (!authState.creds.me?.id) {
|
|
218
|
+
throw new boom_1.Boom('Not authenticated')
|
|
219
|
+
}
|
|
220
|
+
const protocolMessage = {
|
|
221
|
+
protocolMessage: {
|
|
222
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
223
|
+
type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
|
|
227
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
228
|
+
additionalAttributes: {
|
|
229
|
+
category: 'peer',
|
|
230
|
+
push_priority: 'high_force',
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
return msgId;
|
|
234
|
+
};
|
|
235
|
+
const createParticipantNodes = async (jids, message, extraAttrs) => {
|
|
236
|
+
const patched = await patchMessageBeforeSending(message, jids);
|
|
237
|
+
const bytes = (0, Utils_1.encodeWAMessage)(patched);
|
|
238
|
+
let shouldIncludeDeviceIdentity = false;
|
|
239
|
+
const nodes = await Promise.all(jids.map(async (jid) => {
|
|
240
|
+
const { type, ciphertext } = await signalRepository
|
|
241
|
+
.encryptMessage({ jid, data: bytes });
|
|
242
|
+
if (type === 'pkmsg') {
|
|
243
|
+
shouldIncludeDeviceIdentity = true;
|
|
244
|
+
}
|
|
245
|
+
const node = {
|
|
246
|
+
tag: 'to',
|
|
247
|
+
attrs: { jid },
|
|
248
|
+
content: [{
|
|
249
|
+
tag: 'enc',
|
|
250
|
+
attrs: {
|
|
251
|
+
v: '2',
|
|
252
|
+
type,
|
|
253
|
+
...extraAttrs || {}
|
|
254
|
+
},
|
|
255
|
+
content: ciphertext
|
|
256
|
+
}]
|
|
257
|
+
};
|
|
258
|
+
return node;
|
|
259
|
+
}));
|
|
260
|
+
return { nodes, shouldIncludeDeviceIdentity };
|
|
261
|
+
};
|
|
262
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
|
|
263
|
+
const meId = authState.creds.me.id;
|
|
264
|
+
let shouldIncludeDeviceIdentity = false;
|
|
265
|
+
let didPushAdditional = false
|
|
266
|
+
const { user, server } = WABinary_1.jidDecode(jid);
|
|
267
|
+
const statusJid = 'status@broadcast';
|
|
268
|
+
const isGroup = server === 'g.us';
|
|
269
|
+
const isStatus = jid === statusJid;
|
|
270
|
+
const isLid = server === 'lid';
|
|
271
|
+
const isPrivate = server === 's.whatsapp.net'
|
|
272
|
+
const isNewsletter = server === 'newsletter';
|
|
273
|
+
msgId = msgId || (0, Utils_1.generateMessageID)();
|
|
274
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
275
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
|
|
276
|
+
const participants = [];
|
|
277
|
+
const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
|
|
278
|
+
const binaryNodeContent = [];
|
|
279
|
+
const devices = [];
|
|
280
|
+
const meMsg = {
|
|
281
|
+
deviceSentMessage: {
|
|
282
|
+
destinationJid,
|
|
283
|
+
message
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
const extraAttrs = {}
|
|
287
|
+
const messages = Utils_1.normalizeMessageContent(message);
|
|
288
|
+
const buttonType = getButtonType(messages);
|
|
289
|
+
if (participant) {
|
|
290
|
+
if (!isGroup && !isStatus) {
|
|
291
|
+
additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
|
|
292
|
+
}
|
|
293
|
+
const { user, device } = WABinary_1.jidDecode(participant.jid);
|
|
294
|
+
devices.push({ user, device });
|
|
295
|
+
}
|
|
296
|
+
await authState.keys.transaction(async () => {
|
|
297
|
+
const mediaType = getMediaType(messages);
|
|
298
|
+
if (mediaType) {
|
|
299
|
+
extraAttrs['mediatype'] = mediaType
|
|
300
|
+
}
|
|
301
|
+
if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
|
|
302
|
+
extraAttrs['decrypt-fail'] = 'hide'
|
|
303
|
+
}
|
|
304
|
+
if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
|
|
305
|
+
extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
|
|
306
|
+
}
|
|
307
|
+
if (isGroup || isStatus) {
|
|
308
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
309
|
+
(async () => {
|
|
310
|
+
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
|
|
311
|
+
if (groupData) {
|
|
312
|
+
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
|
|
313
|
+
}
|
|
314
|
+
else if (!isStatus) {
|
|
315
|
+
groupData = await groupMetadata(jid)
|
|
316
|
+
}
|
|
317
|
+
return groupData;
|
|
318
|
+
})(),
|
|
319
|
+
(async () => {
|
|
320
|
+
if (!participant && !isStatus) {
|
|
321
|
+
const result = await authState.keys.get('sender-key-memory', [jid])
|
|
322
|
+
return result[jid] || {}
|
|
323
|
+
}
|
|
324
|
+
return {}
|
|
325
|
+
})()
|
|
326
|
+
]);
|
|
327
|
+
if (!participant) {
|
|
328
|
+
const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
|
|
329
|
+
if (isStatus && statusJidList) {
|
|
330
|
+
participantsList.push(...statusJidList)
|
|
331
|
+
}
|
|
332
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
|
|
333
|
+
devices.push(...additionalDevices)
|
|
334
|
+
}
|
|
335
|
+
const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
|
|
336
|
+
const bytes = Utils_1.encodeWAMessage(patched);
|
|
337
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
338
|
+
group: destinationJid,
|
|
339
|
+
data: bytes,
|
|
340
|
+
meId,
|
|
341
|
+
});
|
|
342
|
+
const senderKeyJids = [];
|
|
343
|
+
for (const { user, device } of devices) {
|
|
344
|
+
const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
|
|
345
|
+
if (!senderKeyMap[jid] || !!participant) {
|
|
346
|
+
senderKeyJids.push(jid);
|
|
347
|
+
senderKeyMap[jid] = true;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (senderKeyJids.length) {
|
|
351
|
+
logger.debug({ senderKeyJids }, 'sending new sender key');
|
|
352
|
+
const senderKeyMsg = {
|
|
353
|
+
senderKeyDistributionMessage: {
|
|
354
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
355
|
+
groupId: destinationJid
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
await assertSessions(senderKeyJids, false);
|
|
359
|
+
const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
|
|
360
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
361
|
+
participants.push(...result.nodes);
|
|
362
|
+
}
|
|
363
|
+
binaryNodeContent.push({
|
|
364
|
+
tag: 'enc',
|
|
365
|
+
attrs: { v: '2', type: 'skmsg', ...extraAttrs },
|
|
366
|
+
content: ciphertext
|
|
367
|
+
});
|
|
368
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
|
|
369
|
+
}
|
|
370
|
+
else if (isNewsletter) {
|
|
371
|
+
if (message.protocolMessage?.editedMessage) {
|
|
372
|
+
msgId = message.protocolMessage.key?.id
|
|
373
|
+
message = message.protocolMessage.editedMessage
|
|
374
|
+
}
|
|
375
|
+
if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
|
|
376
|
+
msgId = message.protocolMessage.key?.id
|
|
377
|
+
message = {}
|
|
378
|
+
}
|
|
379
|
+
const patched = await patchMessageBeforeSending(message, [])
|
|
380
|
+
const bytes = Utils_1.encodeNewsletterMessage(patched)
|
|
381
|
+
binaryNodeContent.push({
|
|
382
|
+
tag: 'plaintext',
|
|
383
|
+
attrs: extraAttrs ? extraAttrs : {},
|
|
384
|
+
content: bytes
|
|
385
|
+
})
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
const { user: meUser } = WABinary_1.jidDecode(meId);
|
|
389
|
+
if (!participant) {
|
|
390
|
+
devices.push({ user })
|
|
391
|
+
if (user !== meUser) {
|
|
392
|
+
devices.push({ user: meUser })
|
|
393
|
+
}
|
|
394
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
395
|
+
const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
|
|
396
|
+
devices.push(...additionalDevices)
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const allJids = [];
|
|
400
|
+
const meJids = [];
|
|
401
|
+
const otherJids = [];
|
|
402
|
+
for (const { user, device } of devices) {
|
|
403
|
+
const isMe = user === meUser
|
|
404
|
+
const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
|
|
405
|
+
if (isMe) {
|
|
406
|
+
meJids.push(jid)
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
otherJids.push(jid)
|
|
410
|
+
}
|
|
411
|
+
allJids.push(jid)
|
|
412
|
+
}
|
|
413
|
+
await assertSessions(allJids, false);
|
|
414
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
415
|
+
createParticipantNodes(meJids, meMsg, extraAttrs),
|
|
416
|
+
createParticipantNodes(otherJids, message, extraAttrs)
|
|
417
|
+
])
|
|
418
|
+
participants.push(...meNodes);
|
|
419
|
+
participants.push(...otherNodes);
|
|
420
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
421
|
+
}
|
|
422
|
+
if (participants.length) {
|
|
423
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
424
|
+
const peerNode = participants[0]?.content?.[0]
|
|
425
|
+
if (peerNode) {
|
|
426
|
+
binaryNodeContent.push(peerNode)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
binaryNodeContent.push({
|
|
431
|
+
tag: 'participants',
|
|
432
|
+
attrs: {},
|
|
433
|
+
content: participants
|
|
434
|
+
})
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const stanza = {
|
|
438
|
+
tag: 'message',
|
|
439
|
+
attrs: {
|
|
440
|
+
id: msgId,
|
|
441
|
+
type: getTypeMessage(messages),
|
|
442
|
+
...(additionalAttributes || {})
|
|
443
|
+
},
|
|
444
|
+
content: binaryNodeContent
|
|
445
|
+
}
|
|
446
|
+
if (participant) {
|
|
447
|
+
if (WABinary_1.isJidGroup(destinationJid)) {
|
|
448
|
+
stanza.attrs.to = destinationJid;
|
|
449
|
+
stanza.attrs.participant = participant.jid;
|
|
450
|
+
}
|
|
451
|
+
else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
|
|
452
|
+
stanza.attrs.to = participant.jid;
|
|
453
|
+
stanza.attrs.recipient = destinationJid;
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
stanza.attrs.to = participant.jid;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
stanza.attrs.to = destinationJid;
|
|
461
|
+
}
|
|
462
|
+
if (shouldIncludeDeviceIdentity) {
|
|
463
|
+
stanza.content.push({
|
|
464
|
+
tag: 'device-identity',
|
|
465
|
+
attrs: {},
|
|
466
|
+
content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
|
|
467
|
+
});
|
|
468
|
+
logger.debug({ jid }, 'adding device identity');
|
|
469
|
+
}
|
|
470
|
+
if (AI && isPrivate) {
|
|
471
|
+
const botNode = {
|
|
472
|
+
tag: 'bot',
|
|
473
|
+
attrs: {
|
|
474
|
+
biz_bot: '1'
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
|
|
478
|
+
if (filteredBizBot) {
|
|
479
|
+
stanza.content.push(...additionalNodes)
|
|
480
|
+
didPushAdditional = true
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
stanza.content.push(botNode)
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (!isNewsletter && buttonType && !isStatus) {
|
|
487
|
+
const content = WABinary_1.getAdditionalNode(buttonType)
|
|
488
|
+
const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
|
|
489
|
+
if (filteredNode) {
|
|
490
|
+
didPushAdditional = true
|
|
491
|
+
stanza.content.push(...additionalNodes)
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
stanza.content.push(...content)
|
|
495
|
+
}
|
|
496
|
+
logger.debug({ jid }, 'adding business node')
|
|
497
|
+
}
|
|
498
|
+
if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
|
|
499
|
+
stanza.content.push(...additionalNodes);
|
|
500
|
+
}
|
|
501
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`);
|
|
502
|
+
await sendNode(stanza);
|
|
503
|
+
});
|
|
504
|
+
message = Types_1.WAProto.Message.fromObject(message)
|
|
505
|
+
const messageJSON = {
|
|
506
|
+
key: {
|
|
507
|
+
remoteJid: jid,
|
|
508
|
+
fromMe: true,
|
|
509
|
+
id: msgId
|
|
510
|
+
},
|
|
511
|
+
message: message,
|
|
512
|
+
messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
|
|
513
|
+
messageStubParameters: [],
|
|
514
|
+
participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
|
|
515
|
+
status: Types_1.WAMessageStatus.PENDING
|
|
516
|
+
}
|
|
517
|
+
return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
|
|
518
|
+
};
|
|
519
|
+
const getTypeMessage = (msg) => {
|
|
520
|
+
const message = Utils_1.normalizeMessageContent(msg);
|
|
521
|
+
if (message.reactionMessage) {
|
|
522
|
+
return 'reaction'
|
|
523
|
+
}
|
|
524
|
+
else if (getMediaType(message)) {
|
|
525
|
+
return 'media'
|
|
526
|
+
}
|
|
527
|
+
else {
|
|
528
|
+
return 'text'
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const MEDIA_TYPE_MAP = {
|
|
532
|
+
imageMessage: 'image',
|
|
533
|
+
contactMessage: 'vcard',
|
|
534
|
+
documentMessage: 'document',
|
|
535
|
+
contactsArrayMessage: 'contact_array',
|
|
536
|
+
liveLocationMessage: 'livelocation',
|
|
537
|
+
stickerMessage: 'sticker',
|
|
538
|
+
listMessage: 'list',
|
|
539
|
+
listResponseMessage: 'list_response',
|
|
540
|
+
buttonsResponseMessage: 'buttons_response',
|
|
541
|
+
orderMessage: 'order',
|
|
542
|
+
productMessage: 'product',
|
|
543
|
+
interactiveResponseMessage: 'native_flow_response',
|
|
544
|
+
groupInviteMessage: 'url',
|
|
545
|
+
stickerPackMessage: 'sticker_pack',
|
|
546
|
+
}
|
|
547
|
+
const getMediaType = (message) => {
|
|
548
|
+
if (message.videoMessage) {
|
|
549
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
|
550
|
+
}
|
|
551
|
+
if (message.audioMessage) {
|
|
552
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
|
553
|
+
}
|
|
554
|
+
for (const key in MEDIA_TYPE_MAP) {
|
|
555
|
+
if (message[key]) return MEDIA_TYPE_MAP[key]
|
|
556
|
+
}
|
|
557
|
+
if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
558
|
+
return 'productlink'
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const NATIVE_FLOW_BUTTON_MAP = {
|
|
562
|
+
review_and_pay: 'review_and_pay',
|
|
563
|
+
review_order: 'review_order',
|
|
564
|
+
payment_info: 'payment_info',
|
|
565
|
+
payment_status: 'payment_status',
|
|
566
|
+
payment_method: 'payment_method',
|
|
567
|
+
}
|
|
568
|
+
const getButtonType = (message) => {
|
|
569
|
+
if (message.listMessage) return 'list'
|
|
570
|
+
if (message.buttonsMessage) return 'buttons'
|
|
571
|
+
const btnName = message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name;
|
|
572
|
+
if (btnName && NATIVE_FLOW_BUTTON_MAP[btnName]) return NATIVE_FLOW_BUTTON_MAP[btnName]
|
|
573
|
+
if (message.interactiveMessage?.nativeFlowMessage) return 'interactive'
|
|
574
|
+
}
|
|
575
|
+
const getPrivacyTokens = async (jids) => {
|
|
576
|
+
const t = Utils_1.unixTimestampSeconds().toString();
|
|
577
|
+
const result = await query({
|
|
578
|
+
tag: 'iq',
|
|
579
|
+
attrs: {
|
|
580
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
581
|
+
type: 'set',
|
|
582
|
+
xmlns: 'privacy'
|
|
583
|
+
},
|
|
584
|
+
content: [
|
|
585
|
+
{
|
|
586
|
+
tag: 'tokens',
|
|
587
|
+
attrs: {},
|
|
588
|
+
content: jids.map(jid => ({
|
|
589
|
+
tag: 'token',
|
|
590
|
+
attrs: {
|
|
591
|
+
jid: WABinary_1.jidNormalizedUser(jid),
|
|
592
|
+
t,
|
|
593
|
+
type: 'trusted_contact'
|
|
594
|
+
}
|
|
595
|
+
}))
|
|
596
|
+
}
|
|
597
|
+
]
|
|
598
|
+
});
|
|
599
|
+
return result;
|
|
600
|
+
}
|
|
601
|
+
const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
|
|
602
|
+
const ourin = new Z(Utils_1, waUploadToServer, relayMessage, config, sock);
|
|
603
|
+
const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
|
|
604
|
+
return {
|
|
605
|
+
...sock,
|
|
606
|
+
getPrivacyTokens,
|
|
607
|
+
assertSessions,
|
|
608
|
+
relayMessage,
|
|
609
|
+
sendReceipt,
|
|
610
|
+
sendReceipts,
|
|
611
|
+
ourin,
|
|
612
|
+
readMessages,
|
|
613
|
+
refreshMediaConn,
|
|
614
|
+
getUSyncDevices,
|
|
615
|
+
createParticipantNodes,
|
|
616
|
+
waUploadToServer,
|
|
617
|
+
sendPeerDataOperationMessage,
|
|
618
|
+
fetchPrivacySettings,
|
|
619
|
+
updateMediaMessage: async (message) => {
|
|
620
|
+
const content = (0, Utils_1.assertMediaContent)(message.message);
|
|
621
|
+
const mediaKey = content.mediaKey;
|
|
622
|
+
const meId = authState.creds.me.id;
|
|
623
|
+
const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
|
|
624
|
+
let error = undefined;
|
|
625
|
+
await Promise.all([
|
|
626
|
+
sendNode(node),
|
|
627
|
+
waitForMsgMediaUpdate(update => {
|
|
628
|
+
const result = update.find(c => c.key.id === message.key.id);
|
|
629
|
+
if (result) {
|
|
630
|
+
if (result.error) {
|
|
631
|
+
error = result.error;
|
|
632
|
+
}
|
|
633
|
+
else {
|
|
634
|
+
try {
|
|
635
|
+
const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
|
|
636
|
+
if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
637
|
+
const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
|
|
638
|
+
throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
|
|
639
|
+
}
|
|
640
|
+
content.directPath = media.directPath;
|
|
641
|
+
content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
|
|
642
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
|
|
643
|
+
}
|
|
644
|
+
catch (err) {
|
|
645
|
+
error = err;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return true;
|
|
649
|
+
}
|
|
650
|
+
})
|
|
651
|
+
]);
|
|
652
|
+
if (error) {
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
655
|
+
ev.emit('messages.update', [
|
|
656
|
+
{
|
|
657
|
+
key: message.key,
|
|
658
|
+
update: {
|
|
659
|
+
message: message.message
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
]);
|
|
663
|
+
return message;
|
|
664
|
+
},
|
|
665
|
+
setLabelGroup: async (id, text) => {
|
|
666
|
+
await relayMessage(id, {
|
|
667
|
+
protocolMessage: {
|
|
668
|
+
type: 30,
|
|
669
|
+
memberLabel: {
|
|
670
|
+
label: text.slice(0, 30)
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}, {
|
|
674
|
+
additionalNodes: [
|
|
675
|
+
{
|
|
676
|
+
tag: "meta",
|
|
677
|
+
attrs: {
|
|
678
|
+
tag_reason: "user_update",
|
|
679
|
+
appdata: "member_tag"
|
|
680
|
+
},
|
|
681
|
+
content: undefined
|
|
682
|
+
}
|
|
683
|
+
]
|
|
684
|
+
})
|
|
685
|
+
},
|
|
686
|
+
sendStatusMention: async (content, jids = []) => {
|
|
687
|
+
return await ourin.sendStatusWhatsApp(content, jids);
|
|
688
|
+
},
|
|
689
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
690
|
+
const userJid = authState.creds.me.id;
|
|
691
|
+
delete options.ephemeralExpiration
|
|
692
|
+
const { filter = false, quoted } = options;
|
|
693
|
+
const getParticipantAttr = () => filter ? { participant: { jid } } : {};
|
|
694
|
+
const messageType = ourin.detectType(content);
|
|
695
|
+
if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
|
|
696
|
+
typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
|
|
697
|
+
const { disappearingMessagesInChat } = content
|
|
698
|
+
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
|
699
|
+
(disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
|
|
700
|
+
disappearingMessagesInChat
|
|
701
|
+
await groupToggleEphemeral(jid, value)
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
let mediaHandle
|
|
705
|
+
if (messageType) {
|
|
706
|
+
switch (messageType) {
|
|
707
|
+
case 'PAYMENT':
|
|
708
|
+
const paymentContent = await ourin.handlePayment(content, quoted);
|
|
709
|
+
return await relayMessage(jid, paymentContent, {
|
|
710
|
+
messageId: Utils_1.generateMessageID(),
|
|
711
|
+
...getParticipantAttr()
|
|
712
|
+
});
|
|
713
|
+
case 'PRODUCT':
|
|
714
|
+
const productContent = await ourin.handleProduct(content, jid, quoted);
|
|
715
|
+
const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
|
|
716
|
+
return await relayMessage(jid, productMsg.message, {
|
|
717
|
+
messageId: productMsg.key.id,
|
|
718
|
+
...getParticipantAttr()
|
|
719
|
+
});
|
|
720
|
+
case 'INTERACTIVE':
|
|
721
|
+
const interactiveContent = await ourin.handleInteractive(content, jid, quoted);
|
|
722
|
+
const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
|
|
723
|
+
return await relayMessage(jid, interactiveMsg.message, {
|
|
724
|
+
messageId: interactiveMsg.key.id,
|
|
725
|
+
...getParticipantAttr()
|
|
726
|
+
});
|
|
727
|
+
case 'INTERACTIVE_BUTTONS':
|
|
728
|
+
const ibContent = await ourin.handleInteractiveButtons(content, jid, quoted);
|
|
729
|
+
const ibMsg = await Utils_1.generateWAMessageFromContent(jid, ibContent, { quoted });
|
|
730
|
+
return await relayMessage(jid, ibMsg.message, {
|
|
731
|
+
messageId: ibMsg.key.id,
|
|
732
|
+
...getParticipantAttr()
|
|
733
|
+
});
|
|
734
|
+
case 'ALBUM':
|
|
735
|
+
return await ourin.handleAlbum(content, jid, quoted)
|
|
736
|
+
case 'EVENT':
|
|
737
|
+
return await ourin.handleEvent(content, jid, quoted)
|
|
738
|
+
case 'POLL_RESULT':
|
|
739
|
+
return await ourin.handlePollResult(content, jid, quoted)
|
|
740
|
+
case 'GROUP_STORY':
|
|
741
|
+
return await ourin.handleGroupStory(content, jid, quoted)
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
const fullMsg = await Utils_1.generateWAMessage(jid, content, {
|
|
745
|
+
logger,
|
|
746
|
+
userJid,
|
|
747
|
+
quoted,
|
|
748
|
+
getUrlInfo: text => link_preview_1.getUrlInfo(text, {
|
|
749
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
750
|
+
fetchOpts: {
|
|
751
|
+
timeout: 3000,
|
|
752
|
+
...axiosOptions || {}
|
|
753
|
+
},
|
|
754
|
+
logger,
|
|
755
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
756
|
+
}),
|
|
757
|
+
upload: async (readStream, opts) => {
|
|
758
|
+
const up = await waUploadToServer(readStream, {
|
|
759
|
+
...opts,
|
|
760
|
+
newsletter: WABinary_1.isJidNewsLetter(jid)
|
|
761
|
+
});
|
|
762
|
+
return up;
|
|
763
|
+
},
|
|
764
|
+
mediaCache: config.mediaCache,
|
|
765
|
+
options: config.options,
|
|
766
|
+
...options
|
|
767
|
+
});
|
|
768
|
+
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
769
|
+
const isEditMsg = 'edit' in content && !!content.edit;
|
|
770
|
+
const isAiMsg = 'ai' in content && !!content.ai;
|
|
771
|
+
const additionalAttributes = {};
|
|
772
|
+
const additionalNodes = [];
|
|
773
|
+
if (isDeleteMsg) {
|
|
774
|
+
const fromMe = content.delete?.fromMe;
|
|
775
|
+
const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
|
|
776
|
+
additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
|
|
777
|
+
} else if (isEditMsg) {
|
|
778
|
+
additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
|
|
779
|
+
} else if (isAiMsg) {
|
|
780
|
+
additionalNodes.push({
|
|
781
|
+
attrs: {
|
|
782
|
+
biz_bot: '1'
|
|
783
|
+
}, tag: "bot"
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
await relayMessage(jid, fullMsg.message, {
|
|
787
|
+
messageId: fullMsg.key.id,
|
|
788
|
+
cachedGroupMetadata: options.cachedGroupMetadata,
|
|
789
|
+
additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
|
|
790
|
+
additionalAttributes,
|
|
791
|
+
statusJidList: options.statusJidList
|
|
792
|
+
});
|
|
793
|
+
if (config.emitOwnEvents) {
|
|
794
|
+
process.nextTick(() => {
|
|
795
|
+
processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
return fullMsg;
|
|
799
|
+
}
|
|
800
|
+
},
|
|
801
|
+
react(m, emoji = '') {
|
|
802
|
+
const key = m?.quoted?.key || m?.key
|
|
803
|
+
if (!key) throw new Error('No message key to react')
|
|
804
|
+
|
|
805
|
+
return this.sendMessage(key.remoteJid, {
|
|
806
|
+
react: {
|
|
807
|
+
text: emoji,
|
|
808
|
+
key
|
|
809
|
+
}
|
|
810
|
+
})
|
|
811
|
+
},
|
|
812
|
+
unreact(m) {
|
|
813
|
+
const key = m?.quoted?.key || m?.key
|
|
814
|
+
if (!key) throw new Error('No message key to react')
|
|
815
|
+
|
|
816
|
+
return this.sendMessage(key.remoteJid, {
|
|
817
|
+
react: {
|
|
818
|
+
text: '',
|
|
819
|
+
key
|
|
820
|
+
}
|
|
821
|
+
})
|
|
822
|
+
},
|
|
823
|
+
async delay(s) {
|
|
824
|
+
if( s < 0 ) s = 0;
|
|
825
|
+
const ms = s * 1000;
|
|
826
|
+
return await new Promise(resolve => setTimeout(resolve, ms));
|
|
827
|
+
},
|
|
828
|
+
edit(m, newText) {
|
|
829
|
+
if (!m?.key) throw new Error('Invalid message')
|
|
830
|
+
return this.sendMessage(m.key.remoteJid, {
|
|
831
|
+
edit: m.key,
|
|
832
|
+
text: newText
|
|
833
|
+
})
|
|
834
|
+
},
|
|
835
|
+
del(m) {
|
|
836
|
+
if (!m?.key) throw new Error('Invalid message')
|
|
837
|
+
return this.sendMessage(m.key.remoteJid, {
|
|
838
|
+
delete: m.key
|
|
839
|
+
})
|
|
840
|
+
},
|
|
841
|
+
detect(m) {
|
|
842
|
+
if (!m?.message) return 'unknown'
|
|
843
|
+
|
|
844
|
+
const msg = Utils_1.normalizeMessageContent(m.message)
|
|
845
|
+
|
|
846
|
+
if (msg.reactionMessage) return 'reaction'
|
|
847
|
+
if (msg.protocolMessage?.type === 0) return 'revoke'
|
|
848
|
+
if (msg.protocolMessage?.editedMessage) return 'edited'
|
|
849
|
+
|
|
850
|
+
if (msg.viewOnceMessageV2 || msg.viewOnceMessage) return 'viewonce'
|
|
851
|
+
|
|
852
|
+
if (msg.imageMessage) return 'image'
|
|
853
|
+
if (msg.videoMessage) return msg.videoMessage.gifPlayback ? 'gif' : 'video'
|
|
854
|
+
if (msg.audioMessage) return msg.audioMessage.ptt ? 'ptt' : 'audio'
|
|
855
|
+
if (msg.stickerMessage) return 'sticker'
|
|
856
|
+
if (msg.documentMessage) return 'document'
|
|
857
|
+
if (msg.contactMessage) return 'contact'
|
|
858
|
+
if (msg.locationMessage || msg.liveLocationMessage) return 'location'
|
|
859
|
+
if (msg.pollCreationMessage) return 'poll'
|
|
860
|
+
if (msg.interactiveMessage) return 'interactive'
|
|
861
|
+
if (msg.buttonsResponseMessage) return 'button_response'
|
|
862
|
+
if (msg.listResponseMessage) return 'list_response'
|
|
863
|
+
if (msg.extendedTextMessage || msg.conversation) return 'text'
|
|
864
|
+
|
|
865
|
+
return 'unknown'
|
|
866
|
+
},
|
|
867
|
+
async forward(jid, m, options = {}) {
|
|
868
|
+
if (!m?.message) throw new Error('Invalid message')
|
|
869
|
+
const {
|
|
870
|
+
force = false,
|
|
871
|
+
removeContext = false
|
|
872
|
+
} = options
|
|
873
|
+
const msg = Utils_1.normalizeMessageContent(m.message)
|
|
874
|
+
let content = JSON.parse(JSON.stringify(msg))
|
|
875
|
+
if (removeContext) {
|
|
876
|
+
const ctx =
|
|
877
|
+
content?.extendedTextMessage?.contextInfo ||
|
|
878
|
+
content?.imageMessage?.contextInfo ||
|
|
879
|
+
content?.videoMessage?.contextInfo ||
|
|
880
|
+
content?.documentMessage?.contextInfo
|
|
881
|
+
|
|
882
|
+
if (ctx) delete ctx.quotedMessage
|
|
883
|
+
if (ctx) delete ctx.participant
|
|
884
|
+
if (ctx) delete ctx.stanzaId
|
|
885
|
+
if (ctx) delete ctx.mentionedJid
|
|
886
|
+
}
|
|
887
|
+
const target =
|
|
888
|
+
content.extendedTextMessage ||
|
|
889
|
+
content.imageMessage ||
|
|
890
|
+
content.videoMessage ||
|
|
891
|
+
content.documentMessage
|
|
892
|
+
if (target) {
|
|
893
|
+
target.contextInfo = target.contextInfo || {}
|
|
894
|
+
target.contextInfo.forwardingScore = force ? 999 : 1
|
|
895
|
+
target.contextInfo.isForwarded = true
|
|
896
|
+
}
|
|
897
|
+
const fullMsg = await Utils_1.generateWAMessage(
|
|
898
|
+
jid,
|
|
899
|
+
content,
|
|
900
|
+
{
|
|
901
|
+
logger,
|
|
902
|
+
userJid: authState.creds.me.id,
|
|
903
|
+
upload: waUploadToServer
|
|
904
|
+
}
|
|
905
|
+
)
|
|
906
|
+
await relayMessage(jid, fullMsg.message, {
|
|
907
|
+
messageId: fullMsg.key.id
|
|
908
|
+
})
|
|
909
|
+
return fullMsg
|
|
910
|
+
},
|
|
911
|
+
|
|
912
|
+
async resize(buf, width, height, {
|
|
913
|
+
quality = 80,
|
|
914
|
+
}) {
|
|
915
|
+
const sharp = (await import('sharp')).default;
|
|
916
|
+
return sharp(buf)
|
|
917
|
+
.resize(width, height, { fit: 'inside' })
|
|
918
|
+
.jpeg({ quality })
|
|
919
|
+
.toBuffer();
|
|
920
|
+
},
|
|
921
|
+
|
|
922
|
+
async convert(buf, { to }) {
|
|
923
|
+
const fmt = to.toLowerCase().replace('.', '');
|
|
924
|
+
const IMG = { jpeg: 'jpeg', jpg: 'jpeg', png: 'png', webp: 'webp' };
|
|
925
|
+
if (IMG[fmt]) {
|
|
926
|
+
const sharp = (await import('sharp')).default;
|
|
927
|
+
return sharp(buf).toFormat(IMG[fmt]).toBuffer();
|
|
928
|
+
}
|
|
929
|
+
const { spawn } = require('child_process');
|
|
930
|
+
const args = ['-i', 'pipe:0', '-y'];
|
|
931
|
+
if (fmt === 'mp4') args.push('-movflags', 'frag_keyframe+empty_moov', '-f', 'mp4');
|
|
932
|
+
else args.push('-f', fmt);
|
|
933
|
+
args.push('pipe:1');
|
|
934
|
+
return new Promise((resolve, reject) => {
|
|
935
|
+
const ff = spawn('ffmpeg', args, { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
936
|
+
const chunks = [];
|
|
937
|
+
let len = 0;
|
|
938
|
+
ff.stdout.on('data', c => { chunks.push(c); len += c.length; });
|
|
939
|
+
ff.on('close', code => code === 0
|
|
940
|
+
? resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, len))
|
|
941
|
+
: reject(new Error(`Convert failed (${code})`))
|
|
942
|
+
);
|
|
943
|
+
ff.on('error', reject);
|
|
944
|
+
ff.stdin.end(buf);
|
|
945
|
+
});
|
|
946
|
+
},
|
|
947
|
+
|
|
948
|
+
async toSticker(buf, { quality = 80 } = {}) {
|
|
949
|
+
const sharp = (await import('sharp')).default;
|
|
950
|
+
return sharp(buf)
|
|
951
|
+
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
|
952
|
+
.webp({ quality })
|
|
953
|
+
.toBuffer();
|
|
954
|
+
},
|
|
955
|
+
|
|
956
|
+
async compress(buf, { quality = 50 } = {}) {
|
|
957
|
+
try {
|
|
958
|
+
const sharp = (await import('sharp')).default;
|
|
959
|
+
const { format } = await sharp(buf).metadata();
|
|
960
|
+
if (format) return sharp(buf).toFormat(format, { quality }).toBuffer();
|
|
961
|
+
} catch {}
|
|
962
|
+
const { spawn } = require('child_process');
|
|
963
|
+
const crf = String(Math.round(51 - (quality / 100 * 51)));
|
|
964
|
+
return new Promise((resolve, reject) => {
|
|
965
|
+
const ff = spawn('ffmpeg', [
|
|
966
|
+
'-i', 'pipe:0', '-y',
|
|
967
|
+
'-crf', crf, '-preset', 'ultrafast',
|
|
968
|
+
'-movflags', 'frag_keyframe+empty_moov', '-f', 'mp4', 'pipe:1'
|
|
969
|
+
], { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
970
|
+
const chunks = [];
|
|
971
|
+
let len = 0;
|
|
972
|
+
ff.stdout.on('data', c => { chunks.push(c); len += c.length; });
|
|
973
|
+
ff.on('close', code => code === 0
|
|
974
|
+
? resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, len))
|
|
975
|
+
: reject(new Error('Compress failed'))
|
|
976
|
+
);
|
|
977
|
+
ff.on('error', reject);
|
|
978
|
+
ff.stdin.end(buf);
|
|
979
|
+
});
|
|
980
|
+
},
|
|
981
|
+
|
|
982
|
+
async metadata(buf) {
|
|
983
|
+
const result = { size: buf.length };
|
|
984
|
+
try {
|
|
985
|
+
const sharp = (await import('sharp')).default;
|
|
986
|
+
const meta = await sharp(buf).metadata();
|
|
987
|
+
if (meta.format) {
|
|
988
|
+
result.mimetype = `image/${meta.format}`;
|
|
989
|
+
result.width = meta.width;
|
|
990
|
+
result.height = meta.height;
|
|
991
|
+
result.channels = meta.channels;
|
|
992
|
+
result.hasAlpha = meta.hasAlpha;
|
|
993
|
+
return result;
|
|
994
|
+
}
|
|
995
|
+
} catch {}
|
|
996
|
+
const { spawn } = require('child_process');
|
|
997
|
+
return new Promise(resolve => {
|
|
998
|
+
const ff = spawn('ffprobe', [
|
|
999
|
+
'-v', 'quiet', '-print_format', 'json',
|
|
1000
|
+
'-show_format', '-show_streams', 'pipe:0'
|
|
1001
|
+
], { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
1002
|
+
const chunks = [];
|
|
1003
|
+
ff.stdout.on('data', c => chunks.push(c));
|
|
1004
|
+
ff.on('close', () => {
|
|
1005
|
+
try {
|
|
1006
|
+
const d = JSON.parse(Buffer.concat(chunks).toString());
|
|
1007
|
+
const vid = d.streams?.find(s => s.codec_type === 'video');
|
|
1008
|
+
const aud = d.streams?.find(s => s.codec_type === 'audio');
|
|
1009
|
+
if (vid) { result.width = vid.width; result.height = vid.height; }
|
|
1010
|
+
result.duration = parseFloat(d.format?.duration) || undefined;
|
|
1011
|
+
result.mimetype = vid ? 'video/mp4' : aud ? 'audio/mpeg' : undefined;
|
|
1012
|
+
} catch {}
|
|
1013
|
+
resolve(result);
|
|
1014
|
+
});
|
|
1015
|
+
ff.on('error', () => resolve(result));
|
|
1016
|
+
ff.stdin.end(buf);
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
exports.makeMessagesSocket = makeMessagesSocket;
|