@genuxofficial/baileys 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +3344 -0
- package/WAProto/index.d.ts +37016 -0
- package/WAProto/index.js +101044 -0
- package/WASignalGroup/GroupProtocol.js +1697 -0
- package/WASignalGroup/ciphertext_message.js +16 -0
- package/WASignalGroup/group_cipher.js +120 -0
- package/WASignalGroup/group_session_builder.js +46 -0
- package/WASignalGroup/index.js +5 -0
- package/WASignalGroup/keyhelper.js +21 -0
- package/WASignalGroup/protobufs.js +3 -0
- package/WASignalGroup/queue_job.js +69 -0
- package/WASignalGroup/sender_chain_key.js +50 -0
- package/WASignalGroup/sender_key_distribution_message.js +78 -0
- package/WASignalGroup/sender_key_message.js +92 -0
- package/WASignalGroup/sender_key_name.js +70 -0
- package/WASignalGroup/sender_key_record.js +56 -0
- package/WASignalGroup/sender_key_state.js +129 -0
- package/WASignalGroup/sender_message_key.js +39 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +53 -0
- package/lib/Defaults/index.js +106 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +152 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.d.ts +17 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/business.d.ts +149 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.d.ts +85 -0
- package/lib/Socket/chats.js +850 -0
- package/lib/Socket/groups.d.ts +124 -0
- package/lib/Socket/groups.js +314 -0
- package/lib/Socket/index.d.ts +149 -0
- package/lib/Socket/index.js +10 -0
- package/lib/Socket/messages-recv.d.ts +136 -0
- package/lib/Socket/messages-recv.js +912 -0
- package/lib/Socket/messages-send.d.ts +130 -0
- package/lib/Socket/messages-send.js +673 -0
- package/lib/Socket/socket.d.ts +45 -0
- package/lib/Socket/socket.js +622 -0
- package/lib/Socket/usync.d.ts +38 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +420 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.d.ts +105 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +108 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.d.ts +19 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +172 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +56 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +46 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.d.ts +271 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +118 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +63 -0
- package/lib/Types/index.js +41 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +200 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.d.ts +72 -0
- package/lib/Utils/chat-utils.js +745 -0
- package/lib/Utils/crypto.d.ts +42 -0
- package/lib/Utils/crypto.js +181 -0
- package/lib/Utils/decode-wa-message.d.ts +36 -0
- package/lib/Utils/decode-wa-message.js +205 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +520 -0
- package/lib/Utils/generics.d.ts +94 -0
- package/lib/Utils/generics.js +433 -0
- package/lib/Utils/history.d.ts +19 -0
- package/lib/Utils/history.js +94 -0
- package/lib/Utils/index.d.ts +17 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +116 -0
- package/lib/Utils/logger.d.ts +11 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/messages-media.d.ts +108 -0
- package/lib/Utils/messages-media.js +667 -0
- package/lib/Utils/messages.d.ts +78 -0
- package/lib/Utils/messages.js +760 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/process-message.d.ts +42 -0
- package/lib/Utils/process-message.js +373 -0
- package/lib/Utils/signal.d.ts +33 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.js +94 -0
- package/lib/Utils/validate-connection.d.ts +10 -0
- package/lib/Utils/validate-connection.js +175 -0
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.d.ts +8 -0
- package/lib/WABinary/decode.js +254 -0
- package/lib/WABinary/encode.d.ts +4 -0
- package/lib/WABinary/encode.js +234 -0
- package/lib/WABinary/generic-utils.d.ts +16 -0
- package/lib/WABinary/generic-utils.js +110 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +31 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +18 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.d.ts +39 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.d.ts +4 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +26 -0
- package/lib/WAUSync/USyncQuery.js +79 -0
- package/lib/WAUSync/USyncUser.d.ts +10 -0
- package/lib/WAUSync/USyncUser.js +22 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +31 -0
- package/package.json +104 -0
@@ -0,0 +1,912 @@
|
|
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.makeMessagesRecvSocket = void 0;
|
7
|
+
const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
|
8
|
+
const boom_1 = require("@hapi/boom");
|
9
|
+
const crypto_1 = require("crypto");
|
10
|
+
const WAProto_1 = require("../../WAProto");
|
11
|
+
const Defaults_1 = require("../Defaults");
|
12
|
+
const Types_1 = require("../Types");
|
13
|
+
const Utils_1 = require("../Utils");
|
14
|
+
const make_mutex_1 = require("../Utils/make-mutex");
|
15
|
+
const WABinary_1 = require("../WABinary");
|
16
|
+
const groups_1 = require("./groups");
|
17
|
+
const messages_send_1 = require("./messages-send");
|
18
|
+
const makeMessagesRecvSocket = (config) => {
|
19
|
+
const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
|
20
|
+
const sock = (0, messages_send_1.makeMessagesSocket)(config);
|
21
|
+
const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, } = sock;
|
22
|
+
/** this mutex ensures that each retryRequest will wait for the previous one to finish */
|
23
|
+
const retryMutex = (0, make_mutex_1.makeMutex)();
|
24
|
+
const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
|
25
|
+
stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
|
26
|
+
useClones: false
|
27
|
+
});
|
28
|
+
const callOfferCache = config.callOfferCache || new node_cache_1.default({
|
29
|
+
stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
|
30
|
+
useClones: false
|
31
|
+
});
|
32
|
+
const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
|
33
|
+
stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
|
34
|
+
useClones: false
|
35
|
+
});
|
36
|
+
let sendActiveReceipts = false;
|
37
|
+
const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
|
38
|
+
const stanza = {
|
39
|
+
tag: 'ack',
|
40
|
+
attrs: {
|
41
|
+
id: attrs.id,
|
42
|
+
to: attrs.from,
|
43
|
+
class: tag
|
44
|
+
}
|
45
|
+
};
|
46
|
+
if (!!errorCode) {
|
47
|
+
stanza.attrs.error = errorCode.toString();
|
48
|
+
}
|
49
|
+
if (!!attrs.participant) {
|
50
|
+
stanza.attrs.participant = attrs.participant;
|
51
|
+
}
|
52
|
+
if (!!attrs.recipient) {
|
53
|
+
stanza.attrs.recipient = attrs.recipient;
|
54
|
+
}
|
55
|
+
if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
|
56
|
+
stanza.attrs.type = attrs.type;
|
57
|
+
}
|
58
|
+
if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
|
59
|
+
stanza.attrs.from = authState.creds.me.id;
|
60
|
+
}
|
61
|
+
logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
|
62
|
+
await sendNode(stanza);
|
63
|
+
};
|
64
|
+
const rejectCall = async (callId, callFrom) => {
|
65
|
+
const stanza = ({
|
66
|
+
tag: 'call',
|
67
|
+
attrs: {
|
68
|
+
from: authState.creds.me.id,
|
69
|
+
to: callFrom,
|
70
|
+
},
|
71
|
+
content: [{
|
72
|
+
tag: 'reject',
|
73
|
+
attrs: {
|
74
|
+
'call-id': callId,
|
75
|
+
'call-creator': callFrom,
|
76
|
+
count: '0',
|
77
|
+
},
|
78
|
+
content: undefined,
|
79
|
+
}],
|
80
|
+
});
|
81
|
+
await query(stanza);
|
82
|
+
};
|
83
|
+
const sendRetryRequest = async (node, forceIncludeKeys = false) => {
|
84
|
+
const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
|
85
|
+
const { key: msgKey } = fullMessage;
|
86
|
+
const msgId = msgKey.id;
|
87
|
+
const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
|
88
|
+
let retryCount = msgRetryCache.get(key) || 0;
|
89
|
+
if (retryCount >= maxMsgRetryCount) {
|
90
|
+
logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
|
91
|
+
msgRetryCache.del(key);
|
92
|
+
return;
|
93
|
+
}
|
94
|
+
retryCount += 1;
|
95
|
+
msgRetryCache.set(key, retryCount);
|
96
|
+
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
|
97
|
+
if (retryCount === 1) {
|
98
|
+
//request a resend via phone
|
99
|
+
const msgId = await requestPlaceholderResend(msgKey);
|
100
|
+
logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
|
101
|
+
}
|
102
|
+
const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
|
103
|
+
await authState.keys.transaction(async () => {
|
104
|
+
const receipt = {
|
105
|
+
tag: 'receipt',
|
106
|
+
attrs: {
|
107
|
+
id: msgId,
|
108
|
+
type: 'retry',
|
109
|
+
to: node.attrs.from
|
110
|
+
},
|
111
|
+
content: [
|
112
|
+
{
|
113
|
+
tag: 'retry',
|
114
|
+
attrs: {
|
115
|
+
count: retryCount.toString(),
|
116
|
+
id: node.attrs.id,
|
117
|
+
t: node.attrs.t,
|
118
|
+
v: '1'
|
119
|
+
}
|
120
|
+
},
|
121
|
+
{
|
122
|
+
tag: 'registration',
|
123
|
+
attrs: {},
|
124
|
+
content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
|
125
|
+
}
|
126
|
+
]
|
127
|
+
};
|
128
|
+
if (node.attrs.recipient) {
|
129
|
+
receipt.attrs.recipient = node.attrs.recipient;
|
130
|
+
}
|
131
|
+
if (node.attrs.participant) {
|
132
|
+
receipt.attrs.participant = node.attrs.participant;
|
133
|
+
}
|
134
|
+
if (retryCount > 1 || forceIncludeKeys) {
|
135
|
+
const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
|
136
|
+
const [keyId] = Object.keys(preKeys);
|
137
|
+
const key = preKeys[+keyId];
|
138
|
+
const content = receipt.content;
|
139
|
+
content.push({
|
140
|
+
tag: 'keys',
|
141
|
+
attrs: {},
|
142
|
+
content: [
|
143
|
+
{ tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
|
144
|
+
{ tag: 'identity', attrs: {}, content: identityKey.public },
|
145
|
+
(0, Utils_1.xmppPreKey)(key, +keyId),
|
146
|
+
(0, Utils_1.xmppSignedPreKey)(signedPreKey),
|
147
|
+
{ tag: 'device-identity', attrs: {}, content: deviceIdentity }
|
148
|
+
]
|
149
|
+
});
|
150
|
+
ev.emit('creds.update', update);
|
151
|
+
}
|
152
|
+
await sendNode(receipt);
|
153
|
+
logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
|
154
|
+
});
|
155
|
+
};
|
156
|
+
const handleEncryptNotification = async (node) => {
|
157
|
+
const from = node.attrs.from;
|
158
|
+
if (from === WABinary_1.S_WHATSAPP_NET) {
|
159
|
+
const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
|
160
|
+
const count = +countChild.attrs.value;
|
161
|
+
const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
|
162
|
+
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
|
163
|
+
if (shouldUploadMorePreKeys) {
|
164
|
+
await uploadPreKeys();
|
165
|
+
}
|
166
|
+
}
|
167
|
+
else {
|
168
|
+
const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
|
169
|
+
if (identityNode) {
|
170
|
+
logger.info({ jid: from }, 'identity changed');
|
171
|
+
// not handling right now
|
172
|
+
// signal will override new identity anyway
|
173
|
+
}
|
174
|
+
else {
|
175
|
+
logger.info({ node }, 'unknown encrypt notification');
|
176
|
+
}
|
177
|
+
}
|
178
|
+
};
|
179
|
+
const handleGroupNotification = (participant, child, msg) => {
|
180
|
+
var _a, _b, _c, _d;
|
181
|
+
const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
|
182
|
+
switch (child === null || child === void 0 ? void 0 : child.tag) {
|
183
|
+
case 'create':
|
184
|
+
const metadata = (0, groups_1.extractGroupMetadata)(child);
|
185
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
|
186
|
+
msg.messageStubParameters = [metadata.subject];
|
187
|
+
msg.key = { participant: metadata.owner };
|
188
|
+
ev.emit('chats.upsert', [{
|
189
|
+
id: metadata.id,
|
190
|
+
name: metadata.subject,
|
191
|
+
conversationTimestamp: metadata.creation,
|
192
|
+
}]);
|
193
|
+
ev.emit('groups.upsert', [{
|
194
|
+
...metadata,
|
195
|
+
author: participant
|
196
|
+
}]);
|
197
|
+
break;
|
198
|
+
case 'ephemeral':
|
199
|
+
case 'not_ephemeral':
|
200
|
+
msg.message = {
|
201
|
+
protocolMessage: {
|
202
|
+
type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
203
|
+
ephemeralExpiration: +(child.attrs.expiration || 0)
|
204
|
+
}
|
205
|
+
};
|
206
|
+
break;
|
207
|
+
case 'modify':
|
208
|
+
const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
|
209
|
+
msg.messageStubParameters = oldNumber || [];
|
210
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
|
211
|
+
break;
|
212
|
+
case 'promote':
|
213
|
+
case 'demote':
|
214
|
+
case 'remove':
|
215
|
+
case 'add':
|
216
|
+
case 'leave':
|
217
|
+
const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
|
218
|
+
msg.messageStubType = Types_1.WAMessageStubType[stubType];
|
219
|
+
const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
|
220
|
+
if (participants.length === 1 &&
|
221
|
+
// if recv. "remove" message and sender removed themselves
|
222
|
+
// mark as left
|
223
|
+
(0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
|
224
|
+
child.tag === 'remove') {
|
225
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
|
226
|
+
}
|
227
|
+
msg.messageStubParameters = participants;
|
228
|
+
break;
|
229
|
+
case 'subject':
|
230
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
|
231
|
+
msg.messageStubParameters = [child.attrs.subject];
|
232
|
+
break;
|
233
|
+
case 'description':
|
234
|
+
const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
|
235
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
|
236
|
+
msg.messageStubParameters = description ? [description] : undefined;
|
237
|
+
break;
|
238
|
+
case 'announcement':
|
239
|
+
case 'not_announcement':
|
240
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
|
241
|
+
msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
|
242
|
+
break;
|
243
|
+
case 'locked':
|
244
|
+
case 'unlocked':
|
245
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
|
246
|
+
msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
|
247
|
+
break;
|
248
|
+
case 'invite':
|
249
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
|
250
|
+
msg.messageStubParameters = [child.attrs.code];
|
251
|
+
break;
|
252
|
+
case 'member_add_mode':
|
253
|
+
const addMode = child.content;
|
254
|
+
if (addMode) {
|
255
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
|
256
|
+
msg.messageStubParameters = [addMode.toString()];
|
257
|
+
}
|
258
|
+
break;
|
259
|
+
case 'membership_approval_mode':
|
260
|
+
const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
|
261
|
+
if (approvalMode) {
|
262
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
|
263
|
+
msg.messageStubParameters = [approvalMode.attrs.state];
|
264
|
+
}
|
265
|
+
break;
|
266
|
+
case 'created_membership_requests':
|
267
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
268
|
+
msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
|
269
|
+
break;
|
270
|
+
case 'revoked_membership_requests':
|
271
|
+
const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
|
272
|
+
msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
273
|
+
msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
|
274
|
+
break;
|
275
|
+
}
|
276
|
+
};
|
277
|
+
const processNotification = async (node) => {
|
278
|
+
var _a, _b, _c;
|
279
|
+
const result = {};
|
280
|
+
const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
|
281
|
+
const nodeType = node.attrs.type;
|
282
|
+
const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
|
283
|
+
switch (nodeType) {
|
284
|
+
case 'privacy_token':
|
285
|
+
const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
|
286
|
+
for (const { attrs, content } of tokenList) {
|
287
|
+
const jid = attrs.jid;
|
288
|
+
ev.emit('chats.update', [
|
289
|
+
{
|
290
|
+
id: jid,
|
291
|
+
tcToken: content
|
292
|
+
}
|
293
|
+
]);
|
294
|
+
logger.debug({ jid }, 'got privacy token update');
|
295
|
+
}
|
296
|
+
break;
|
297
|
+
case 'w:gp2':
|
298
|
+
handleGroupNotification(node.attrs.participant, child, result);
|
299
|
+
break;
|
300
|
+
case 'mediaretry':
|
301
|
+
const event = (0, Utils_1.decodeMediaRetryNode)(node);
|
302
|
+
ev.emit('messages.media-update', [event]);
|
303
|
+
break;
|
304
|
+
case 'encrypt':
|
305
|
+
await handleEncryptNotification(node);
|
306
|
+
break;
|
307
|
+
case 'devices':
|
308
|
+
const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
|
309
|
+
if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
|
310
|
+
const deviceJids = devices.map(d => d.attrs.jid);
|
311
|
+
logger.info({ deviceJids }, 'got my own devices');
|
312
|
+
}
|
313
|
+
break;
|
314
|
+
case 'server_sync':
|
315
|
+
const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
|
316
|
+
if (update) {
|
317
|
+
const name = update.attrs.name;
|
318
|
+
await resyncAppState([name], false);
|
319
|
+
}
|
320
|
+
break;
|
321
|
+
case 'picture':
|
322
|
+
const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
|
323
|
+
const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
|
324
|
+
ev.emit('contacts.update', [{
|
325
|
+
id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
|
326
|
+
imgUrl: setPicture ? 'changed' : 'removed'
|
327
|
+
}]);
|
328
|
+
if ((0, WABinary_1.isJidGroup)(from)) {
|
329
|
+
const node = setPicture || delPicture;
|
330
|
+
result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
|
331
|
+
if (setPicture) {
|
332
|
+
result.messageStubParameters = [setPicture.attrs.id];
|
333
|
+
}
|
334
|
+
result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
|
335
|
+
result.key = {
|
336
|
+
...result.key || {},
|
337
|
+
participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
|
338
|
+
};
|
339
|
+
}
|
340
|
+
break;
|
341
|
+
case 'account_sync':
|
342
|
+
if (child.tag === 'disappearing_mode') {
|
343
|
+
const newDuration = +child.attrs.duration;
|
344
|
+
const timestamp = +child.attrs.t;
|
345
|
+
logger.info({ newDuration }, 'updated account disappearing mode');
|
346
|
+
ev.emit('creds.update', {
|
347
|
+
accountSettings: {
|
348
|
+
...authState.creds.accountSettings,
|
349
|
+
defaultDisappearingMode: {
|
350
|
+
ephemeralExpiration: newDuration,
|
351
|
+
ephemeralSettingTimestamp: timestamp,
|
352
|
+
},
|
353
|
+
}
|
354
|
+
});
|
355
|
+
}
|
356
|
+
else if (child.tag === 'blocklist') {
|
357
|
+
const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
|
358
|
+
for (const { attrs } of blocklists) {
|
359
|
+
const blocklist = [attrs.jid];
|
360
|
+
const type = (attrs.action === 'block') ? 'add' : 'remove';
|
361
|
+
ev.emit('blocklist.update', { blocklist, type });
|
362
|
+
}
|
363
|
+
}
|
364
|
+
break;
|
365
|
+
case 'link_code_companion_reg':
|
366
|
+
const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
|
367
|
+
const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
|
368
|
+
const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
|
369
|
+
const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
|
370
|
+
const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
|
371
|
+
const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
|
372
|
+
const random = (0, crypto_1.randomBytes)(32);
|
373
|
+
const linkCodeSalt = (0, crypto_1.randomBytes)(32);
|
374
|
+
const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
|
375
|
+
salt: linkCodeSalt,
|
376
|
+
info: 'link_code_pairing_key_bundle_encryption_key'
|
377
|
+
});
|
378
|
+
const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
|
379
|
+
const encryptIv = (0, crypto_1.randomBytes)(12);
|
380
|
+
const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
|
381
|
+
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
|
382
|
+
const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
|
383
|
+
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
|
384
|
+
authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
|
385
|
+
await query({
|
386
|
+
tag: 'iq',
|
387
|
+
attrs: {
|
388
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
389
|
+
type: 'set',
|
390
|
+
id: sock.generateMessageTag(),
|
391
|
+
xmlns: 'md'
|
392
|
+
},
|
393
|
+
content: [
|
394
|
+
{
|
395
|
+
tag: 'link_code_companion_reg',
|
396
|
+
attrs: {
|
397
|
+
jid: authState.creds.me.id,
|
398
|
+
stage: 'companion_finish',
|
399
|
+
},
|
400
|
+
content: [
|
401
|
+
{
|
402
|
+
tag: 'link_code_pairing_wrapped_key_bundle',
|
403
|
+
attrs: {},
|
404
|
+
content: encryptedPayload
|
405
|
+
},
|
406
|
+
{
|
407
|
+
tag: 'companion_identity_public',
|
408
|
+
attrs: {},
|
409
|
+
content: authState.creds.signedIdentityKey.public
|
410
|
+
},
|
411
|
+
{
|
412
|
+
tag: 'link_code_pairing_ref',
|
413
|
+
attrs: {},
|
414
|
+
content: ref
|
415
|
+
}
|
416
|
+
]
|
417
|
+
}
|
418
|
+
]
|
419
|
+
});
|
420
|
+
authState.creds.registered = true;
|
421
|
+
ev.emit('creds.update', authState.creds);
|
422
|
+
}
|
423
|
+
if (Object.keys(result).length) {
|
424
|
+
return result;
|
425
|
+
}
|
426
|
+
};
|
427
|
+
async function decipherLinkPublicKey(data) {
|
428
|
+
const buffer = toRequiredBuffer(data);
|
429
|
+
const salt = buffer.slice(0, 32);
|
430
|
+
const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
|
431
|
+
const iv = buffer.slice(32, 48);
|
432
|
+
const payload = buffer.slice(48, 80);
|
433
|
+
return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
|
434
|
+
}
|
435
|
+
function toRequiredBuffer(data) {
|
436
|
+
if (data === undefined) {
|
437
|
+
throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
|
438
|
+
}
|
439
|
+
return data instanceof Buffer ? data : Buffer.from(data);
|
440
|
+
}
|
441
|
+
const willSendMessageAgain = (id, participant) => {
|
442
|
+
const key = `${id}:${participant}`;
|
443
|
+
const retryCount = msgRetryCache.get(key) || 0;
|
444
|
+
return retryCount < maxMsgRetryCount;
|
445
|
+
};
|
446
|
+
const updateSendMessageAgainCount = (id, participant) => {
|
447
|
+
const key = `${id}:${participant}`;
|
448
|
+
const newValue = (msgRetryCache.get(key) || 0) + 1;
|
449
|
+
msgRetryCache.set(key, newValue);
|
450
|
+
};
|
451
|
+
const sendMessagesAgain = async (key, ids, retryNode) => {
|
452
|
+
var _a;
|
453
|
+
const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
|
454
|
+
const remoteJid = key.remoteJid;
|
455
|
+
const participant = key.participant || remoteJid;
|
456
|
+
// if it's the primary jid sending the request
|
457
|
+
// just re-send the message to everyone
|
458
|
+
// prevents the first message decryption failure
|
459
|
+
const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
|
460
|
+
await assertSessions([participant], true);
|
461
|
+
if ((0, WABinary_1.isJidGroup)(remoteJid)) {
|
462
|
+
await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
|
463
|
+
}
|
464
|
+
logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
|
465
|
+
for (const [i, msg] of msgs.entries()) {
|
466
|
+
if (msg) {
|
467
|
+
updateSendMessageAgainCount(ids[i], participant);
|
468
|
+
const msgRelayOpts = { messageId: ids[i] };
|
469
|
+
if (sendToAll) {
|
470
|
+
msgRelayOpts.useUserDevicesCache = false;
|
471
|
+
}
|
472
|
+
else {
|
473
|
+
msgRelayOpts.participant = {
|
474
|
+
jid: participant,
|
475
|
+
count: +retryNode.attrs.count
|
476
|
+
};
|
477
|
+
}
|
478
|
+
await relayMessage(key.remoteJid, msg, msgRelayOpts);
|
479
|
+
}
|
480
|
+
else {
|
481
|
+
logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
|
482
|
+
}
|
483
|
+
}
|
484
|
+
};
|
485
|
+
const handleReceipt = async (node) => {
|
486
|
+
var _a, _b;
|
487
|
+
const { attrs, content } = node;
|
488
|
+
const isLid = attrs.from.includes('lid');
|
489
|
+
const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, isLid ? (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.lid : (_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
|
490
|
+
const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
|
491
|
+
const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
|
492
|
+
const key = {
|
493
|
+
remoteJid,
|
494
|
+
id: '',
|
495
|
+
fromMe,
|
496
|
+
participant: attrs.participant
|
497
|
+
};
|
498
|
+
if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
|
499
|
+
logger.debug({ remoteJid }, 'ignoring receipt from jid');
|
500
|
+
await sendMessageAck(node);
|
501
|
+
return;
|
502
|
+
}
|
503
|
+
const ids = [attrs.id];
|
504
|
+
if (Array.isArray(content)) {
|
505
|
+
const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
|
506
|
+
ids.push(...items.map(i => i.attrs.id));
|
507
|
+
}
|
508
|
+
try {
|
509
|
+
await Promise.all([
|
510
|
+
processingMutex.mutex(async () => {
|
511
|
+
const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
|
512
|
+
if (typeof status !== 'undefined' &&
|
513
|
+
(
|
514
|
+
// basically, we only want to know when a message from us has been delivered to/read by the other person
|
515
|
+
// or another device of ours has read some messages
|
516
|
+
status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
|
517
|
+
!isNodeFromMe)) {
|
518
|
+
if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
|
519
|
+
if (attrs.participant) {
|
520
|
+
const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
|
521
|
+
ev.emit('message-receipt.update', ids.map(id => ({
|
522
|
+
key: { ...key, id },
|
523
|
+
receipt: {
|
524
|
+
userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
|
525
|
+
[updateKey]: +attrs.t
|
526
|
+
}
|
527
|
+
})));
|
528
|
+
}
|
529
|
+
}
|
530
|
+
else {
|
531
|
+
ev.emit('messages.update', ids.map(id => ({
|
532
|
+
key: { ...key, id },
|
533
|
+
update: { status }
|
534
|
+
})));
|
535
|
+
}
|
536
|
+
}
|
537
|
+
if (attrs.type === 'retry') {
|
538
|
+
// correctly set who is asking for the retry
|
539
|
+
key.participant = key.participant || attrs.from;
|
540
|
+
const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
|
541
|
+
if (willSendMessageAgain(ids[0], key.participant)) {
|
542
|
+
if (key.fromMe) {
|
543
|
+
try {
|
544
|
+
logger.debug({ attrs, key }, 'recv retry request');
|
545
|
+
await sendMessagesAgain(key, ids, retryNode);
|
546
|
+
}
|
547
|
+
catch (error) {
|
548
|
+
logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
|
549
|
+
}
|
550
|
+
}
|
551
|
+
else {
|
552
|
+
logger.info({ attrs, key }, 'recv retry for not fromMe message');
|
553
|
+
}
|
554
|
+
}
|
555
|
+
else {
|
556
|
+
logger.info({ attrs, key }, 'will not send message again, as sent too many times');
|
557
|
+
}
|
558
|
+
}
|
559
|
+
})
|
560
|
+
]);
|
561
|
+
}
|
562
|
+
finally {
|
563
|
+
await sendMessageAck(node);
|
564
|
+
}
|
565
|
+
};
|
566
|
+
const handleNotification = async (node) => {
|
567
|
+
const remoteJid = node.attrs.from;
|
568
|
+
if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
|
569
|
+
logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
|
570
|
+
await sendMessageAck(node);
|
571
|
+
return;
|
572
|
+
}
|
573
|
+
try {
|
574
|
+
await Promise.all([
|
575
|
+
processingMutex.mutex(async () => {
|
576
|
+
var _a;
|
577
|
+
const msg = await processNotification(node);
|
578
|
+
if (msg) {
|
579
|
+
const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
|
580
|
+
msg.key = {
|
581
|
+
remoteJid,
|
582
|
+
fromMe,
|
583
|
+
participant: node.attrs.participant,
|
584
|
+
id: node.attrs.id,
|
585
|
+
...(msg.key || {})
|
586
|
+
};
|
587
|
+
(_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
|
588
|
+
msg.messageTimestamp = +node.attrs.t;
|
589
|
+
const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
|
590
|
+
await upsertMessage(fullMsg, 'append');
|
591
|
+
}
|
592
|
+
})
|
593
|
+
]);
|
594
|
+
}
|
595
|
+
finally {
|
596
|
+
await sendMessageAck(node);
|
597
|
+
}
|
598
|
+
};
|
599
|
+
const handleMessage = async (node) => {
|
600
|
+
var _a, _b, _c;
|
601
|
+
if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
|
602
|
+
logger.debug({ key: node.attrs.key }, 'ignored message');
|
603
|
+
await sendMessageAck(node);
|
604
|
+
return;
|
605
|
+
}
|
606
|
+
let response;
|
607
|
+
if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !(0, WABinary_1.getBinaryNodeChild)(node, 'enc')) {
|
608
|
+
await sendMessageAck(node);
|
609
|
+
const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
|
610
|
+
response = await requestPlaceholderResend(key);
|
611
|
+
if (response === 'RESOLVED') {
|
612
|
+
return;
|
613
|
+
}
|
614
|
+
logger.debug('received unavailable message, acked and requested resend from phone');
|
615
|
+
}
|
616
|
+
else {
|
617
|
+
if (placeholderResendCache.get(node.attrs.id)) {
|
618
|
+
placeholderResendCache.del(node.attrs.id);
|
619
|
+
}
|
620
|
+
}
|
621
|
+
const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
|
622
|
+
if (response && ((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
|
623
|
+
msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
|
624
|
+
}
|
625
|
+
if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
|
626
|
+
ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
|
627
|
+
}
|
628
|
+
try {
|
629
|
+
await Promise.all([
|
630
|
+
processingMutex.mutex(async () => {
|
631
|
+
var _a;
|
632
|
+
await decrypt();
|
633
|
+
// message failed to decrypt
|
634
|
+
if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
|
635
|
+
if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
|
636
|
+
return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
|
637
|
+
}
|
638
|
+
retryMutex.mutex(async () => {
|
639
|
+
if (ws.isOpen) {
|
640
|
+
if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
|
641
|
+
return;
|
642
|
+
}
|
643
|
+
const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
|
644
|
+
await sendRetryRequest(node, !encNode);
|
645
|
+
if (retryRequestDelayMs) {
|
646
|
+
await (0, Utils_1.delay)(retryRequestDelayMs);
|
647
|
+
}
|
648
|
+
}
|
649
|
+
else {
|
650
|
+
logger.debug({ node }, 'connection closed, ignoring retry req');
|
651
|
+
}
|
652
|
+
});
|
653
|
+
}
|
654
|
+
else {
|
655
|
+
// no type in the receipt => message delivered
|
656
|
+
let type = undefined;
|
657
|
+
let participant = msg.key.participant;
|
658
|
+
if (category === 'peer') { // special peer message
|
659
|
+
type = 'peer_msg';
|
660
|
+
}
|
661
|
+
else if (msg.key.fromMe) { // message was sent by us from a different device
|
662
|
+
type = 'sender';
|
663
|
+
// need to specially handle this case
|
664
|
+
if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
|
665
|
+
participant = author;
|
666
|
+
}
|
667
|
+
}
|
668
|
+
else if (!sendActiveReceipts) {
|
669
|
+
type = 'inactive';
|
670
|
+
}
|
671
|
+
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
|
672
|
+
// send ack for history message
|
673
|
+
const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
|
674
|
+
if (isAnyHistoryMsg) {
|
675
|
+
const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
|
676
|
+
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
|
677
|
+
}
|
678
|
+
}
|
679
|
+
(0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
|
680
|
+
await sendMessageAck(node);
|
681
|
+
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
|
682
|
+
})
|
683
|
+
]);
|
684
|
+
}
|
685
|
+
catch (error) {
|
686
|
+
logger.error({ error, node }, 'error in handling message');
|
687
|
+
}
|
688
|
+
};
|
689
|
+
const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
|
690
|
+
var _a;
|
691
|
+
if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
|
692
|
+
throw new boom_1.Boom('Not authenticated');
|
693
|
+
}
|
694
|
+
const pdoMessage = {
|
695
|
+
historySyncOnDemandRequest: {
|
696
|
+
chatJid: oldestMsgKey.remoteJid,
|
697
|
+
oldestMsgFromMe: oldestMsgKey.fromMe,
|
698
|
+
oldestMsgId: oldestMsgKey.id,
|
699
|
+
oldestMsgTimestampMs: oldestMsgTimestamp,
|
700
|
+
onDemandMsgCount: count
|
701
|
+
},
|
702
|
+
peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
|
703
|
+
};
|
704
|
+
return sendPeerDataOperationMessage(pdoMessage);
|
705
|
+
};
|
706
|
+
const requestPlaceholderResend = async (messageKey) => {
|
707
|
+
var _a;
|
708
|
+
if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
|
709
|
+
throw new boom_1.Boom('Not authenticated');
|
710
|
+
}
|
711
|
+
if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
|
712
|
+
logger.debug({ messageKey }, 'already requested resend');
|
713
|
+
return;
|
714
|
+
}
|
715
|
+
else {
|
716
|
+
placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
|
717
|
+
}
|
718
|
+
await (0, Utils_1.delay)(5000);
|
719
|
+
if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
|
720
|
+
logger.debug({ messageKey }, 'message received while resend requested');
|
721
|
+
return 'RESOLVED';
|
722
|
+
}
|
723
|
+
const pdoMessage = {
|
724
|
+
placeholderMessageResendRequest: [{
|
725
|
+
messageKey
|
726
|
+
}],
|
727
|
+
peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
|
728
|
+
};
|
729
|
+
setTimeout(() => {
|
730
|
+
if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
|
731
|
+
logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
|
732
|
+
placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
|
733
|
+
}
|
734
|
+
}, 15000);
|
735
|
+
return sendPeerDataOperationMessage(pdoMessage);
|
736
|
+
};
|
737
|
+
const handleCall = async (node) => {
|
738
|
+
const { attrs } = node;
|
739
|
+
const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
|
740
|
+
const callId = infoChild.attrs['call-id'];
|
741
|
+
const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
|
742
|
+
const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
|
743
|
+
const call = {
|
744
|
+
chatId: attrs.from,
|
745
|
+
from,
|
746
|
+
id: callId,
|
747
|
+
date: new Date(+attrs.t * 1000),
|
748
|
+
offline: !!attrs.offline,
|
749
|
+
status,
|
750
|
+
};
|
751
|
+
if (status === 'offer') {
|
752
|
+
call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
|
753
|
+
call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
|
754
|
+
call.groupJid = infoChild.attrs['group-jid'];
|
755
|
+
callOfferCache.set(call.id, call);
|
756
|
+
}
|
757
|
+
const existingCall = callOfferCache.get(call.id);
|
758
|
+
// use existing call info to populate this event
|
759
|
+
if (existingCall) {
|
760
|
+
call.isVideo = existingCall.isVideo;
|
761
|
+
call.isGroup = existingCall.isGroup;
|
762
|
+
}
|
763
|
+
// delete data once call has ended
|
764
|
+
if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
|
765
|
+
callOfferCache.del(call.id);
|
766
|
+
}
|
767
|
+
ev.emit('call', [call]);
|
768
|
+
await sendMessageAck(node);
|
769
|
+
};
|
770
|
+
const handleBadAck = async ({ attrs }) => {
|
771
|
+
const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
|
772
|
+
// WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
|
773
|
+
// // current hypothesis is that if pash is sent in the ack
|
774
|
+
// // it means -- the message hasn't reached all devices yet
|
775
|
+
// // we'll retry sending the message here
|
776
|
+
// if(attrs.phash) {
|
777
|
+
// logger.info({ attrs }, 'received phash in ack, resending message...')
|
778
|
+
// const msg = await getMessage(key)
|
779
|
+
// if(msg) {
|
780
|
+
// await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
|
781
|
+
// } else {
|
782
|
+
// logger.warn({ attrs }, 'could not send message again, as it was not found')
|
783
|
+
// }
|
784
|
+
// }
|
785
|
+
// error in acknowledgement,
|
786
|
+
// device could not display the message
|
787
|
+
if (attrs.error) {
|
788
|
+
logger.warn({ attrs }, 'received error in ack');
|
789
|
+
ev.emit('messages.update', [
|
790
|
+
{
|
791
|
+
key,
|
792
|
+
update: {
|
793
|
+
status: Types_1.WAMessageStatus.ERROR,
|
794
|
+
messageStubParameters: [
|
795
|
+
attrs.error
|
796
|
+
]
|
797
|
+
}
|
798
|
+
}
|
799
|
+
]);
|
800
|
+
}
|
801
|
+
};
|
802
|
+
/// processes a node with the given function
|
803
|
+
/// and adds the task to the existing buffer if we're buffering events
|
804
|
+
const processNodeWithBuffer = async (node, identifier, exec) => {
|
805
|
+
ev.buffer();
|
806
|
+
await execTask();
|
807
|
+
ev.flush();
|
808
|
+
function execTask() {
|
809
|
+
return exec(node, false)
|
810
|
+
.catch(err => onUnexpectedError(err, identifier));
|
811
|
+
}
|
812
|
+
};
|
813
|
+
const makeOfflineNodeProcessor = () => {
|
814
|
+
const nodeProcessorMap = new Map([
|
815
|
+
['message', handleMessage],
|
816
|
+
['call', handleCall],
|
817
|
+
['receipt', handleReceipt],
|
818
|
+
['notification', handleNotification]
|
819
|
+
]);
|
820
|
+
const nodes = [];
|
821
|
+
let isProcessing = false;
|
822
|
+
const enqueue = (type, node) => {
|
823
|
+
nodes.push({ type, node });
|
824
|
+
if (isProcessing) {
|
825
|
+
return;
|
826
|
+
}
|
827
|
+
isProcessing = true;
|
828
|
+
const promise = async () => {
|
829
|
+
while (nodes.length && ws.isOpen) {
|
830
|
+
const { type, node } = nodes.shift();
|
831
|
+
const nodeProcessor = nodeProcessorMap.get(type);
|
832
|
+
if (!nodeProcessor) {
|
833
|
+
onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
|
834
|
+
continue;
|
835
|
+
}
|
836
|
+
await nodeProcessor(node);
|
837
|
+
}
|
838
|
+
isProcessing = false;
|
839
|
+
};
|
840
|
+
promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
|
841
|
+
};
|
842
|
+
return { enqueue };
|
843
|
+
};
|
844
|
+
const offlineNodeProcessor = makeOfflineNodeProcessor();
|
845
|
+
const processNode = (type, node, identifier, exec) => {
|
846
|
+
const isOffline = !!node.attrs.offline;
|
847
|
+
if (isOffline) {
|
848
|
+
offlineNodeProcessor.enqueue(type, node);
|
849
|
+
}
|
850
|
+
else {
|
851
|
+
processNodeWithBuffer(node, identifier, exec);
|
852
|
+
}
|
853
|
+
};
|
854
|
+
// recv a message
|
855
|
+
ws.on('CB:message', (node) => {
|
856
|
+
processNode('message', node, 'processing message', handleMessage);
|
857
|
+
});
|
858
|
+
ws.on('CB:call', async (node) => {
|
859
|
+
processNode('call', node, 'handling call', handleCall);
|
860
|
+
});
|
861
|
+
ws.on('CB:receipt', node => {
|
862
|
+
processNode('receipt', node, 'handling receipt', handleReceipt);
|
863
|
+
});
|
864
|
+
ws.on('CB:notification', async (node) => {
|
865
|
+
processNode('notification', node, 'handling notification', handleNotification);
|
866
|
+
});
|
867
|
+
ws.on('CB:ack,class:message', (node) => {
|
868
|
+
handleBadAck(node)
|
869
|
+
.catch(error => onUnexpectedError(error, 'handling bad ack'));
|
870
|
+
});
|
871
|
+
ev.on('call', ([call]) => {
|
872
|
+
// missed call + group call notification message generation
|
873
|
+
if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
|
874
|
+
const msg = {
|
875
|
+
key: {
|
876
|
+
remoteJid: call.chatId,
|
877
|
+
id: call.id,
|
878
|
+
fromMe: false
|
879
|
+
},
|
880
|
+
messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
|
881
|
+
};
|
882
|
+
if (call.status === 'timeout') {
|
883
|
+
if (call.isGroup) {
|
884
|
+
msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
|
885
|
+
}
|
886
|
+
else {
|
887
|
+
msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
|
888
|
+
}
|
889
|
+
}
|
890
|
+
else {
|
891
|
+
msg.message = { call: { callKey: Buffer.from(call.id) } };
|
892
|
+
}
|
893
|
+
const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
|
894
|
+
upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
|
895
|
+
}
|
896
|
+
});
|
897
|
+
ev.on('connection.update', ({ isOnline }) => {
|
898
|
+
if (typeof isOnline !== 'undefined') {
|
899
|
+
sendActiveReceipts = isOnline;
|
900
|
+
logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
|
901
|
+
}
|
902
|
+
});
|
903
|
+
return {
|
904
|
+
...sock,
|
905
|
+
sendMessageAck,
|
906
|
+
sendRetryRequest,
|
907
|
+
rejectCall,
|
908
|
+
fetchMessageHistory,
|
909
|
+
requestPlaceholderResend,
|
910
|
+
};
|
911
|
+
};
|
912
|
+
exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
|