@aseppxyzz12/baileys 1.1.8
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 +25 -0
- package/README.md +2579 -0
- package/WAProto/AICommon/AICommon.js +19396 -0
- package/WAProto/AICommon/AICommon.proto +820 -0
- package/WAProto/Adv/Adv.js +1137 -0
- package/WAProto/Adv/Adv.proto +42 -0
- package/WAProto/BotMetadata/BotMetadata.js +8975 -0
- package/WAProto/BotMetadata/BotMetadata.proto +484 -0
- package/WAProto/Cert/Cert.js +893 -0
- package/WAProto/Cert/Cert.proto +30 -0
- package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
- package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
- package/WAProto/CompanionReg/CompanionReg.js +2457 -0
- package/WAProto/CompanionReg/CompanionReg.proto +103 -0
- package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
- package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
- package/WAProto/E2E/E2E.js +78728 -0
- package/WAProto/E2E/E2E.proto +1970 -0
- package/WAProto/Ephemeral/Ephemeral.js +143 -0
- package/WAProto/Ephemeral/Ephemeral.proto +7 -0
- package/WAProto/HistorySync/HistorySync.js +95931 -0
- package/WAProto/HistorySync/HistorySync.proto +229 -0
- package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
- package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
- package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
- package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
- package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
- package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
- package/WAProto/MmsRetry/MmsRetry.js +310 -0
- package/WAProto/MmsRetry/MmsRetry.proto +19 -0
- package/WAProto/Protocol/Protocol.js +399 -0
- package/WAProto/Protocol/Protocol.proto +22 -0
- package/WAProto/Reporting/Reporting.js +535 -0
- package/WAProto/Reporting/Reporting.proto +22 -0
- package/WAProto/ServerSync/ServerSync.js +1830 -0
- package/WAProto/ServerSync/ServerSync.proto +70 -0
- package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
- package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
- package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
- package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
- package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
- package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
- package/WAProto/SyncAction/SyncAction.js +17424 -0
- package/WAProto/SyncAction/SyncAction.proto +663 -0
- package/WAProto/UserPassword/UserPassword.js +544 -0
- package/WAProto/UserPassword/UserPassword.proto +28 -0
- package/WAProto/VnameCert/VnameCert.js +1466 -0
- package/WAProto/VnameCert/VnameCert.proto +65 -0
- package/WAProto/Wa6/Wa6.js +4601 -0
- package/WAProto/Wa6/Wa6.proto +241 -0
- package/WAProto/Web/Web.js +90819 -0
- package/WAProto/Web/Web.proto +605 -0
- package/WAProto/index.js +30 -0
- package/engine-requirements.js +9 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/connection.js +39 -0
- package/lib/Defaults/constants.js +50 -0
- package/lib/Defaults/history.js +13 -0
- package/lib/Defaults/index.js +36 -0
- package/lib/Defaults/media.js +43 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Defaults/prefix.js +12 -0
- package/lib/Function/Download/tiktok.js +19 -0
- package/lib/Function/Tools/bypass.js +19 -0
- package/lib/Function/index.js +13 -0
- package/lib/Signal/Group/ciphertext-message.js +14 -0
- package/lib/Signal/Group/group-session-builder.js +46 -0
- package/lib/Signal/Group/group_cipher.js +104 -0
- package/lib/Signal/Group/index.js +42 -0
- package/lib/Signal/Group/keyhelper.js +21 -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 +78 -0
- package/lib/Signal/Group/sender-key-name.js +49 -0
- package/lib/Signal/Group/sender-key-record.js +45 -0
- package/lib/Signal/Group/sender-key-state.js +100 -0
- package/lib/Signal/Group/sender-message-key.js +28 -0
- package/lib/Signal/libsignal.js +364 -0
- package/lib/Signal/lid-mapping.js +164 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.js +31 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/types.js +12 -0
- package/lib/Socket/Client/web-socket-client.js +62 -0
- package/lib/Socket/Client/websocket.js +67 -0
- package/lib/Socket/business.js +291 -0
- package/lib/Socket/chats.js +874 -0
- package/lib/Socket/community.js +454 -0
- package/lib/Socket/dugong.js +658 -0
- package/lib/Socket/groups.js +357 -0
- package/lib/Socket/index.js +13 -0
- package/lib/Socket/messages-recv.js +1509 -0
- package/lib/Socket/messages-send.js +1505 -0
- package/lib/Socket/mex.js +54 -0
- package/lib/Socket/newsletter.js +171 -0
- package/lib/Socket/registration.js +167 -0
- package/lib/Socket/rich-content.js +279 -0
- package/lib/Socket/socket.js +905 -0
- package/lib/Socket/username.js +157 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.js +37 -0
- package/lib/Store/keyed-db.js +114 -0
- package/lib/Store/make-cache-manager-store.js +77 -0
- package/lib/Store/make-in-memory-store.js +423 -0
- package/lib/Store/make-ordered-dictionary.js +78 -0
- package/lib/Store/object-repository.js +26 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +10 -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 +25 -0
- package/lib/Types/LabelAssociation.js +4 -0
- package/lib/Types/Message.js +11 -0
- package/lib/Types/Mex.js +40 -0
- package/lib/Types/MexUpdates.js +15 -0
- package/lib/Types/Newsletter.js +32 -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 +9 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +60 -0
- package/lib/Utils/auth-utils.js +256 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/bot-toolkit.js +455 -0
- package/lib/Utils/browser-utils.js +29 -0
- package/lib/Utils/business.js +233 -0
- package/lib/Utils/chat-utils.js +904 -0
- package/lib/Utils/companion-reg-client-utils.js +41 -0
- package/lib/Utils/crypto.js +144 -0
- package/lib/Utils/decode-wa-message.js +305 -0
- package/lib/Utils/event-buffer.js +555 -0
- package/lib/Utils/generics.js +411 -0
- package/lib/Utils/history.js +100 -0
- package/lib/Utils/identity-change-handler.js +53 -0
- package/lib/Utils/index.js +57 -0
- package/lib/Utils/link-preview.js +76 -0
- package/lib/Utils/logger.js +4 -0
- package/lib/Utils/lt-hash.js +45 -0
- package/lib/Utils/make-mutex.js +33 -0
- package/lib/Utils/message-composer.js +289 -0
- package/lib/Utils/message-retry-manager.js +134 -0
- package/lib/Utils/messages-media.js +806 -0
- package/lib/Utils/messages.js +1908 -0
- package/lib/Utils/noise-handler.js +157 -0
- package/lib/Utils/offline-node-processor.js +42 -0
- package/lib/Utils/pre-key-manager.js +86 -0
- package/lib/Utils/process-message.js +814 -0
- package/lib/Utils/reporting-utils.js +264 -0
- package/lib/Utils/signal.js +183 -0
- package/lib/Utils/stanza-ack.js +36 -0
- package/lib/Utils/sync-action-utils.js +52 -0
- package/lib/Utils/tc-token-utils.js +167 -0
- package/lib/Utils/use-multi-file-auth-state.js +104 -0
- package/lib/Utils/validate-connection.js +229 -0
- package/lib/Utils/vialeys-event-stream.js +41 -0
- package/lib/WABinary/constants.js +1308 -0
- package/lib/WABinary/decode.js +233 -0
- package/lib/WABinary/encode.js +212 -0
- package/lib/WABinary/generic-utils.js +124 -0
- package/lib/WABinary/index.js +36 -0
- package/lib/WABinary/jid-utils.js +101 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +12 -0
- package/lib/WAM/constants.js +20491 -0
- package/lib/WAM/encode.js +148 -0
- package/lib/WAM/index.js +34 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.js +38 -0
- package/lib/WAUSync/USyncQuery.js +97 -0
- package/lib/WAUSync/USyncUser.js +33 -0
- package/lib/WAUSync/index.js +34 -0
- package/lib/index.js +113 -0
- package/lib/messages-send.js +1496 -0
- package/package.json +100 -0
|
@@ -0,0 +1,1505 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const { default: NodeCache } = require("@cacheable/node-cache");
|
|
4
|
+
const { Boom: Boom } = require("@hapi/boom");
|
|
5
|
+
const { randomBytes: randomBytes } = require("crypto");
|
|
6
|
+
const { proto: proto } = require("../../WAProto");
|
|
7
|
+
const {
|
|
8
|
+
DEFAULT_CACHE_TTLS: DEFAULT_CACHE_TTLS,
|
|
9
|
+
WA_DEFAULT_EPHEMERAL: WA_DEFAULT_EPHEMERAL,
|
|
10
|
+
} = require("../Defaults/constants");
|
|
11
|
+
const {
|
|
12
|
+
delay: delay,
|
|
13
|
+
assertMediaContent: assertMediaContent,
|
|
14
|
+
bindWaitForEvent: bindWaitForEvent,
|
|
15
|
+
decryptMediaRetryData: decryptMediaRetryData,
|
|
16
|
+
encodeNewsletterMessage: encodeNewsletterMessage,
|
|
17
|
+
encodeSignedDeviceIdentity: encodeSignedDeviceIdentity,
|
|
18
|
+
encodeWAMessage: encodeWAMessage,
|
|
19
|
+
encryptMediaRetryRequest: encryptMediaRetryRequest,
|
|
20
|
+
extractDeviceJids: extractDeviceJids,
|
|
21
|
+
generateMessageID: generateMessageID,
|
|
22
|
+
generateParticipantHashV2: generateParticipantHashV2,
|
|
23
|
+
generateWAMessage: generateWAMessage,
|
|
24
|
+
generateWAMessageFromContent: generateWAMessageFromContent,
|
|
25
|
+
getStatusCodeForMediaRetry: getStatusCodeForMediaRetry,
|
|
26
|
+
getUrlFromDirectPath: getUrlFromDirectPath,
|
|
27
|
+
getWAUploadToServer: getWAUploadToServer,
|
|
28
|
+
MessageRetryManager: MessageRetryManager,
|
|
29
|
+
normalizeMessageContent: normalizeMessageContent,
|
|
30
|
+
parseAndInjectE2ESessions: parseAndInjectE2ESessions,
|
|
31
|
+
unixTimestampSeconds: unixTimestampSeconds,
|
|
32
|
+
prepareAlbumMessageContent: prepareAlbumMessageContent,
|
|
33
|
+
aggregateMessageKeysNotFromMe: aggregateMessageKeysNotFromMe,
|
|
34
|
+
generateWAMessageContent: generateWAMessageContent,
|
|
35
|
+
} = require("../Utils");
|
|
36
|
+
const AsepXyzRichContent = require("./rich-content");
|
|
37
|
+
const { WAMessageAddressingMode: WAMessageAddressingMode } = require("../Types");
|
|
38
|
+
const {
|
|
39
|
+
areJidsSameUser: areJidsSameUser,
|
|
40
|
+
getBinaryNodeChild: getBinaryNodeChild,
|
|
41
|
+
getBinaryNodeChildren: getBinaryNodeChildren,
|
|
42
|
+
getBinaryFilteredBizBot: getBinaryFilteredBizBot,
|
|
43
|
+
getBinaryFilteredButtons: getBinaryFilteredButtons,
|
|
44
|
+
isHostedLidUser: isHostedLidUser,
|
|
45
|
+
isHostedPnUser: isHostedPnUser,
|
|
46
|
+
isJidNewsletter: isJidNewsletter,
|
|
47
|
+
isJidGroup: isJidGroup,
|
|
48
|
+
isLidUser: isLidUser,
|
|
49
|
+
isPnUser: isPnUser,
|
|
50
|
+
jidDecode: jidDecode,
|
|
51
|
+
jidEncode: jidEncode,
|
|
52
|
+
jidNormalizedUser: jidNormalizedUser,
|
|
53
|
+
STORIES_JID: STORIES_JID,
|
|
54
|
+
S_WHATSAPP_NET: S_WHATSAPP_NET,
|
|
55
|
+
} = require("../WABinary");
|
|
56
|
+
const { USyncUser: USyncUser, USyncQuery: USyncQuery } = require("../WAUSync");
|
|
57
|
+
const { makeNewsletterSocket: makeNewsletterSocket } = require("./newsletter");
|
|
58
|
+
const { getUrlInfo: getUrlInfo } = require("../Utils/link-preview");
|
|
59
|
+
const { makeKeyedMutex: makeKeyedMutex } = require("../Utils/make-mutex");
|
|
60
|
+
const makeMessagesSocket = (config) => {
|
|
61
|
+
const {
|
|
62
|
+
logger: logger,
|
|
63
|
+
linkPreviewImageThumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
64
|
+
generateHighQualityLinkPreview: generateHighQualityLinkPreview,
|
|
65
|
+
options: httpRequestOptions,
|
|
66
|
+
patchMessageBeforeSending: patchMessageBeforeSending,
|
|
67
|
+
cachedGroupMetadata: cachedGroupMetadata,
|
|
68
|
+
enableRecentMessageCache: enableRecentMessageCache,
|
|
69
|
+
maxMsgRetryCount: maxMsgRetryCount,
|
|
70
|
+
} = config;
|
|
71
|
+
const conn = makeNewsletterSocket(config);
|
|
72
|
+
const {
|
|
73
|
+
ev: ev,
|
|
74
|
+
authState: authState,
|
|
75
|
+
messageMutex: messageMutex,
|
|
76
|
+
signalRepository: signalRepository,
|
|
77
|
+
upsertMessage: upsertMessage,
|
|
78
|
+
createCallLink: createCallLink,
|
|
79
|
+
query: query,
|
|
80
|
+
fetchPrivacySettings: fetchPrivacySettings,
|
|
81
|
+
sendNode: sendNode,
|
|
82
|
+
groupQuery: groupQuery,
|
|
83
|
+
groupMetadata: groupMetadata,
|
|
84
|
+
groupToggleEphemeral: groupToggleEphemeral,
|
|
85
|
+
executeUSyncQuery: executeUSyncQuery,
|
|
86
|
+
newsletterMetadata: newsletterMetadata,
|
|
87
|
+
} = conn;
|
|
88
|
+
const userDevicesCache =
|
|
89
|
+
config.userDevicesCache ||
|
|
90
|
+
new NodeCache({
|
|
91
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
92
|
+
useClones: false,
|
|
93
|
+
});
|
|
94
|
+
const peerSessionsCache = new NodeCache({
|
|
95
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
96
|
+
useClones: false,
|
|
97
|
+
});
|
|
98
|
+
const messageRetryManager = enableRecentMessageCache
|
|
99
|
+
? new MessageRetryManager(logger, maxMsgRetryCount)
|
|
100
|
+
: null;
|
|
101
|
+
const encryptionMutex = makeKeyedMutex();
|
|
102
|
+
let mediaConn;
|
|
103
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
104
|
+
const media = await mediaConn;
|
|
105
|
+
if (
|
|
106
|
+
!media ||
|
|
107
|
+
forceGet ||
|
|
108
|
+
new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1e3
|
|
109
|
+
) {
|
|
110
|
+
mediaConn = (async () => {
|
|
111
|
+
const result = await query({
|
|
112
|
+
tag: "iq",
|
|
113
|
+
attrs: { type: "set", xmlns: "w:m", to: S_WHATSAPP_NET },
|
|
114
|
+
content: [{ tag: "media_conn", attrs: {} }],
|
|
115
|
+
});
|
|
116
|
+
const mediaConnNode = getBinaryNodeChild(result, "media_conn");
|
|
117
|
+
const node = {
|
|
118
|
+
hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs: attrs }) => ({
|
|
119
|
+
hostname: attrs.hostname,
|
|
120
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes,
|
|
121
|
+
})),
|
|
122
|
+
auth: mediaConnNode.attrs.auth,
|
|
123
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
124
|
+
fetchDate: new Date(),
|
|
125
|
+
};
|
|
126
|
+
logger.debug("fetched media conn");
|
|
127
|
+
return node;
|
|
128
|
+
})();
|
|
129
|
+
}
|
|
130
|
+
return mediaConn;
|
|
131
|
+
};
|
|
132
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
133
|
+
if (!messageIds || messageIds.length === 0) {
|
|
134
|
+
throw new Boom("missing ids in receipt");
|
|
135
|
+
}
|
|
136
|
+
const node = { tag: "receipt", attrs: { id: messageIds[0] } };
|
|
137
|
+
const isReadReceipt = type === "read" || type === "read-self";
|
|
138
|
+
if (isReadReceipt) {
|
|
139
|
+
node.attrs.t = unixTimestampSeconds().toString();
|
|
140
|
+
}
|
|
141
|
+
if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
|
|
142
|
+
node.attrs.recipient = jid;
|
|
143
|
+
node.attrs.to = participant;
|
|
144
|
+
} else {
|
|
145
|
+
node.attrs.to = jid;
|
|
146
|
+
if (participant) {
|
|
147
|
+
node.attrs.participant = participant;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (type) {
|
|
151
|
+
node.attrs.type = type;
|
|
152
|
+
}
|
|
153
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
154
|
+
if (remainingMessageIds.length) {
|
|
155
|
+
node.content = [
|
|
156
|
+
{
|
|
157
|
+
tag: "list",
|
|
158
|
+
attrs: {},
|
|
159
|
+
content: remainingMessageIds.map((id) => ({
|
|
160
|
+
tag: "item",
|
|
161
|
+
attrs: { id: id },
|
|
162
|
+
})),
|
|
163
|
+
},
|
|
164
|
+
];
|
|
165
|
+
}
|
|
166
|
+
logger.debug({ attrs: node.attrs, messageIds: messageIds }, "sending receipt for messages");
|
|
167
|
+
await sendNode(node);
|
|
168
|
+
};
|
|
169
|
+
const sendReceipts = async (keys, type) => {
|
|
170
|
+
const recps = aggregateMessageKeysNotFromMe(keys);
|
|
171
|
+
for (const { jid: jid, participant: participant, messageIds: messageIds } of recps) {
|
|
172
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const readMessages = async (keys) => {
|
|
176
|
+
const privacySettings = await fetchPrivacySettings();
|
|
177
|
+
const readType = privacySettings.readreceipts === "all" ? "read" : "read-self";
|
|
178
|
+
await sendReceipts(keys, readType);
|
|
179
|
+
};
|
|
180
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
181
|
+
const deviceResults = [];
|
|
182
|
+
if (!useCache) {
|
|
183
|
+
logger.debug("not using cache for devices");
|
|
184
|
+
}
|
|
185
|
+
const toFetch = [];
|
|
186
|
+
const jidsWithUser = jids
|
|
187
|
+
.map((jid) => {
|
|
188
|
+
const decoded = jidDecode(jid);
|
|
189
|
+
const user = decoded?.user;
|
|
190
|
+
const device = decoded?.device;
|
|
191
|
+
const isExplicitDevice = typeof device === "number" && device >= 0;
|
|
192
|
+
if (isExplicitDevice && user) {
|
|
193
|
+
deviceResults.push({ user: user, device: device, jid: jid });
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
jid = jidNormalizedUser(jid);
|
|
197
|
+
return { jid: jid, user: user };
|
|
198
|
+
})
|
|
199
|
+
.filter((jid) => jid !== null);
|
|
200
|
+
let mgetDevices;
|
|
201
|
+
if (useCache && userDevicesCache.mget) {
|
|
202
|
+
const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
|
|
203
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
204
|
+
}
|
|
205
|
+
for (const { jid: jid, user: user } of jidsWithUser) {
|
|
206
|
+
if (useCache) {
|
|
207
|
+
const devices =
|
|
208
|
+
mgetDevices?.[user] ||
|
|
209
|
+
(userDevicesCache.mget ? undefined : await userDevicesCache.get(user));
|
|
210
|
+
if (devices) {
|
|
211
|
+
const devicesWithJid = devices.map((d) => ({
|
|
212
|
+
...d,
|
|
213
|
+
jid: jidEncode(d.user, d.server, d.device),
|
|
214
|
+
}));
|
|
215
|
+
deviceResults.push(...devicesWithJid);
|
|
216
|
+
logger.trace({ user: user }, "using cache for devices");
|
|
217
|
+
} else {
|
|
218
|
+
toFetch.push(jid);
|
|
219
|
+
}
|
|
220
|
+
} else {
|
|
221
|
+
toFetch.push(jid);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (!toFetch.length) {
|
|
225
|
+
return deviceResults;
|
|
226
|
+
}
|
|
227
|
+
const requestedLidUsers = new Set();
|
|
228
|
+
for (const jid of toFetch) {
|
|
229
|
+
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
230
|
+
const user = jidDecode(jid)?.user;
|
|
231
|
+
if (user) requestedLidUsers.add(user);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const query = new USyncQuery()
|
|
235
|
+
.withContext("message")
|
|
236
|
+
.withDeviceProtocol()
|
|
237
|
+
.withLIDProtocol();
|
|
238
|
+
for (const jid of toFetch) {
|
|
239
|
+
query.withUser(new USyncUser().withId(jid));
|
|
240
|
+
}
|
|
241
|
+
const result = await executeUSyncQuery(query);
|
|
242
|
+
if (result) {
|
|
243
|
+
const lidResults = result.list.filter((a) => !!a.lid);
|
|
244
|
+
if (lidResults.length > 0) {
|
|
245
|
+
logger.trace("Storing LID maps from device call");
|
|
246
|
+
await signalRepository.lidMapping.storeLIDPNMappings(
|
|
247
|
+
lidResults.map((a) => ({ lid: a.lid, pn: a.id }))
|
|
248
|
+
);
|
|
249
|
+
try {
|
|
250
|
+
const lids = lidResults.map((a) => a.lid);
|
|
251
|
+
if (lids.length) {
|
|
252
|
+
await assertSessions(lids, true);
|
|
253
|
+
}
|
|
254
|
+
} catch (e) {
|
|
255
|
+
logger.warn(
|
|
256
|
+
{ e: e, count: lidResults.length },
|
|
257
|
+
"failed to assert sessions for newly mapped LIDs"
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const extracted = extractDeviceJids(
|
|
262
|
+
result?.list,
|
|
263
|
+
authState.creds.me.id,
|
|
264
|
+
authState.creds.me.lid,
|
|
265
|
+
ignoreZeroDevices
|
|
266
|
+
);
|
|
267
|
+
const deviceMap = {};
|
|
268
|
+
for (const item of extracted) {
|
|
269
|
+
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
270
|
+
deviceMap[item.user]?.push(item);
|
|
271
|
+
}
|
|
272
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
273
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
274
|
+
for (const item of userDevices) {
|
|
275
|
+
const finalJid = isLidUser
|
|
276
|
+
? jidEncode(user, item.server, item.device)
|
|
277
|
+
: jidEncode(item.user, item.server, item.device);
|
|
278
|
+
deviceResults.push({ ...item, jid: finalJid });
|
|
279
|
+
logger.debug(
|
|
280
|
+
{
|
|
281
|
+
user: item.user,
|
|
282
|
+
device: item.device,
|
|
283
|
+
finalJid: finalJid,
|
|
284
|
+
usedLid: isLidUser,
|
|
285
|
+
},
|
|
286
|
+
"Processed device with LID priority"
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (userDevicesCache.mset) {
|
|
291
|
+
await userDevicesCache.mset(
|
|
292
|
+
Object.entries(deviceMap).map(([key, value]) => ({
|
|
293
|
+
key: key,
|
|
294
|
+
value: value,
|
|
295
|
+
}))
|
|
296
|
+
);
|
|
297
|
+
} else {
|
|
298
|
+
for (const key in deviceMap) {
|
|
299
|
+
if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const userDeviceUpdates = {};
|
|
303
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
304
|
+
if (devices && devices.length > 0) {
|
|
305
|
+
userDeviceUpdates[userId] = devices.map((d) => d.device?.toString() || "0");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
309
|
+
try {
|
|
310
|
+
await authState.keys.set({ "device-list": userDeviceUpdates });
|
|
311
|
+
logger.debug(
|
|
312
|
+
{ userCount: Object.keys(userDeviceUpdates).length },
|
|
313
|
+
"stored user device lists for bulk migration"
|
|
314
|
+
);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
logger.warn({ error: error }, "failed to store user device lists");
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return deviceResults;
|
|
321
|
+
};
|
|
322
|
+
const updateMemberLabel = (jid, memberLabel) => {
|
|
323
|
+
if (!isJidGroup(jid)) {
|
|
324
|
+
throw new Error("Jid must a group!");
|
|
325
|
+
}
|
|
326
|
+
const protocolMessage = {
|
|
327
|
+
protocolMessage: {
|
|
328
|
+
type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
|
|
329
|
+
memberLabel: {
|
|
330
|
+
label: memberLabel?.slice(0, 30),
|
|
331
|
+
labelTimestamp: unixTimestampSeconds(),
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
return relayMessage(jid, protocolMessage, {
|
|
336
|
+
additionalNodes: [
|
|
337
|
+
{
|
|
338
|
+
tag: "meta",
|
|
339
|
+
attrs: { tag_reason: "user_update", appdata: "member_tag" },
|
|
340
|
+
},
|
|
341
|
+
],
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
const assertSessions = async (jids, force) => {
|
|
345
|
+
let didFetchNewSession = false;
|
|
346
|
+
const uniqueJids = [...new Set(jids)];
|
|
347
|
+
const jidsRequiringFetch = [];
|
|
348
|
+
logger.debug({ jids: jids }, "assertSessions call with jids");
|
|
349
|
+
for (const jid of uniqueJids) {
|
|
350
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(jid);
|
|
351
|
+
const cachedSession = peerSessionsCache.get(signalId);
|
|
352
|
+
if (cachedSession !== undefined) {
|
|
353
|
+
if (cachedSession && !force) {
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
} else {
|
|
357
|
+
const sessionValidation = await signalRepository.validateSession(jid);
|
|
358
|
+
const hasSession = sessionValidation.exists;
|
|
359
|
+
peerSessionsCache.set(signalId, hasSession);
|
|
360
|
+
if (hasSession && !force) {
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
jidsRequiringFetch.push(jid);
|
|
365
|
+
}
|
|
366
|
+
if (jidsRequiringFetch.length) {
|
|
367
|
+
const wireJids = [
|
|
368
|
+
...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
369
|
+
...(
|
|
370
|
+
(await signalRepository.lidMapping.getLIDsForPNs(
|
|
371
|
+
jidsRequiringFetch.filter((jid) => !!isPnUser(jid) || !!isHostedPnUser(jid))
|
|
372
|
+
)) || []
|
|
373
|
+
).map((a) => a.lid),
|
|
374
|
+
];
|
|
375
|
+
logger.debug(
|
|
376
|
+
{ jidsRequiringFetch: jidsRequiringFetch, wireJids: wireJids },
|
|
377
|
+
"fetching sessions"
|
|
378
|
+
);
|
|
379
|
+
const result = await query({
|
|
380
|
+
tag: "iq",
|
|
381
|
+
attrs: { xmlns: "encrypt", type: "get", to: S_WHATSAPP_NET },
|
|
382
|
+
content: [
|
|
383
|
+
{
|
|
384
|
+
tag: "key",
|
|
385
|
+
attrs: {},
|
|
386
|
+
content: wireJids.map((jid) => {
|
|
387
|
+
const attrs = { jid: jid };
|
|
388
|
+
if (force) attrs.reason = "identity";
|
|
389
|
+
return { tag: "user", attrs: attrs };
|
|
390
|
+
}),
|
|
391
|
+
},
|
|
392
|
+
],
|
|
393
|
+
});
|
|
394
|
+
await parseAndInjectE2ESessions(result, signalRepository);
|
|
395
|
+
didFetchNewSession = true;
|
|
396
|
+
for (const wireJid of wireJids) {
|
|
397
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
|
|
398
|
+
peerSessionsCache.set(signalId, true);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return didFetchNewSession;
|
|
402
|
+
};
|
|
403
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
404
|
+
if (!authState.creds.me?.id) {
|
|
405
|
+
throw new Boom("Not authenticated");
|
|
406
|
+
}
|
|
407
|
+
const protocolMessage = {
|
|
408
|
+
protocolMessage: {
|
|
409
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
410
|
+
type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE,
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
const meJid = jidNormalizedUser(authState.creds.me.id);
|
|
414
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
415
|
+
additionalAttributes: { category: "peer", push_priority: "high_force" },
|
|
416
|
+
additionalNodes: [{ tag: "meta", attrs: { appdata: "default" } }],
|
|
417
|
+
});
|
|
418
|
+
return msgId;
|
|
419
|
+
};
|
|
420
|
+
const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
|
|
421
|
+
if (!recipientJids.length) {
|
|
422
|
+
return { nodes: [], shouldIncludeDeviceIdentity: false };
|
|
423
|
+
}
|
|
424
|
+
const patched = await patchMessageBeforeSending(message, recipientJids);
|
|
425
|
+
const patchedMessages = Array.isArray(patched)
|
|
426
|
+
? patched
|
|
427
|
+
: recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
|
|
428
|
+
let shouldIncludeDeviceIdentity = false;
|
|
429
|
+
const meId = authState.creds.me.id;
|
|
430
|
+
const meLid = authState.creds.me?.lid;
|
|
431
|
+
const meLidUser = meLid ? jidDecode(meLid)?.user : null;
|
|
432
|
+
const encryptionPromises = patchedMessages.map(
|
|
433
|
+
async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
434
|
+
if (!jid) return null;
|
|
435
|
+
let msgToEncrypt = patchedMessage;
|
|
436
|
+
if (dsmMessage) {
|
|
437
|
+
const { user: targetUser } = jidDecode(jid);
|
|
438
|
+
const { user: ownPnUser } = jidDecode(meId);
|
|
439
|
+
const ownLidUser = meLidUser;
|
|
440
|
+
const isOwnUser =
|
|
441
|
+
targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
|
|
442
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
443
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
444
|
+
msgToEncrypt = dsmMessage;
|
|
445
|
+
logger.debug(
|
|
446
|
+
{ jid: jid, targetUser: targetUser },
|
|
447
|
+
"Using DSM for own device"
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const bytes = encodeWAMessage(msgToEncrypt);
|
|
452
|
+
const mutexKey = jid;
|
|
453
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
454
|
+
const { type: type, ciphertext: ciphertext } =
|
|
455
|
+
await signalRepository.encryptMessage({ jid: jid, data: bytes });
|
|
456
|
+
if (type === "pkmsg") {
|
|
457
|
+
shouldIncludeDeviceIdentity = true;
|
|
458
|
+
}
|
|
459
|
+
return {
|
|
460
|
+
tag: "to",
|
|
461
|
+
attrs: { jid: jid },
|
|
462
|
+
content: [
|
|
463
|
+
{
|
|
464
|
+
tag: "enc",
|
|
465
|
+
attrs: { v: "2", type: type, ...(extraAttrs || {}) },
|
|
466
|
+
content: ciphertext,
|
|
467
|
+
},
|
|
468
|
+
],
|
|
469
|
+
};
|
|
470
|
+
});
|
|
471
|
+
return node;
|
|
472
|
+
}
|
|
473
|
+
);
|
|
474
|
+
const nodes = (await Promise.all(encryptionPromises)).filter((node) => node !== null);
|
|
475
|
+
return {
|
|
476
|
+
nodes: nodes,
|
|
477
|
+
shouldIncludeDeviceIdentity: shouldIncludeDeviceIdentity,
|
|
478
|
+
};
|
|
479
|
+
};
|
|
480
|
+
const profilePictureUrl = async (jid) => {
|
|
481
|
+
if (isJidNewsletter(jid)) {
|
|
482
|
+
const metadata = await conn.newsletterMetadata("JID", jid);
|
|
483
|
+
return getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || "");
|
|
484
|
+
} else {
|
|
485
|
+
const result = await query({
|
|
486
|
+
tag: "iq",
|
|
487
|
+
attrs: {
|
|
488
|
+
target: jidNormalizedUser(jid),
|
|
489
|
+
to: S_WHATSAPP_NET,
|
|
490
|
+
type: "get",
|
|
491
|
+
xmlns: "w:profile:picture",
|
|
492
|
+
},
|
|
493
|
+
content: [{ tag: "picture", attrs: { type: "image", query: "url" } }],
|
|
494
|
+
});
|
|
495
|
+
const child = getBinaryNodeChild(result, "picture");
|
|
496
|
+
return child?.attrs?.url || null;
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
const relayMessage = async (
|
|
500
|
+
jid,
|
|
501
|
+
message,
|
|
502
|
+
{
|
|
503
|
+
messageId: msgId,
|
|
504
|
+
participant: participant,
|
|
505
|
+
additionalAttributes: additionalAttributes,
|
|
506
|
+
useUserDevicesCache: useUserDevicesCache,
|
|
507
|
+
useCachedGroupMetadata: useCachedGroupMetadata,
|
|
508
|
+
statusJidList: statusJidList,
|
|
509
|
+
additionalNodes: additionalNodes,
|
|
510
|
+
AI: AI = false,
|
|
511
|
+
}
|
|
512
|
+
) => {
|
|
513
|
+
const meId = authState.creds.me.id;
|
|
514
|
+
const meLid = authState.creds.me?.lid;
|
|
515
|
+
const isRetryResend = Boolean(participant?.jid);
|
|
516
|
+
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
517
|
+
let didPushAdditional = false;
|
|
518
|
+
const statusJid = "status@broadcast";
|
|
519
|
+
const { user: user, server: server } = jidDecode(jid);
|
|
520
|
+
const isGroup = server === "g.us";
|
|
521
|
+
const isStatus = jid === statusJid;
|
|
522
|
+
const isLid = server === "lid";
|
|
523
|
+
const isNewsletter = server === "newsletter";
|
|
524
|
+
const isGroupOrStatus = isGroup || isStatus;
|
|
525
|
+
const finalJid = jid;
|
|
526
|
+
msgId = msgId || generateMessageID(meId);
|
|
527
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
528
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
529
|
+
const participants = [];
|
|
530
|
+
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
531
|
+
const binaryNodeContent = [];
|
|
532
|
+
const devices = [];
|
|
533
|
+
const meMsg = {
|
|
534
|
+
deviceSentMessage: { destinationJid: destinationJid, message: message },
|
|
535
|
+
messageContextInfo: message.messageContextInfo,
|
|
536
|
+
};
|
|
537
|
+
const extraAttrs = {};
|
|
538
|
+
const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/;
|
|
539
|
+
const messages = normalizeMessageContent(message);
|
|
540
|
+
const buttonType = getButtonType(messages);
|
|
541
|
+
const pollMessage =
|
|
542
|
+
messages.pollCreationMessage ||
|
|
543
|
+
messages.pollCreationMessageV2 ||
|
|
544
|
+
messages.pollCreationMessageV3;
|
|
545
|
+
if (participant) {
|
|
546
|
+
if (!isGroup && !isStatus) {
|
|
547
|
+
additionalAttributes = {
|
|
548
|
+
...additionalAttributes,
|
|
549
|
+
device_fanout: "false",
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
const { user: user, device: device } = jidDecode(participant.jid);
|
|
553
|
+
devices.push({ user: user, device: device, jid: participant.jid });
|
|
554
|
+
}
|
|
555
|
+
await authState.keys.transaction(async () => {
|
|
556
|
+
const mediaType = getMediaType(message);
|
|
557
|
+
if (mediaType) {
|
|
558
|
+
extraAttrs["mediatype"] = mediaType;
|
|
559
|
+
}
|
|
560
|
+
if (isNewsletter) {
|
|
561
|
+
|
|
562
|
+
const patched = patchMessageBeforeSending
|
|
563
|
+
? await patchMessageBeforeSending(message, [])
|
|
564
|
+
: message
|
|
565
|
+
|
|
566
|
+
const mediaType = getMediaType(patched)
|
|
567
|
+
|
|
568
|
+
if (mediaType) {
|
|
569
|
+
extraAttrs["mediatype"] = mediaType
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (
|
|
573
|
+
patched.interactiveMessage &&
|
|
574
|
+
!extraAttrs["mediatype"]
|
|
575
|
+
) {
|
|
576
|
+
extraAttrs["mediatype"] = "interactive"
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const bytes = encodeNewsletterMessage(patched)
|
|
580
|
+
|
|
581
|
+
binaryNodeContent.push({
|
|
582
|
+
tag: "plaintext",
|
|
583
|
+
attrs: extraAttrs,
|
|
584
|
+
content: bytes
|
|
585
|
+
})
|
|
586
|
+
|
|
587
|
+
const stanza = {
|
|
588
|
+
tag: "message",
|
|
589
|
+
attrs: {
|
|
590
|
+
to: jid,
|
|
591
|
+
id: msgId,
|
|
592
|
+
type: getTypeMessage(patched),
|
|
593
|
+
...(additionalAttributes || {}),
|
|
594
|
+
},
|
|
595
|
+
content: binaryNodeContent,
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
logger.debug(
|
|
599
|
+
{
|
|
600
|
+
msgId,
|
|
601
|
+
mediaType,
|
|
602
|
+
extraAttrs
|
|
603
|
+
},
|
|
604
|
+
`sending newsletter message to ${jid}`
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
await sendNode(stanza)
|
|
608
|
+
|
|
609
|
+
return
|
|
610
|
+
}
|
|
611
|
+
if (
|
|
612
|
+
messages.pinInChatMessage ||
|
|
613
|
+
messages.keepInChatMessage ||
|
|
614
|
+
message.reactionMessage ||
|
|
615
|
+
message.protocolMessage?.editedMessage
|
|
616
|
+
) {
|
|
617
|
+
extraAttrs["decrypt-fail"] = "hide";
|
|
618
|
+
}
|
|
619
|
+
if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
|
|
620
|
+
extraAttrs["native_flow_name"] =
|
|
621
|
+
messages.interactiveResponseMessage.nativeFlowResponseMessage?.name ||
|
|
622
|
+
"menu_options";
|
|
623
|
+
}
|
|
624
|
+
if (isGroupOrStatus && !isRetryResend) {
|
|
625
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
626
|
+
(async () => {
|
|
627
|
+
let groupData =
|
|
628
|
+
useCachedGroupMetadata && cachedGroupMetadata
|
|
629
|
+
? await cachedGroupMetadata(jid)
|
|
630
|
+
: undefined;
|
|
631
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
632
|
+
logger.trace(
|
|
633
|
+
{ jid: jid, participants: groupData.participants.length },
|
|
634
|
+
"using cached group metadata"
|
|
635
|
+
);
|
|
636
|
+
} else if (!isStatus) {
|
|
637
|
+
groupData = await groupMetadata(jid);
|
|
638
|
+
}
|
|
639
|
+
return groupData;
|
|
640
|
+
})(),
|
|
641
|
+
(async () => {
|
|
642
|
+
if (!participant && !isStatus) {
|
|
643
|
+
const result = await authState.keys.get("sender-key-memory", [jid]);
|
|
644
|
+
return result[jid] || {};
|
|
645
|
+
}
|
|
646
|
+
return {};
|
|
647
|
+
})(),
|
|
648
|
+
]);
|
|
649
|
+
const participantsList = groupData ? groupData.participants.map((p) => p.id) : [];
|
|
650
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
651
|
+
additionalAttributes = {
|
|
652
|
+
...additionalAttributes,
|
|
653
|
+
expiration: groupData.ephemeralDuration.toString(),
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
if (isStatus && statusJidList) {
|
|
657
|
+
participantsList.push(...statusJidList);
|
|
658
|
+
}
|
|
659
|
+
const additionalDevices = await getUSyncDevices(
|
|
660
|
+
participantsList,
|
|
661
|
+
!!useUserDevicesCache,
|
|
662
|
+
false
|
|
663
|
+
);
|
|
664
|
+
devices.push(...additionalDevices);
|
|
665
|
+
if (isGroup) {
|
|
666
|
+
additionalAttributes = {
|
|
667
|
+
...additionalAttributes,
|
|
668
|
+
addressing_mode: groupData?.addressingMode || "lid",
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
const patched = await patchMessageBeforeSending(message);
|
|
672
|
+
if (Array.isArray(patched)) {
|
|
673
|
+
throw new Boom("Per-jid patching is not supported in groups");
|
|
674
|
+
}
|
|
675
|
+
const bytes = encodeWAMessage(patched);
|
|
676
|
+
const groupAddressingMode =
|
|
677
|
+
additionalAttributes?.["addressing_mode"] || groupData?.addressingMode || "lid";
|
|
678
|
+
const groupSenderIdentity = groupAddressingMode === "lid" && meLid ? meLid : meId;
|
|
679
|
+
const {
|
|
680
|
+
ciphertext: ciphertext,
|
|
681
|
+
senderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
682
|
+
} = await signalRepository.encryptGroupMessage({
|
|
683
|
+
group: destinationJid,
|
|
684
|
+
data: bytes,
|
|
685
|
+
meId: groupSenderIdentity,
|
|
686
|
+
});
|
|
687
|
+
const senderKeyRecipients = [];
|
|
688
|
+
for (const device of devices) {
|
|
689
|
+
const deviceJid = device.jid;
|
|
690
|
+
const hasKey = !!senderKeyMap[deviceJid];
|
|
691
|
+
if (
|
|
692
|
+
(!hasKey || !!participant) &&
|
|
693
|
+
!isHostedLidUser(deviceJid) &&
|
|
694
|
+
!isHostedPnUser(deviceJid) &&
|
|
695
|
+
device.device !== 99
|
|
696
|
+
) {
|
|
697
|
+
senderKeyRecipients.push(deviceJid);
|
|
698
|
+
senderKeyMap[deviceJid] = true;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
if (senderKeyRecipients.length) {
|
|
702
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, "sending new sender key");
|
|
703
|
+
const senderKeyMsg = {
|
|
704
|
+
senderKeyDistributionMessage: {
|
|
705
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
706
|
+
groupId: destinationJid,
|
|
707
|
+
},
|
|
708
|
+
};
|
|
709
|
+
const senderKeySessionTargets = senderKeyRecipients;
|
|
710
|
+
await assertSessions(senderKeySessionTargets);
|
|
711
|
+
const result = await createParticipantNodes(
|
|
712
|
+
senderKeyRecipients,
|
|
713
|
+
senderKeyMsg,
|
|
714
|
+
extraAttrs
|
|
715
|
+
);
|
|
716
|
+
shouldIncludeDeviceIdentity =
|
|
717
|
+
shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
718
|
+
participants.push(...result.nodes);
|
|
719
|
+
}
|
|
720
|
+
binaryNodeContent.push({
|
|
721
|
+
tag: "enc",
|
|
722
|
+
attrs: { v: "2", type: "skmsg", ...extraAttrs },
|
|
723
|
+
content: ciphertext,
|
|
724
|
+
});
|
|
725
|
+
await authState.keys.set({
|
|
726
|
+
"sender-key-memory": { [jid]: senderKeyMap },
|
|
727
|
+
});
|
|
728
|
+
} else {
|
|
729
|
+
let ownId = meId;
|
|
730
|
+
if (isLid && meLid) {
|
|
731
|
+
ownId = meLid;
|
|
732
|
+
logger.debug(
|
|
733
|
+
{ to: jid, ownId: ownId },
|
|
734
|
+
"Using LID identity for @lid conversation"
|
|
735
|
+
);
|
|
736
|
+
} else {
|
|
737
|
+
logger.debug(
|
|
738
|
+
{ to: jid, ownId: ownId },
|
|
739
|
+
"Using PN identity for @s.whatsapp.net conversation"
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
const { user: ownUser } = jidDecode(ownId);
|
|
743
|
+
if (!isRetryResend) {
|
|
744
|
+
const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
|
|
745
|
+
devices.push({
|
|
746
|
+
user: user,
|
|
747
|
+
device: 0,
|
|
748
|
+
jid: jidEncode(user, targetUserServer, 0),
|
|
749
|
+
});
|
|
750
|
+
if (user !== ownUser) {
|
|
751
|
+
const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
|
|
752
|
+
const ownUserForAddressing =
|
|
753
|
+
isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
|
|
754
|
+
devices.push({
|
|
755
|
+
user: ownUserForAddressing,
|
|
756
|
+
device: 0,
|
|
757
|
+
jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
if (additionalAttributes?.["category"] !== "peer") {
|
|
761
|
+
devices.length = 0;
|
|
762
|
+
const senderIdentity =
|
|
763
|
+
isLid && meLid
|
|
764
|
+
? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
|
|
765
|
+
: jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
|
|
766
|
+
const sessionDevices = await getUSyncDevices(
|
|
767
|
+
[senderIdentity, jid],
|
|
768
|
+
true,
|
|
769
|
+
false
|
|
770
|
+
);
|
|
771
|
+
devices.push(...sessionDevices);
|
|
772
|
+
logger.debug(
|
|
773
|
+
{
|
|
774
|
+
deviceCount: devices.length,
|
|
775
|
+
devices: devices.map(
|
|
776
|
+
(d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`
|
|
777
|
+
),
|
|
778
|
+
},
|
|
779
|
+
"Device enumeration complete with unified addressing"
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const allRecipients = [];
|
|
784
|
+
const meRecipients = [];
|
|
785
|
+
const otherRecipients = [];
|
|
786
|
+
const { user: mePnUser } = jidDecode(meId);
|
|
787
|
+
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
|
|
788
|
+
for (const { user: user, jid: jid } of devices) {
|
|
789
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
790
|
+
if (isExactSenderDevice) {
|
|
791
|
+
logger.debug(
|
|
792
|
+
{ jid: jid, meId: meId, meLid: meLid },
|
|
793
|
+
"Skipping exact sender device (whatsmeow pattern)"
|
|
794
|
+
);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
const isMe = user === mePnUser || user === meLidUser;
|
|
798
|
+
if (isMe) {
|
|
799
|
+
meRecipients.push(jid);
|
|
800
|
+
} else {
|
|
801
|
+
otherRecipients.push(jid);
|
|
802
|
+
}
|
|
803
|
+
allRecipients.push(jid);
|
|
804
|
+
}
|
|
805
|
+
await assertSessions(allRecipients);
|
|
806
|
+
const [
|
|
807
|
+
{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
|
|
808
|
+
{ nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
|
|
809
|
+
] = await Promise.all([
|
|
810
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
811
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
|
|
812
|
+
]);
|
|
813
|
+
participants.push(...meNodes);
|
|
814
|
+
participants.push(...otherNodes);
|
|
815
|
+
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
816
|
+
extraAttrs["phash"] = generateParticipantHashV2([
|
|
817
|
+
...meRecipients,
|
|
818
|
+
...otherRecipients,
|
|
819
|
+
]);
|
|
820
|
+
}
|
|
821
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
822
|
+
}
|
|
823
|
+
if (isRetryResend) {
|
|
824
|
+
const isParticipantLid = isLidUser(participant.jid);
|
|
825
|
+
const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
|
|
826
|
+
const encodedMessageToSend = isMe
|
|
827
|
+
? encodeWAMessage({
|
|
828
|
+
deviceSentMessage: {
|
|
829
|
+
destinationJid: destinationJid,
|
|
830
|
+
message: message,
|
|
831
|
+
},
|
|
832
|
+
})
|
|
833
|
+
: encodeWAMessage(message);
|
|
834
|
+
const { type: type, ciphertext: encryptedContent } =
|
|
835
|
+
await signalRepository.encryptMessage({
|
|
836
|
+
data: encodedMessageToSend,
|
|
837
|
+
jid: participant.jid,
|
|
838
|
+
});
|
|
839
|
+
binaryNodeContent.push({
|
|
840
|
+
tag: "enc",
|
|
841
|
+
attrs: { v: "2", type: type, count: participant.count.toString() },
|
|
842
|
+
content: encryptedContent,
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
if (participants.length) {
|
|
846
|
+
if (additionalAttributes?.["category"] === "peer") {
|
|
847
|
+
const peerNode = participants[0]?.content?.[0];
|
|
848
|
+
if (peerNode) {
|
|
849
|
+
binaryNodeContent.push(peerNode);
|
|
850
|
+
}
|
|
851
|
+
} else {
|
|
852
|
+
binaryNodeContent.push({
|
|
853
|
+
tag: "participants",
|
|
854
|
+
attrs: {},
|
|
855
|
+
content: participants,
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
const stanza = {
|
|
860
|
+
tag: "message",
|
|
861
|
+
attrs: {
|
|
862
|
+
id: msgId,
|
|
863
|
+
to: destinationJid,
|
|
864
|
+
type: getTypeMessage(message),
|
|
865
|
+
...(additionalAttributes || {}),
|
|
866
|
+
},
|
|
867
|
+
content: binaryNodeContent,
|
|
868
|
+
};
|
|
869
|
+
if (participant) {
|
|
870
|
+
if (isJidGroup(destinationJid)) {
|
|
871
|
+
stanza.attrs.to = destinationJid;
|
|
872
|
+
stanza.attrs.participant = participant.jid;
|
|
873
|
+
} else if (areJidsSameUser(participant.jid, meId)) {
|
|
874
|
+
stanza.attrs.to = participant.jid;
|
|
875
|
+
stanza.attrs.recipient = destinationJid;
|
|
876
|
+
} else {
|
|
877
|
+
stanza.attrs.to = participant.jid;
|
|
878
|
+
}
|
|
879
|
+
} else {
|
|
880
|
+
stanza.attrs.to = destinationJid;
|
|
881
|
+
}
|
|
882
|
+
if (shouldIncludeDeviceIdentity) {
|
|
883
|
+
stanza.content.push({
|
|
884
|
+
tag: "device-identity",
|
|
885
|
+
attrs: {},
|
|
886
|
+
content: encodeSignedDeviceIdentity(authState.creds.account, true),
|
|
887
|
+
});
|
|
888
|
+
logger.debug({ jid: jid }, "adding device identity");
|
|
889
|
+
}
|
|
890
|
+
const contactTcTokenData =
|
|
891
|
+
!isGroup && !isRetryResend && !isStatus
|
|
892
|
+
? await authState.keys.get("tctoken", [destinationJid])
|
|
893
|
+
: {};
|
|
894
|
+
const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
|
|
895
|
+
if (tcTokenBuffer) {
|
|
896
|
+
stanza.content.push({
|
|
897
|
+
tag: "tctoken",
|
|
898
|
+
attrs: {},
|
|
899
|
+
content: tcTokenBuffer,
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
|
|
903
|
+
stanza.content.push({ tag: "multicast", attrs: {} });
|
|
904
|
+
}
|
|
905
|
+
if (pollMessage || messages.eventMessage) {
|
|
906
|
+
stanza.content.push({
|
|
907
|
+
tag: "meta",
|
|
908
|
+
attrs: messages.eventMessage
|
|
909
|
+
? { event_type: "creation" }
|
|
910
|
+
: isNewsletter
|
|
911
|
+
? {
|
|
912
|
+
polltype: "creation",
|
|
913
|
+
contenttype: pollMessage?.pollContentType === 2 ? "image" : "text",
|
|
914
|
+
}
|
|
915
|
+
: { polltype: "creation" },
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
if (!isNewsletter && buttonType) {
|
|
919
|
+
const buttonsNode = getButtonArgs(messages);
|
|
920
|
+
const filteredButtons = getBinaryFilteredButtons(
|
|
921
|
+
additionalNodes ? additionalNodes : []
|
|
922
|
+
);
|
|
923
|
+
if (filteredButtons) {
|
|
924
|
+
stanza.content.push(...additionalNodes);
|
|
925
|
+
didPushAdditional = true;
|
|
926
|
+
} else {
|
|
927
|
+
stanza.content.push(buttonsNode);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
if (AI && isPrivate) {
|
|
931
|
+
const botNode = { tag: "bot", attrs: { biz_bot: "1" } };
|
|
932
|
+
const filteredBizBot = getBinaryFilteredBizBot(
|
|
933
|
+
additionalNodes ? additionalNodes : []
|
|
934
|
+
);
|
|
935
|
+
if (filteredBizBot) {
|
|
936
|
+
stanza.content.push(...additionalNodes);
|
|
937
|
+
didPushAdditional = true;
|
|
938
|
+
} else {
|
|
939
|
+
stanza.content.push(botNode);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
|
|
943
|
+
stanza.content.push(...additionalNodes);
|
|
944
|
+
}
|
|
945
|
+
logger.debug({ msgId: msgId }, `sending message to ${participants.length} devices`);
|
|
946
|
+
await sendNode(stanza);
|
|
947
|
+
if (messageRetryManager && !participant) {
|
|
948
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
949
|
+
}
|
|
950
|
+
}, meId);
|
|
951
|
+
return msgId;
|
|
952
|
+
};
|
|
953
|
+
const getTypeMessage = (msg) => {
|
|
954
|
+
const message = normalizeMessageContent(msg);
|
|
955
|
+
if (
|
|
956
|
+
message.pollCreationMessage ||
|
|
957
|
+
message.pollCreationMessageV2 ||
|
|
958
|
+
message.pollCreationMessageV3
|
|
959
|
+
) {
|
|
960
|
+
return "poll";
|
|
961
|
+
} else if (message.reactionMessage) {
|
|
962
|
+
return "reaction";
|
|
963
|
+
} else if (message.eventMessage) {
|
|
964
|
+
return "event";
|
|
965
|
+
} else if (getMediaType(message)) {
|
|
966
|
+
return "media";
|
|
967
|
+
} else {
|
|
968
|
+
return "text";
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
const getMediaType = (message) => {
|
|
972
|
+
if (message.imageMessage) {
|
|
973
|
+
return "image";
|
|
974
|
+
} else if (message.stickerMessage) {
|
|
975
|
+
return message.stickerMessage.isLottie
|
|
976
|
+
? "1p_sticker"
|
|
977
|
+
: message.stickerMessage.isAvatar
|
|
978
|
+
? "avatar_sticker"
|
|
979
|
+
: "sticker";
|
|
980
|
+
} else if (message.videoMessage) {
|
|
981
|
+
return message.videoMessage.gifPlayback ? "gif" : "video";
|
|
982
|
+
} else if (message.audioMessage) {
|
|
983
|
+
return message.audioMessage.ptt ? "ptt" : "audio";
|
|
984
|
+
} else if (message.ptvMessage) {
|
|
985
|
+
return "ptv";
|
|
986
|
+
} else if (message.albumMessage) {
|
|
987
|
+
return "collection";
|
|
988
|
+
} else if (message.contactMessage) {
|
|
989
|
+
return "vcard";
|
|
990
|
+
} else if (message.documentMessage) {
|
|
991
|
+
return "document";
|
|
992
|
+
} else if (message.stickerPackMessage) {
|
|
993
|
+
return "sticker_pack";
|
|
994
|
+
} else if (message.contactsArrayMessage) {
|
|
995
|
+
return "contact_array";
|
|
996
|
+
} else if (message.locationMessage) {
|
|
997
|
+
return "location";
|
|
998
|
+
} else if (message.liveLocationMessage) {
|
|
999
|
+
return "livelocation";
|
|
1000
|
+
} else if (message.listMessage) {
|
|
1001
|
+
return "list";
|
|
1002
|
+
} else if (message.listResponseMessage) {
|
|
1003
|
+
return "list_response";
|
|
1004
|
+
} else if (message.buttonsResponseMessage) {
|
|
1005
|
+
return "buttons_response";
|
|
1006
|
+
} else if (message.orderMessage) {
|
|
1007
|
+
return "order";
|
|
1008
|
+
} else if (message.productMessage) {
|
|
1009
|
+
return "product";
|
|
1010
|
+
} else if (message.interactiveResponseMessage) {
|
|
1011
|
+
return "native_flow_response";
|
|
1012
|
+
} else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
1013
|
+
return "cataloglink";
|
|
1014
|
+
} else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
1015
|
+
return "productlink";
|
|
1016
|
+
} else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
|
|
1017
|
+
return "url";
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
const getButtonType = (message) => {
|
|
1021
|
+
if (message.listMessage) {
|
|
1022
|
+
return "list";
|
|
1023
|
+
} else if (message.buttonsMessage) {
|
|
1024
|
+
return "buttons";
|
|
1025
|
+
} else if (message.interactiveMessage?.nativeFlowMessage) {
|
|
1026
|
+
return "native_flow";
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
const getButtonArgs = (message) => {
|
|
1030
|
+
const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
|
|
1031
|
+
const firstButtonName = nativeFlow?.buttons?.[0]?.name;
|
|
1032
|
+
const nativeFlowSpecials = [
|
|
1033
|
+
"mpm",
|
|
1034
|
+
"cta_catalog",
|
|
1035
|
+
"send_location",
|
|
1036
|
+
"call_permission_request",
|
|
1037
|
+
"wa_payment_transaction_details",
|
|
1038
|
+
"automated_greeting_message_view_catalog",
|
|
1039
|
+
];
|
|
1040
|
+
if (
|
|
1041
|
+
nativeFlow &&
|
|
1042
|
+
(firstButtonName === "review_and_pay" || firstButtonName === "payment_info")
|
|
1043
|
+
) {
|
|
1044
|
+
return {
|
|
1045
|
+
tag: "biz",
|
|
1046
|
+
attrs: {
|
|
1047
|
+
native_flow_name:
|
|
1048
|
+
firstButtonName === "review_and_pay" ? "order_details" : firstButtonName,
|
|
1049
|
+
},
|
|
1050
|
+
};
|
|
1051
|
+
} else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
|
|
1052
|
+
return {
|
|
1053
|
+
tag: "biz",
|
|
1054
|
+
attrs: {
|
|
1055
|
+
actual_actors: "2",
|
|
1056
|
+
host_storage: "2",
|
|
1057
|
+
privacy_mode_ts: unixTimestampSeconds().toString(),
|
|
1058
|
+
},
|
|
1059
|
+
content: [
|
|
1060
|
+
{
|
|
1061
|
+
tag: "interactive",
|
|
1062
|
+
attrs: { type: "native_flow", v: "1" },
|
|
1063
|
+
content: [{ tag: "native_flow", attrs: { v: "2", name: firstButtonName } }],
|
|
1064
|
+
},
|
|
1065
|
+
{ tag: "quality_control", attrs: { source_type: "third_party" } },
|
|
1066
|
+
],
|
|
1067
|
+
};
|
|
1068
|
+
} else if (nativeFlow || message.buttonsMessage) {
|
|
1069
|
+
return {
|
|
1070
|
+
tag: "biz",
|
|
1071
|
+
attrs: {
|
|
1072
|
+
actual_actors: "2",
|
|
1073
|
+
host_storage: "2",
|
|
1074
|
+
privacy_mode_ts: unixTimestampSeconds().toString(),
|
|
1075
|
+
},
|
|
1076
|
+
content: [
|
|
1077
|
+
{
|
|
1078
|
+
tag: "interactive",
|
|
1079
|
+
attrs: { type: "native_flow", v: "1" },
|
|
1080
|
+
content: [{ tag: "native_flow", attrs: { v: "9", name: "mixed" } }],
|
|
1081
|
+
},
|
|
1082
|
+
{ tag: "quality_control", attrs: { source_type: "third_party" } },
|
|
1083
|
+
],
|
|
1084
|
+
};
|
|
1085
|
+
} else if (message.listMessage) {
|
|
1086
|
+
return {
|
|
1087
|
+
tag: "biz",
|
|
1088
|
+
attrs: {
|
|
1089
|
+
actual_actors: "2",
|
|
1090
|
+
host_storage: "2",
|
|
1091
|
+
privacy_mode_ts: unixTimestampSeconds().toString(),
|
|
1092
|
+
},
|
|
1093
|
+
content: [
|
|
1094
|
+
{ tag: "list", attrs: { v: "2", type: "product_list" } },
|
|
1095
|
+
{ tag: "quality_control", attrs: { source_type: "third_party" } },
|
|
1096
|
+
],
|
|
1097
|
+
};
|
|
1098
|
+
} else {
|
|
1099
|
+
return {
|
|
1100
|
+
tag: "biz",
|
|
1101
|
+
attrs: {
|
|
1102
|
+
actual_actors: "2",
|
|
1103
|
+
host_storage: "2",
|
|
1104
|
+
privacy_mode_ts: unixTimestampSeconds().toString(),
|
|
1105
|
+
},
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
const getPrivacyTokens = async (jids) => {
|
|
1110
|
+
const t = unixTimestampSeconds().toString();
|
|
1111
|
+
const result = await query({
|
|
1112
|
+
tag: "iq",
|
|
1113
|
+
attrs: { to: S_WHATSAPP_NET, type: "set", xmlns: "privacy" },
|
|
1114
|
+
content: [
|
|
1115
|
+
{
|
|
1116
|
+
tag: "tokens",
|
|
1117
|
+
attrs: {},
|
|
1118
|
+
content: jids.map((jid) => ({
|
|
1119
|
+
tag: "token",
|
|
1120
|
+
attrs: {
|
|
1121
|
+
jid: jidNormalizedUser(jid),
|
|
1122
|
+
t: t,
|
|
1123
|
+
type: "trusted_contact",
|
|
1124
|
+
},
|
|
1125
|
+
})),
|
|
1126
|
+
},
|
|
1127
|
+
],
|
|
1128
|
+
});
|
|
1129
|
+
return result;
|
|
1130
|
+
};
|
|
1131
|
+
const getEphemeralGroup = (jid) => {
|
|
1132
|
+
if (!isJidGroup(jid)) throw new TypeError("Jid should originate from a group!");
|
|
1133
|
+
return groupQuery(jid, "get", [{ tag: "query", attrs: { request: "interactive" } }])
|
|
1134
|
+
.then((groups) => getBinaryNodeChild(groups, "group"))
|
|
1135
|
+
.then((metadata) => getBinaryNodeChild(metadata, "ephemeral")?.attrs?.expiration || 0);
|
|
1136
|
+
};
|
|
1137
|
+
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
|
|
1138
|
+
const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
|
|
1139
|
+
// Added for AsepXyz Baileys (ported from PouCode): handles rich sendMessage()
|
|
1140
|
+
// content shapes -- payment requests, product cards, events, poll results, orders, group labels.
|
|
1141
|
+
const richContent = new AsepXyzRichContent(
|
|
1142
|
+
{ generateWAMessageContent, generateWAMessageFromContent, generateMessageID },
|
|
1143
|
+
waUploadToServer,
|
|
1144
|
+
relayMessage
|
|
1145
|
+
);
|
|
1146
|
+
return {
|
|
1147
|
+
...conn,
|
|
1148
|
+
getPrivacyTokens: getPrivacyTokens,
|
|
1149
|
+
assertSessions: assertSessions,
|
|
1150
|
+
profilePictureUrl: profilePictureUrl,
|
|
1151
|
+
relayMessage: relayMessage,
|
|
1152
|
+
sendReceipt: sendReceipt,
|
|
1153
|
+
sendReceipts: sendReceipts,
|
|
1154
|
+
readMessages: readMessages,
|
|
1155
|
+
getUSyncDevices: getUSyncDevices,
|
|
1156
|
+
refreshMediaConn: refreshMediaConn,
|
|
1157
|
+
waUploadToServer: waUploadToServer,
|
|
1158
|
+
getEphemeralGroup: getEphemeralGroup,
|
|
1159
|
+
fetchPrivacySettings: fetchPrivacySettings,
|
|
1160
|
+
messageRetryManager: messageRetryManager,
|
|
1161
|
+
createParticipantNodes: createParticipantNodes,
|
|
1162
|
+
sendPeerDataOperationMessage: sendPeerDataOperationMessage,
|
|
1163
|
+
updateMemberLabel: updateMemberLabel,
|
|
1164
|
+
updateMediaMessage: async (message) => {
|
|
1165
|
+
const content = assertMediaContent(message.message);
|
|
1166
|
+
const mediaKey = content.mediaKey;
|
|
1167
|
+
const meId = authState.creds.me.id;
|
|
1168
|
+
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
|
|
1169
|
+
let error = undefined;
|
|
1170
|
+
await Promise.all([
|
|
1171
|
+
sendNode(node),
|
|
1172
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
1173
|
+
const result = update.find((c) => c.key.id === message.key.id);
|
|
1174
|
+
if (result) {
|
|
1175
|
+
if (result.error) {
|
|
1176
|
+
error = result.error;
|
|
1177
|
+
} else {
|
|
1178
|
+
try {
|
|
1179
|
+
const media = await decryptMediaRetryData(
|
|
1180
|
+
result.media,
|
|
1181
|
+
mediaKey,
|
|
1182
|
+
result.key.id
|
|
1183
|
+
);
|
|
1184
|
+
if (
|
|
1185
|
+
media.result !== proto.MediaRetryNotification.ResultType.SUCCESS
|
|
1186
|
+
) {
|
|
1187
|
+
const resultStr =
|
|
1188
|
+
proto.MediaRetryNotification.ResultType[media.result];
|
|
1189
|
+
throw new Boom(
|
|
1190
|
+
`Media re-upload failed by device (${resultStr})`,
|
|
1191
|
+
{
|
|
1192
|
+
data: media,
|
|
1193
|
+
statusCode:
|
|
1194
|
+
getStatusCodeForMediaRetry(media.result) || 404,
|
|
1195
|
+
}
|
|
1196
|
+
);
|
|
1197
|
+
}
|
|
1198
|
+
content.directPath = media.directPath;
|
|
1199
|
+
content.url = getUrlFromDirectPath(content.directPath);
|
|
1200
|
+
logger.debug(
|
|
1201
|
+
{ directPath: media.directPath, key: result.key },
|
|
1202
|
+
"media update successful"
|
|
1203
|
+
);
|
|
1204
|
+
} catch (err) {
|
|
1205
|
+
error = err;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return true;
|
|
1209
|
+
}
|
|
1210
|
+
}),
|
|
1211
|
+
]);
|
|
1212
|
+
if (error) {
|
|
1213
|
+
throw error;
|
|
1214
|
+
}
|
|
1215
|
+
ev.emit("messages.update", [
|
|
1216
|
+
{ key: message.key, update: { message: message.message } },
|
|
1217
|
+
]);
|
|
1218
|
+
return message;
|
|
1219
|
+
},
|
|
1220
|
+
sendStatusMentions: async (content, jids = []) => {
|
|
1221
|
+
const userJid = jidNormalizedUser(authState.creds.me.id);
|
|
1222
|
+
let allUsers = new Set();
|
|
1223
|
+
allUsers.add(userJid);
|
|
1224
|
+
for (const id of jids) {
|
|
1225
|
+
const isGroup = isJidGroup(id);
|
|
1226
|
+
const isPrivate = isPnUser(id);
|
|
1227
|
+
if (isGroup) {
|
|
1228
|
+
try {
|
|
1229
|
+
const metadata =
|
|
1230
|
+
(await cachedGroupMetadata(id)) || (await groupMetadata(id));
|
|
1231
|
+
const participants = metadata.participants.map((p) =>
|
|
1232
|
+
jidNormalizedUser(p.id)
|
|
1233
|
+
);
|
|
1234
|
+
participants.forEach((jid) => allUsers.add(jid));
|
|
1235
|
+
} catch (error) {
|
|
1236
|
+
logger.error(`Error getting metadata for group ${id}: ${error}`);
|
|
1237
|
+
}
|
|
1238
|
+
} else if (isPrivate) {
|
|
1239
|
+
allUsers.add(jidNormalizedUser(id));
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
const uniqueUsers = Array.from(allUsers);
|
|
1243
|
+
const getRandomHexColor = () =>
|
|
1244
|
+
"#" +
|
|
1245
|
+
Math.floor(Math.random() * 16777215)
|
|
1246
|
+
.toString(16)
|
|
1247
|
+
.padStart(6, "0");
|
|
1248
|
+
const isMedia = content.image || content.video || content.audio;
|
|
1249
|
+
const isAudio = !!content.audio;
|
|
1250
|
+
const messageContent = { ...content };
|
|
1251
|
+
if (isMedia && !isAudio) {
|
|
1252
|
+
if (messageContent.text) {
|
|
1253
|
+
messageContent.caption = messageContent.text;
|
|
1254
|
+
delete messageContent.text;
|
|
1255
|
+
}
|
|
1256
|
+
delete messageContent.ptt;
|
|
1257
|
+
delete messageContent.font;
|
|
1258
|
+
delete messageContent.backgroundColor;
|
|
1259
|
+
delete messageContent.textColor;
|
|
1260
|
+
}
|
|
1261
|
+
if (isAudio) {
|
|
1262
|
+
delete messageContent.text;
|
|
1263
|
+
delete messageContent.caption;
|
|
1264
|
+
delete messageContent.font;
|
|
1265
|
+
delete messageContent.textColor;
|
|
1266
|
+
}
|
|
1267
|
+
const font = !isMedia ? content.font || Math.floor(Math.random() * 9) : undefined;
|
|
1268
|
+
const textColor = !isMedia ? content.textColor || getRandomHexColor() : undefined;
|
|
1269
|
+
const backgroundColor =
|
|
1270
|
+
!isMedia || isAudio ? content.backgroundColor || getRandomHexColor() : undefined;
|
|
1271
|
+
const ptt = isAudio
|
|
1272
|
+
? typeof content.ptt === "boolean"
|
|
1273
|
+
? content.ptt
|
|
1274
|
+
: true
|
|
1275
|
+
: undefined;
|
|
1276
|
+
let msg;
|
|
1277
|
+
let mediaHandle;
|
|
1278
|
+
try {
|
|
1279
|
+
msg = await generateWAMessage(STORIES_JID, messageContent, {
|
|
1280
|
+
logger: logger,
|
|
1281
|
+
userJid: userJid,
|
|
1282
|
+
getUrlInfo: (text) =>
|
|
1283
|
+
getUrlInfo(text, {
|
|
1284
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1285
|
+
fetchOpts: { timeout: 3e3, ...(httpRequestOptions || {}) },
|
|
1286
|
+
logger: logger,
|
|
1287
|
+
uploadImage: generateHighQualityLinkPreview
|
|
1288
|
+
? waUploadToServer
|
|
1289
|
+
: undefined,
|
|
1290
|
+
}),
|
|
1291
|
+
upload: async (encFilePath, opts) => {
|
|
1292
|
+
const up = await waUploadToServer(encFilePath, { ...opts });
|
|
1293
|
+
mediaHandle = up.handle;
|
|
1294
|
+
return up;
|
|
1295
|
+
},
|
|
1296
|
+
mediaCache: config.mediaCache,
|
|
1297
|
+
options: config.options,
|
|
1298
|
+
font: font,
|
|
1299
|
+
textColor: textColor,
|
|
1300
|
+
backgroundColor: backgroundColor,
|
|
1301
|
+
ptt: ptt,
|
|
1302
|
+
});
|
|
1303
|
+
} catch (error) {
|
|
1304
|
+
logger.error(`Error generating message: ${error}`);
|
|
1305
|
+
throw error;
|
|
1306
|
+
}
|
|
1307
|
+
await relayMessage(STORIES_JID, msg.message, {
|
|
1308
|
+
messageId: msg.key.id,
|
|
1309
|
+
statusJidList: uniqueUsers,
|
|
1310
|
+
additionalNodes: [
|
|
1311
|
+
{
|
|
1312
|
+
tag: "meta",
|
|
1313
|
+
attrs: {},
|
|
1314
|
+
content: [
|
|
1315
|
+
{
|
|
1316
|
+
tag: "mentioned_users",
|
|
1317
|
+
attrs: {},
|
|
1318
|
+
content: jids.map((jid) => ({
|
|
1319
|
+
tag: "to",
|
|
1320
|
+
attrs: { jid: jidNormalizedUser(jid) },
|
|
1321
|
+
})),
|
|
1322
|
+
},
|
|
1323
|
+
],
|
|
1324
|
+
},
|
|
1325
|
+
],
|
|
1326
|
+
});
|
|
1327
|
+
for (const id of jids) {
|
|
1328
|
+
try {
|
|
1329
|
+
const normalizedId = jidNormalizedUser(id);
|
|
1330
|
+
const isPrivate = isPnUser(normalizedId);
|
|
1331
|
+
const type = isPrivate ? "statusMentionMessage" : "groupStatusMentionMessage";
|
|
1332
|
+
const protocolMessage = {
|
|
1333
|
+
[type]: {
|
|
1334
|
+
message: { protocolMessage: { key: msg.key, type: 25 } },
|
|
1335
|
+
},
|
|
1336
|
+
messageContextInfo: { messageSecret: randomBytes(32) },
|
|
1337
|
+
};
|
|
1338
|
+
const statusMsg = await generateWAMessageFromContent(
|
|
1339
|
+
normalizedId,
|
|
1340
|
+
protocolMessage,
|
|
1341
|
+
{}
|
|
1342
|
+
);
|
|
1343
|
+
await relayMessage(normalizedId, statusMsg.message, {
|
|
1344
|
+
additionalNodes: [
|
|
1345
|
+
{
|
|
1346
|
+
tag: "meta",
|
|
1347
|
+
attrs: isPrivate
|
|
1348
|
+
? { is_status_mention: "true" }
|
|
1349
|
+
: { is_group_status_mention: "true" },
|
|
1350
|
+
},
|
|
1351
|
+
],
|
|
1352
|
+
});
|
|
1353
|
+
await delay(2e3);
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
logger.error(`Error sending to ${id}: ${error}`);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
return msg;
|
|
1359
|
+
},
|
|
1360
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
1361
|
+
const userJid = authState.creds.me.id;
|
|
1362
|
+
const additionalAttributes = {};
|
|
1363
|
+
if (!options.ephemeralExpiration) {
|
|
1364
|
+
if (isJidGroup(jid)) {
|
|
1365
|
+
const expiration = await getEphemeralGroup(jid);
|
|
1366
|
+
options.ephemeralExpiration = expiration;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
if (
|
|
1370
|
+
typeof content === "object" &&
|
|
1371
|
+
"disappearingMessagesInChat" in content &&
|
|
1372
|
+
typeof content["disappearingMessagesInChat"] !== "undefined" &&
|
|
1373
|
+
isJidGroup(jid)
|
|
1374
|
+
) {
|
|
1375
|
+
const { disappearingMessagesInChat: disappearingMessagesInChat } = content;
|
|
1376
|
+
const value =
|
|
1377
|
+
typeof disappearingMessagesInChat === "boolean"
|
|
1378
|
+
? disappearingMessagesInChat
|
|
1379
|
+
? WA_DEFAULT_EPHEMERAL
|
|
1380
|
+
: 0
|
|
1381
|
+
: disappearingMessagesInChat;
|
|
1382
|
+
await groupToggleEphemeral(jid, value);
|
|
1383
|
+
} else if (typeof content === "object" && "album" in content && content.album) {
|
|
1384
|
+
const albumMsg = await prepareAlbumMessageContent(jid, content.album, {
|
|
1385
|
+
conn: {
|
|
1386
|
+
relayMessage: relayMessage,
|
|
1387
|
+
waUploadToServer: waUploadToServer,
|
|
1388
|
+
},
|
|
1389
|
+
userJid: userJid,
|
|
1390
|
+
...options,
|
|
1391
|
+
});
|
|
1392
|
+
for (const media of albumMsg) {
|
|
1393
|
+
await delay(options.delay || 500);
|
|
1394
|
+
await relayMessage(jid, media.message, {
|
|
1395
|
+
messageId: media.key.id,
|
|
1396
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1397
|
+
additionalAttributes: additionalAttributes,
|
|
1398
|
+
statusJidList: options.statusJidList,
|
|
1399
|
+
additionalNodes: options.additionalNodes,
|
|
1400
|
+
AI: options.ai,
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
return albumMsg;
|
|
1404
|
+
} else if (richContent.detectType(content)) {
|
|
1405
|
+
// Added for AsepXyz Baileys (ported from PouCode)
|
|
1406
|
+
const type = richContent.detectType(content);
|
|
1407
|
+
switch (type) {
|
|
1408
|
+
case "PAYMENT": {
|
|
1409
|
+
const msg = await generateWAMessageFromContent(jid, await richContent.handlePayment(content, options.quoted), { userJid, ...options });
|
|
1410
|
+
await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalAttributes, ...options });
|
|
1411
|
+
return msg;
|
|
1412
|
+
}
|
|
1413
|
+
case "PRODUCT": {
|
|
1414
|
+
const msg = await generateWAMessageFromContent(jid, await richContent.handleProduct(content, jid, options.quoted), { userJid, ...options });
|
|
1415
|
+
await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalAttributes, ...options });
|
|
1416
|
+
return msg;
|
|
1417
|
+
}
|
|
1418
|
+
case "EVENT":
|
|
1419
|
+
return await richContent.handleEvent(content, jid, options.quoted);
|
|
1420
|
+
case "POLL_RESULT":
|
|
1421
|
+
return await richContent.handlePollResult(content, jid, options.quoted);
|
|
1422
|
+
case "ORDER":
|
|
1423
|
+
return await richContent.handleOrderMessage(content, jid, options.quoted);
|
|
1424
|
+
case "GROUP_STATUS":
|
|
1425
|
+
return await richContent.handleGroupStory(content, jid, options.quoted);
|
|
1426
|
+
case "GROUP_LABEL":
|
|
1427
|
+
return await richContent.handleGbLabel(content, jid);
|
|
1428
|
+
default:
|
|
1429
|
+
break;
|
|
1430
|
+
}
|
|
1431
|
+
return;
|
|
1432
|
+
} else {
|
|
1433
|
+
let mediaHandle;
|
|
1434
|
+
const fullMsg = await generateWAMessage(jid, content, {
|
|
1435
|
+
logger: logger,
|
|
1436
|
+
userJid: userJid,
|
|
1437
|
+
getUrlInfo: (text) =>
|
|
1438
|
+
getUrlInfo(text, {
|
|
1439
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1440
|
+
fetchOpts: { timeout: 3e3, ...(httpRequestOptions || {}) },
|
|
1441
|
+
logger: logger,
|
|
1442
|
+
uploadImage: generateHighQualityLinkPreview
|
|
1443
|
+
? waUploadToServer
|
|
1444
|
+
: undefined,
|
|
1445
|
+
}),
|
|
1446
|
+
getProfilePicUrl: profilePictureUrl,
|
|
1447
|
+
getCallLink: createCallLink,
|
|
1448
|
+
upload: async (encFilePath, opts) => {
|
|
1449
|
+
const up = await waUploadToServer(encFilePath, {
|
|
1450
|
+
...opts,
|
|
1451
|
+
newsletter: isJidNewsletter(jid),
|
|
1452
|
+
});
|
|
1453
|
+
mediaHandle = up.handle;
|
|
1454
|
+
return up;
|
|
1455
|
+
},
|
|
1456
|
+
mediaCache: config.mediaCache,
|
|
1457
|
+
options: config.options,
|
|
1458
|
+
messageId: generateMessageID(userJid),
|
|
1459
|
+
...options,
|
|
1460
|
+
});
|
|
1461
|
+
const isPin = "pin" in content && !!content.pin;
|
|
1462
|
+
const isEdit = "edit" in content && !!content.edit;
|
|
1463
|
+
const isDelete = "delete" in content && !!content.delete;
|
|
1464
|
+
const isKeep = "keep" in content && !!content.keep && content.keep?.type === 2;
|
|
1465
|
+
if (isDelete || isKeep) {
|
|
1466
|
+
if (
|
|
1467
|
+
(isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) ||
|
|
1468
|
+
isJidNewsletter(jid)
|
|
1469
|
+
) {
|
|
1470
|
+
additionalAttributes.edit = "8";
|
|
1471
|
+
} else {
|
|
1472
|
+
additionalAttributes.edit = "7";
|
|
1473
|
+
}
|
|
1474
|
+
} else if (isEdit) {
|
|
1475
|
+
additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
|
|
1476
|
+
} else if (isPin) {
|
|
1477
|
+
additionalAttributes.edit = "2";
|
|
1478
|
+
}
|
|
1479
|
+
if (mediaHandle) {
|
|
1480
|
+
additionalAttributes["media_id"] = mediaHandle;
|
|
1481
|
+
}
|
|
1482
|
+
if ("cachedGroupMetadata" in options) {
|
|
1483
|
+
console.warn(
|
|
1484
|
+
"cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config."
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
await relayMessage(jid, fullMsg.message, {
|
|
1488
|
+
messageId: fullMsg.key.id,
|
|
1489
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1490
|
+
additionalAttributes: additionalAttributes,
|
|
1491
|
+
statusJidList: options.statusJidList,
|
|
1492
|
+
additionalNodes: options.additionalNodes,
|
|
1493
|
+
AI: options.ai,
|
|
1494
|
+
});
|
|
1495
|
+
if (config.emitOwnEvents) {
|
|
1496
|
+
process.nextTick(async () => {
|
|
1497
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, "append"));
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
return fullMsg;
|
|
1501
|
+
}
|
|
1502
|
+
},
|
|
1503
|
+
};
|
|
1504
|
+
};
|
|
1505
|
+
module.exports = { makeMessagesSocket: makeMessagesSocket };
|