whalibmob 5.40.35 → 5.40.37
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/README.md +6 -0
- package/docs/events-history.md +41 -0
- package/docs/groups-channels.md +86 -0
- package/docs/messaging.md +107 -0
- package/index.d.ts +136 -0
- package/index.js +1 -0
- package/lib/Client.js +824 -25
- package/lib/appstate/Mutations.js +51 -1
- package/lib/appstate/SyncdProto.js +48 -0
- package/lib/messages/MessageSecret.js +116 -0
- package/lib/messages/MessageSender.js +38 -0
- package/lib/noise.js +6 -0
- package/lib/proto/MessageProto.js +110 -3
- package/llms.txt +3 -2
- package/package.json +1 -1
package/lib/Client.js
CHANGED
|
@@ -208,6 +208,8 @@ function stripInviteUrl(codeOrUrl) {
|
|
|
208
208
|
|
|
209
209
|
const PING_INTERVAL_MS = 25000;
|
|
210
210
|
const KEEPALIVE_INTERVAL = 20000;
|
|
211
|
+
// How long a keepalive ping may go unanswered before it counts as missed.
|
|
212
|
+
const KEEPALIVE_TIMEOUT_MS = 10000;
|
|
211
213
|
const RECONNECT_BACKOFF = [1000, 2000, 4000, 8000, 15000, 30000];
|
|
212
214
|
|
|
213
215
|
// How many attempts an upload gets before it is left for the next check, and
|
|
@@ -1076,7 +1078,11 @@ function captureInfo(decoded, editOf) {
|
|
|
1076
1078
|
if (protocol.type === 3) protocol.ephemeralExpiration = decoded.ephemeralExpiration;
|
|
1077
1079
|
return { kind: 'protocol', protocol };
|
|
1078
1080
|
}
|
|
1079
|
-
|
|
1081
|
+
// Add-ons act on a message that is already in the chat; none is a message
|
|
1082
|
+
// of its own.
|
|
1083
|
+
if (!type || type === 'unknown' || type === 'reaction' || type === 'pollVote' || type === 'senderKeyDistribution' ||
|
|
1084
|
+
type === 'encReaction' || type === 'encComment' || type === 'encEventResponse' ||
|
|
1085
|
+
type === 'secretEncrypted' || type === 'pinInChat' || type === 'keepInChat') {
|
|
1080
1086
|
return { kind: 'skip' };
|
|
1081
1087
|
}
|
|
1082
1088
|
const info = { kind: 'content' };
|
|
@@ -1784,6 +1790,15 @@ class WhalibmobClient extends EventEmitter {
|
|
|
1784
1790
|
return;
|
|
1785
1791
|
}
|
|
1786
1792
|
|
|
1793
|
+
if (err && String(err.code) === '402') {
|
|
1794
|
+
const expire = err.banExpireSecs != null ? err.banExpireSecs : null;
|
|
1795
|
+
this.emit('temporary_ban', {
|
|
1796
|
+
code: err.banCode != null ? err.banCode : null,
|
|
1797
|
+
expireSecs: expire,
|
|
1798
|
+
expiresAt: expire != null ? Date.now() + expire * 1000 : null
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1787
1802
|
if (err && err.loggedOut) {
|
|
1788
1803
|
_whaDbg('[DBG] HANDSHAKE_REJECTED code=' + err.code + ' — not retrying');
|
|
1789
1804
|
this._fatal = true;
|
|
@@ -3147,6 +3162,30 @@ class WhalibmobClient extends EventEmitter {
|
|
|
3147
3162
|
this._sendAppStateSyncForTypes(dirtyTypes);
|
|
3148
3163
|
}
|
|
3149
3164
|
|
|
3165
|
+
// What the server is about to replay from while we were away, and the
|
|
3166
|
+
// moment it has finished. Until offline_sync_completed, what arrives is
|
|
3167
|
+
// backlog rather than live traffic.
|
|
3168
|
+
for (const child of children) {
|
|
3169
|
+
if (!child) continue;
|
|
3170
|
+
const a = child.attrs || {};
|
|
3171
|
+
const num = (v) => (v != null && Number.isFinite(Number(v)) ? Number(v) : 0);
|
|
3172
|
+
if (child.description === 'offline_preview') {
|
|
3173
|
+
this.emit('offline_sync_preview', {
|
|
3174
|
+
total: num(a.count),
|
|
3175
|
+
appDataChanges: num(a.appdata),
|
|
3176
|
+
messages: num(a.message),
|
|
3177
|
+
notifications: num(a.notification),
|
|
3178
|
+
receipts: num(a.receipt)
|
|
3179
|
+
});
|
|
3180
|
+
} else if (child.description === 'offline') {
|
|
3181
|
+
this.emit('offline_sync_completed', { count: num(a.count) });
|
|
3182
|
+
} else if (child.description === 'downgrade_webclient') {
|
|
3183
|
+
// The QR was scanned by a phone that has multi-device turned off. The
|
|
3184
|
+
// same QR still works once it is turned on.
|
|
3185
|
+
this.emit('qr_scanned_without_multidevice', {});
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
|
|
3150
3189
|
// After the first login the server asks for a SafetyNet attestation with
|
|
3151
3190
|
// <ib><safetynet><integrity nonce='…'/></safetynet></ib>. The client answers
|
|
3152
3191
|
// in the same window with <ib><integrity_payload> (and a keystore chain that
|
|
@@ -3675,6 +3714,42 @@ class WhalibmobClient extends EventEmitter {
|
|
|
3675
3714
|
this.emit('push_name_update', { name, remote: true });
|
|
3676
3715
|
break;
|
|
3677
3716
|
}
|
|
3717
|
+
case 'labelEdit': {
|
|
3718
|
+
const l = a.labelEditAction || {};
|
|
3719
|
+
this.emit('label_edit', {
|
|
3720
|
+
labelId: what.labelId, name: l.name || '', color: l.color || 0,
|
|
3721
|
+
deleted: removed || !!l.deleted, remote: true
|
|
3722
|
+
});
|
|
3723
|
+
break;
|
|
3724
|
+
}
|
|
3725
|
+
case 'labelChat':
|
|
3726
|
+
this.emit('label_association', {
|
|
3727
|
+
labelId: what.labelId, jid: what.jid, msgId: null,
|
|
3728
|
+
labeled: !removed && !!(a.labelAssociationAction && a.labelAssociationAction.labeled), remote: true
|
|
3729
|
+
});
|
|
3730
|
+
break;
|
|
3731
|
+
case 'labelMessage':
|
|
3732
|
+
this.emit('label_association', {
|
|
3733
|
+
labelId: what.labelId, jid: what.jid, msgId: what.msgId,
|
|
3734
|
+
labeled: !removed && !!(a.labelAssociationAction && a.labelAssociationAction.labeled), remote: true
|
|
3735
|
+
});
|
|
3736
|
+
break;
|
|
3737
|
+
case 'deleteForMe':
|
|
3738
|
+
this.emit('message_deleted_for_me', {
|
|
3739
|
+
jid, msgId: what.msgId, fromMe: what.fromMe,
|
|
3740
|
+
deleteMedia: !!(a.deleteMessageForMeAction && a.deleteMessageForMeAction.deleteMedia), remote: true
|
|
3741
|
+
});
|
|
3742
|
+
break;
|
|
3743
|
+
case 'statusMute':
|
|
3744
|
+
this.emit('status_muted', {
|
|
3745
|
+
jid, muted: !removed && !!(a.userStatusMuteAction && a.userStatusMuteAction.muted), remote: true
|
|
3746
|
+
});
|
|
3747
|
+
break;
|
|
3748
|
+
case 'unarchiveChats':
|
|
3749
|
+
this.emit('unarchive_chats_setting', {
|
|
3750
|
+
unarchiveChats: !!(a.unarchiveChatsSetting && a.unarchiveChatsSetting.unarchiveChats), remote: true
|
|
3751
|
+
});
|
|
3752
|
+
break;
|
|
3678
3753
|
case 'clear':
|
|
3679
3754
|
case 'delete':
|
|
3680
3755
|
this.emit('chat_removed', { jid, kind: what.kind, remote: true });
|
|
@@ -3842,16 +3917,9 @@ class WhalibmobClient extends EventEmitter {
|
|
|
3842
3917
|
if (this._sender && this._connected) this._sender.ping();
|
|
3843
3918
|
}, PING_INTERVAL_MS);
|
|
3844
3919
|
|
|
3845
|
-
this.
|
|
3846
|
-
|
|
3847
|
-
|
|
3848
|
-
id: this._genMsgId(),
|
|
3849
|
-
to: 's.whatsapp.net',
|
|
3850
|
-
type: 'get',
|
|
3851
|
-
xmlns: 'w:p'
|
|
3852
|
-
}, [new BinaryNode('ping', {}, null)]));
|
|
3853
|
-
}
|
|
3854
|
-
}, KEEPALIVE_INTERVAL);
|
|
3920
|
+
this._keepAliveErrors = 0;
|
|
3921
|
+
this._keepAliveLastOk = Date.now();
|
|
3922
|
+
this._keepTimer = setInterval(() => { this._keepAlivePing(); }, KEEPALIVE_INTERVAL);
|
|
3855
3923
|
|
|
3856
3924
|
// The server is supposed to say when it is running out of one-time keys,
|
|
3857
3925
|
// and mostly does. This is for when it does not: a session that stays up
|
|
@@ -3862,6 +3930,45 @@ class WhalibmobClient extends EventEmitter {
|
|
|
3862
3930
|
}, PRE_KEY_CHECK_INTERVAL);
|
|
3863
3931
|
}
|
|
3864
3932
|
|
|
3933
|
+
// The keepalive ping, with its answer waited for.
|
|
3934
|
+
//
|
|
3935
|
+
// A ping that is only ever sent proves nothing: on a connection that died
|
|
3936
|
+
// without closing, the writes go into a buffer and the client carries on
|
|
3937
|
+
// believing it is online. Each ping now has a deadline. A missed one is
|
|
3938
|
+
// announced as keepalive_timeout, with how many in a row and when the last
|
|
3939
|
+
// answer came; the first answer after that is keepalive_restored. Nothing is
|
|
3940
|
+
// torn down here — the caller decides whether a silent connection is worth
|
|
3941
|
+
// dropping.
|
|
3942
|
+
_keepAlivePing() {
|
|
3943
|
+
if (!this._socket || !this._connected) return;
|
|
3944
|
+
this._sendIq(new BinaryNode('iq', {
|
|
3945
|
+
id: this._genMsgId(),
|
|
3946
|
+
to: 's.whatsapp.net',
|
|
3947
|
+
type: 'get',
|
|
3948
|
+
xmlns: 'w:p'
|
|
3949
|
+
}, [new BinaryNode('ping', {}, null)]), { timeoutMs: KEEPALIVE_TIMEOUT_MS, rejectOnNoReply: true })
|
|
3950
|
+
.then(() => {
|
|
3951
|
+
const errors = this._keepAliveErrors || 0;
|
|
3952
|
+
this._keepAliveErrors = 0;
|
|
3953
|
+
this._keepAliveLastOk = Date.now();
|
|
3954
|
+
if (errors > 0) {
|
|
3955
|
+
_whaDbg('[DBG] KEEPALIVE restored after ' + errors + ' missed');
|
|
3956
|
+
this.emit('keepalive_restored', { missed: errors });
|
|
3957
|
+
}
|
|
3958
|
+
})
|
|
3959
|
+
.catch((err) => {
|
|
3960
|
+
// A close has its own events; only a deadline is a silent connection.
|
|
3961
|
+
if (!err || err.code !== 'IQ_TIMEOUT' || !this._connected) return;
|
|
3962
|
+
this._keepAliveErrors = (this._keepAliveErrors || 0) + 1;
|
|
3963
|
+
_whaDbg('[DBG] KEEPALIVE timeout #' + this._keepAliveErrors);
|
|
3964
|
+
this.emit('keepalive_timeout', {
|
|
3965
|
+
errorCount: this._keepAliveErrors,
|
|
3966
|
+
lastSuccess: this._keepAliveLastOk || null
|
|
3967
|
+
});
|
|
3968
|
+
})
|
|
3969
|
+
.catch(() => {});
|
|
3970
|
+
}
|
|
3971
|
+
|
|
3865
3972
|
_stopTimers() {
|
|
3866
3973
|
if (this._pingTimer) { clearInterval(this._pingTimer); this._pingTimer = null; }
|
|
3867
3974
|
if (this._keepTimer) { clearInterval(this._keepTimer); this._keepTimer = null; }
|
|
@@ -4059,6 +4166,19 @@ class WhalibmobClient extends EventEmitter {
|
|
|
4059
4166
|
const fromRaw = attrs.from || null;
|
|
4060
4167
|
const partRaw = attrs.participant || null;
|
|
4061
4168
|
const from = String(attrs.from || '');
|
|
4169
|
+
// A channel post is not encrypted: the Message rides in <plaintext>.
|
|
4170
|
+
if (from.endsWith('@newsletter')) {
|
|
4171
|
+
const post = this._parseNewsletterMessages({ content: [node] })[0];
|
|
4172
|
+
this._sendMessageAck(String(attrs.id || ''), fromRaw, null);
|
|
4173
|
+
if (post && post.decoded) {
|
|
4174
|
+
this.emit('message', {
|
|
4175
|
+
id: post.id, from, participant: from, ts: post.ts, decoded: post.decoded, node,
|
|
4176
|
+
fromMe: false, chat: from, newsletter: true, serverId: post.serverId,
|
|
4177
|
+
viewsCount: post.viewsCount, reactionCounts: post.reactionCounts
|
|
4178
|
+
});
|
|
4179
|
+
}
|
|
4180
|
+
return;
|
|
4181
|
+
}
|
|
4062
4182
|
const id = String(attrs.id || '');
|
|
4063
4183
|
const ts = parseInt(attrs.t || '0', 10);
|
|
4064
4184
|
const participant = String(attrs.participant || from);
|
|
@@ -5557,6 +5677,10 @@ class WhalibmobClient extends EventEmitter {
|
|
|
5557
5677
|
this._handleMexNotification(node);
|
|
5558
5678
|
}
|
|
5559
5679
|
|
|
5680
|
+
if (type === 'picture') this._handlePictureNotification(node);
|
|
5681
|
+
if (type === 'status') this._handleAboutNotification(node);
|
|
5682
|
+
if (type === 'newsletter') this._handleNewsletterNotification(node);
|
|
5683
|
+
|
|
5560
5684
|
if (type === 'privacy_token') {
|
|
5561
5685
|
// Incoming trusted-contact token from a conversation partner — store it
|
|
5562
5686
|
// so we can attach it on next DM send (prevents error 463).
|
|
@@ -6080,6 +6204,18 @@ class WhalibmobClient extends EventEmitter {
|
|
|
6080
6204
|
return;
|
|
6081
6205
|
}
|
|
6082
6206
|
|
|
6207
|
+
// A temporary ban: the account is fine and the session survives, but the
|
|
6208
|
+
// server will refuse it until the ban runs out. `code` says which kind,
|
|
6209
|
+
// `expireSecs` how long is left.
|
|
6210
|
+
if (reason === '402') {
|
|
6211
|
+
const expire = attrs.expire != null && Number.isFinite(Number(attrs.expire)) ? Number(attrs.expire) : null;
|
|
6212
|
+
this.emit('temporary_ban', {
|
|
6213
|
+
code: attrs.code != null ? String(attrs.code) : null,
|
|
6214
|
+
expireSecs: expire,
|
|
6215
|
+
expiresAt: expire != null ? Date.now() + expire * 1000 : null
|
|
6216
|
+
});
|
|
6217
|
+
}
|
|
6218
|
+
|
|
6083
6219
|
// Not every failure kills the session. These five do — 401, 403, 405, 406,
|
|
6084
6220
|
// 409 — and the rest are worth another attempt. A 500 or a 503 is the
|
|
6085
6221
|
// server having a bad minute; giving
|
|
@@ -8434,6 +8570,219 @@ class WhalibmobClient extends EventEmitter {
|
|
|
8434
8570
|
return this._sender.editMessage(origMsgId, chatJid, newText, opts);
|
|
8435
8571
|
}
|
|
8436
8572
|
|
|
8573
|
+
/**
|
|
8574
|
+
* Send a message this library has no method for.
|
|
8575
|
+
*
|
|
8576
|
+
* `message` is an encoded `Message` protobuf, built with whatever schema
|
|
8577
|
+
* tooling you use. It is encrypted and fanned out exactly as the built-in
|
|
8578
|
+
* sends are; only the content is yours.
|
|
8579
|
+
*
|
|
8580
|
+
* The stanza still has to say what kind of message it carries, which the
|
|
8581
|
+
* server reads without decrypting anything:
|
|
8582
|
+
*
|
|
8583
|
+
* @param {string} to
|
|
8584
|
+
* @param {Buffer} message
|
|
8585
|
+
* @param {object} [opts]
|
|
8586
|
+
* @param {'text'|'media'|'poll'|'reaction'} [opts.type] stanza type, default 'text'
|
|
8587
|
+
* @param {string} [opts.mediaType] for 'media': image, video, audio, ptt,
|
|
8588
|
+
* document, sticker, gif, vcard, location…
|
|
8589
|
+
* @param {'creation'|'vote'} [opts.pollType] for 'poll'
|
|
8590
|
+
* @param {string} [opts.edit] the edit attribute: '1' edit, '2' pin,
|
|
8591
|
+
* '7' revoke, '8' admin revoke
|
|
8592
|
+
* @param {boolean} [opts.hide] tell recipients to show nothing if it
|
|
8593
|
+
* cannot be decrypted
|
|
8594
|
+
* @param {string} [opts.id] message id, generated when absent
|
|
8595
|
+
*/
|
|
8596
|
+
async sendRawMessage(to, message, opts) {
|
|
8597
|
+
if (!this._sender || !this._connected) throw new Error('Not connected');
|
|
8598
|
+
return this._sender.sendRaw(to, message, opts);
|
|
8599
|
+
}
|
|
8600
|
+
|
|
8601
|
+
/**
|
|
8602
|
+
* Vote on a poll.
|
|
8603
|
+
*
|
|
8604
|
+
* @param {string} chatJid the chat the poll is in
|
|
8605
|
+
* @param {object} poll
|
|
8606
|
+
* @param {string} poll.id the poll message's id
|
|
8607
|
+
* @param {string} poll.sender who sent the poll (their JID, as the poll
|
|
8608
|
+
* message's sender; our own for a poll we sent)
|
|
8609
|
+
* @param {boolean} [poll.fromMe] the poll is ours
|
|
8610
|
+
* @param {Buffer} poll.encKey the poll's message secret: `decoded.encKey`
|
|
8611
|
+
* on a received poll, or what `sendPoll` returned
|
|
8612
|
+
* @param {string[]} selected the option texts to vote for; empty clears the vote
|
|
8613
|
+
*/
|
|
8614
|
+
async sendPollVote(chatJid, poll, selected, opts) {
|
|
8615
|
+
if (!this._sender || !this._connected) throw new Error('Not connected');
|
|
8616
|
+
const MS = require('./messages/MessageSecret');
|
|
8617
|
+
const { encodePollUpdateMessage, encodePollVoteMessage } = require('./proto/MessageProto');
|
|
8618
|
+
if (!poll || !poll.id) throw new Error('sendPollVote: the poll\'s message id is required');
|
|
8619
|
+
const chat = makeJid(chatJid);
|
|
8620
|
+
const isGroup = chat.endsWith('@g.us');
|
|
8621
|
+
const voter = this._addOnSenderFor(poll.sender, opts);
|
|
8622
|
+
const pollSender = poll.fromMe ? voter : poll.sender;
|
|
8623
|
+
if (!pollSender) throw new Error('sendPollVote: poll.sender is required for a poll somebody else sent');
|
|
8624
|
+
const sealed = MS.encryptSecret({
|
|
8625
|
+
type: MS.SECRET_TYPE.POLL_VOTE,
|
|
8626
|
+
messageSecret: poll.encKey || poll.messageSecret,
|
|
8627
|
+
targetId: poll.id, targetSender: pollSender, sender: voter,
|
|
8628
|
+
plaintext: encodePollVoteMessage(MS.hashPollOptions(selected))
|
|
8629
|
+
});
|
|
8630
|
+
const key = { remoteJid: chat, fromMe: !!poll.fromMe, id: poll.id };
|
|
8631
|
+
if (isGroup && !poll.fromMe) key.participant = toNonAdJid(String(poll.sender));
|
|
8632
|
+
const message = encodePollUpdateMessage({ key, encPayload: sealed.encPayload, encIv: sealed.encIv });
|
|
8633
|
+
return this._sender.sendRaw(chat, message,
|
|
8634
|
+
Object.assign({}, opts, { type: 'poll', pollType: 'vote', hide: true }));
|
|
8635
|
+
}
|
|
8636
|
+
|
|
8637
|
+
// Which of our own addresses an add-on is sent as. It has to be in the same
|
|
8638
|
+
// space as the message it acts on: a target addressed by LID is answered
|
|
8639
|
+
// from our LID, one addressed by phone number from our number.
|
|
8640
|
+
_addOnSenderFor(targetSender, opts) {
|
|
8641
|
+
if (opts && opts.sender) return toNonAdJid(String(opts.sender));
|
|
8642
|
+
const lid = this._myLid ? toNonAdJid(String(this._myLid)) : null;
|
|
8643
|
+
if (lid && String(targetSender || '').endsWith('@lid')) return lid;
|
|
8644
|
+
return toNonAdJid(this._ownDeviceJid());
|
|
8645
|
+
}
|
|
8646
|
+
|
|
8647
|
+
/**
|
|
8648
|
+
* Pin a message for everyone in a chat, or unpin it.
|
|
8649
|
+
*
|
|
8650
|
+
* @param {string} chatJid
|
|
8651
|
+
* @param {object} target `{ id, fromMe, participant? }` — the message, and
|
|
8652
|
+
* in a group who sent it when it is not ours
|
|
8653
|
+
* @param {object} [opts]
|
|
8654
|
+
* @param {boolean} [opts.pin] false unpins; default true
|
|
8655
|
+
* @param {number} [opts.durationSecs] how long it stays pinned: 86400,
|
|
8656
|
+
* 604800 (default) or 2592000
|
|
8657
|
+
*/
|
|
8658
|
+
async pinMessage(chatJid, target, opts) {
|
|
8659
|
+
if (!this._sender || !this._connected) throw new Error('Not connected');
|
|
8660
|
+
opts = opts || {};
|
|
8661
|
+
if (!target || !target.id) throw new Error('pinMessage: the target message id is required');
|
|
8662
|
+
const { encodePinInChatMessage } = require('./proto/MessageProto');
|
|
8663
|
+
const chat = makeJid(chatJid);
|
|
8664
|
+
const key = { remoteJid: chat, fromMe: !!target.fromMe, id: target.id };
|
|
8665
|
+
if (chat.endsWith('@g.us') && !target.fromMe && target.participant) {
|
|
8666
|
+
key.participant = toNonAdJid(String(target.participant));
|
|
8667
|
+
}
|
|
8668
|
+
const message = encodePinInChatMessage({
|
|
8669
|
+
key, pin: opts.pin !== false,
|
|
8670
|
+
durationSecs: opts.durationSecs || 604800
|
|
8671
|
+
});
|
|
8672
|
+
return this._sender.sendRaw(chat, message, { id: opts.id, type: 'text', edit: '2' });
|
|
8673
|
+
}
|
|
8674
|
+
|
|
8675
|
+
/** Unpin a message pinned for everyone. */
|
|
8676
|
+
async unpinMessage(chatJid, target, opts) {
|
|
8677
|
+
return this.pinMessage(chatJid, target, Object.assign({}, opts, { pin: false }));
|
|
8678
|
+
}
|
|
8679
|
+
|
|
8680
|
+
/**
|
|
8681
|
+
* Open an add-on that is sealed under another message's secret.
|
|
8682
|
+
*
|
|
8683
|
+
* A reaction or a comment in a community announcement group, a response to
|
|
8684
|
+
* an event and an encrypted edit all arrive naming their target and carrying
|
|
8685
|
+
* ciphertext. The key comes from the target message's secret
|
|
8686
|
+
* (`decoded.messageSecret` on that message), who sent the target, and who
|
|
8687
|
+
* sent the add-on.
|
|
8688
|
+
*
|
|
8689
|
+
* @param {object} msg the `message` event payload, or its `decoded`
|
|
8690
|
+
* @param {object} opts
|
|
8691
|
+
* @param {Buffer} opts.messageSecret the target message's 32-byte secret
|
|
8692
|
+
* @param {string} [opts.targetSender] who sent the target; defaults to the
|
|
8693
|
+
* key's participant, or its chat in a DM
|
|
8694
|
+
* @param {string} [opts.sender] who sent the add-on; defaults to the
|
|
8695
|
+
* message's sender
|
|
8696
|
+
* @returns {{type: string, targetKey: object, plaintext: Buffer, decoded: object|null}}
|
|
8697
|
+
* `plaintext` is the protobuf inside; `decoded` is it read as a
|
|
8698
|
+
* Message where that is what it is (an edit, a comment)
|
|
8699
|
+
*/
|
|
8700
|
+
decryptSecretMessage(msg, opts) {
|
|
8701
|
+
opts = opts || {};
|
|
8702
|
+
const MS = require('./messages/MessageSecret');
|
|
8703
|
+
const d = (msg && msg.decoded) ? msg.decoded : msg;
|
|
8704
|
+
const LABEL = {
|
|
8705
|
+
encReaction: MS.SECRET_TYPE.REACTION,
|
|
8706
|
+
encComment: MS.SECRET_TYPE.COMMENT,
|
|
8707
|
+
encEventResponse: MS.SECRET_TYPE.EVENT_RESPONSE
|
|
8708
|
+
};
|
|
8709
|
+
if (!d || !(d.type in LABEL || d.type === 'secretEncrypted')) {
|
|
8710
|
+
throw new Error('decryptSecretMessage: this message is not an encrypted add-on');
|
|
8711
|
+
}
|
|
8712
|
+
const type = d.type === 'secretEncrypted'
|
|
8713
|
+
? MS.SECRET_ENC_TYPE[d.secretEncType]
|
|
8714
|
+
: LABEL[d.type];
|
|
8715
|
+
if (!type) throw new Error('decryptSecretMessage: unsupported secretEncType ' + d.secretEncType);
|
|
8716
|
+
const key = d.targetKey || {};
|
|
8717
|
+
if (!key.id) throw new Error('decryptSecretMessage: the add-on does not name its target');
|
|
8718
|
+
|
|
8719
|
+
const sender = toNonAdJid(String(
|
|
8720
|
+
opts.sender || (msg && msg.participant) || (msg && msg.from) || ''));
|
|
8721
|
+
if (!sender || sender.startsWith('@')) {
|
|
8722
|
+
throw new Error('decryptSecretMessage: cannot tell who sent this — pass opts.sender');
|
|
8723
|
+
}
|
|
8724
|
+
// Who sent the target. Ours: the add-on's own sender. In a direct chat:
|
|
8725
|
+
// the chat the key names. In a group: the participant the key names.
|
|
8726
|
+
const chat = String((msg && (msg.chat || msg.from)) || key.remoteJid || '');
|
|
8727
|
+
const direct = chat.endsWith('@s.whatsapp.net') || chat.endsWith('@lid');
|
|
8728
|
+
const targetSender = toNonAdJid(String(
|
|
8729
|
+
opts.targetSender || (key.fromMe ? sender
|
|
8730
|
+
: direct ? (key.remoteJid || key.participant || '')
|
|
8731
|
+
: (key.participant || key.remoteJid || ''))));
|
|
8732
|
+
|
|
8733
|
+
const plaintext = MS.decryptSecret({
|
|
8734
|
+
type, messageSecret: opts.messageSecret || opts.encKey,
|
|
8735
|
+
targetId: key.id, targetSender, sender,
|
|
8736
|
+
encPayload: d.encPayload, encIv: d.encIv
|
|
8737
|
+
});
|
|
8738
|
+
|
|
8739
|
+
const out = { type: d.type, secretType: type, targetKey: key, plaintext, decoded: null };
|
|
8740
|
+
const { decodeFields, decodeMessageContainer } = require('./proto/MessageProto');
|
|
8741
|
+
try {
|
|
8742
|
+
if (d.type === 'encReaction') {
|
|
8743
|
+
// ReactionMessage { key = 1, text = 2, senderTimestampMS = 4 }
|
|
8744
|
+
const f = decodeFields(plaintext);
|
|
8745
|
+
out.text = Buffer.isBuffer(f[2]) ? f[2].toString('utf8') : '';
|
|
8746
|
+
if (typeof f[4] === 'number') out.senderTimestampMs = f[4];
|
|
8747
|
+
} else if (d.type === 'encEventResponse') {
|
|
8748
|
+
// EventResponseMessage { response = 1 (1 going, 2 not going, 3 maybe),
|
|
8749
|
+
// timestampMS = 2, extraGuestCount = 3 }
|
|
8750
|
+
const f = decodeFields(plaintext);
|
|
8751
|
+
out.response = ({ 1: 'going', 2: 'not_going', 3: 'maybe' })[f[1]] || 'unknown';
|
|
8752
|
+
if (typeof f[2] === 'number') out.timestampMs = f[2];
|
|
8753
|
+
if (typeof f[3] === 'number') out.extraGuestCount = f[3];
|
|
8754
|
+
} else if (d.type === 'encComment') {
|
|
8755
|
+
// CommentMessage { message = 1, targetMessageKey = 2 }
|
|
8756
|
+
const f = decodeFields(plaintext);
|
|
8757
|
+
if (Buffer.isBuffer(f[1])) { out.messageRaw = f[1]; out.decoded = decodeMessageContainer(f[1]); }
|
|
8758
|
+
} else {
|
|
8759
|
+
out.decoded = decodeMessageContainer(plaintext);
|
|
8760
|
+
}
|
|
8761
|
+
} catch (_) { /* the plaintext is still there to read */ }
|
|
8762
|
+
return out;
|
|
8763
|
+
}
|
|
8764
|
+
|
|
8765
|
+
/** A reaction sent in a community announcement group. See `decryptSecretMessage`. */
|
|
8766
|
+
decryptReaction(msg, opts) {
|
|
8767
|
+
const d = (msg && msg.decoded) ? msg.decoded : msg;
|
|
8768
|
+
if (!d || d.type !== 'encReaction') throw new Error('decryptReaction: this is not an encrypted reaction');
|
|
8769
|
+
return this.decryptSecretMessage(msg, opts);
|
|
8770
|
+
}
|
|
8771
|
+
|
|
8772
|
+
/** A comment on a community announcement. See `decryptSecretMessage`. */
|
|
8773
|
+
decryptComment(msg, opts) {
|
|
8774
|
+
const d = (msg && msg.decoded) ? msg.decoded : msg;
|
|
8775
|
+
if (!d || d.type !== 'encComment') throw new Error('decryptComment: this is not an encrypted comment');
|
|
8776
|
+
return this.decryptSecretMessage(msg, opts);
|
|
8777
|
+
}
|
|
8778
|
+
|
|
8779
|
+
/** A response to an event. See `decryptSecretMessage`. */
|
|
8780
|
+
decryptEventResponse(msg, opts) {
|
|
8781
|
+
const d = (msg && msg.decoded) ? msg.decoded : msg;
|
|
8782
|
+
if (!d || d.type !== 'encEventResponse') throw new Error('decryptEventResponse: this is not an event response');
|
|
8783
|
+
return this.decryptSecretMessage(msg, opts);
|
|
8784
|
+
}
|
|
8785
|
+
|
|
8437
8786
|
// Delete a message
|
|
8438
8787
|
// fromMe: whether the message was sent by us
|
|
8439
8788
|
// forEveryone: true = revoke for all, false = delete locally only
|
|
@@ -9378,8 +9727,10 @@ class WhalibmobClient extends EventEmitter {
|
|
|
9378
9727
|
if (!voter || voter.startsWith('@')) {
|
|
9379
9728
|
throw new Error('decryptPollVote: cannot tell who cast this vote — pass opts.voter');
|
|
9380
9729
|
}
|
|
9730
|
+
// In a group the key's remoteJid is the group; the poll's author is the
|
|
9731
|
+
// participant it names.
|
|
9381
9732
|
const pollSender = toNonAdJid(String(
|
|
9382
|
-
opts.pollSender || (key.fromMe ? voter : (key.remoteJid || voter))));
|
|
9733
|
+
opts.pollSender || (key.fromMe ? voter : (key.participant || key.remoteJid || voter))));
|
|
9383
9734
|
|
|
9384
9735
|
const info = Buffer.concat([
|
|
9385
9736
|
Buffer.from(pollId, 'utf8'),
|
|
@@ -10062,19 +10413,467 @@ class WhalibmobClient extends EventEmitter {
|
|
|
10062
10413
|
async sendNewsletterText(newsletterJid, text) {
|
|
10063
10414
|
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10064
10415
|
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10065
|
-
|
|
10066
|
-
|
|
10067
|
-
|
|
10068
|
-
|
|
10069
|
-
|
|
10070
|
-
|
|
10071
|
-
|
|
10072
|
-
|
|
10073
|
-
|
|
10074
|
-
|
|
10075
|
-
|
|
10076
|
-
|
|
10077
|
-
|
|
10416
|
+
// A channel post is an encoded Message in <plaintext>, the same shape the
|
|
10417
|
+
// posts we receive have. This used to send the bare text in a node of
|
|
10418
|
+
// another name, with a server id the client does not get to choose.
|
|
10419
|
+
const { encodeText } = require('./proto/MessageProto');
|
|
10420
|
+
return this.sendNewsletterMessage(jid, encodeText(String(text == null ? '' : text)), { type: 'text' });
|
|
10421
|
+
}
|
|
10422
|
+
|
|
10423
|
+
|
|
10424
|
+
// ─── Newsletters: reading, reacting, following along ──────────────────────
|
|
10425
|
+
|
|
10426
|
+
// <message server_id id type t> children of a newsletter reply or push.
|
|
10427
|
+
_parseNewsletterMessages(parent) {
|
|
10428
|
+
const { decodeMessageContainer } = require('./proto/MessageProto');
|
|
10429
|
+
const out = [];
|
|
10430
|
+
const children = parent && Array.isArray(parent.content) ? parent.content : [];
|
|
10431
|
+
for (const child of children) {
|
|
10432
|
+
if (!child || child.description !== 'message') continue;
|
|
10433
|
+
const a = child.attrs || {};
|
|
10434
|
+
const msg = {
|
|
10435
|
+
serverId: a.server_id != null ? Number(a.server_id) : null,
|
|
10436
|
+
id: a.id != null ? String(a.id) : null,
|
|
10437
|
+
type: a.type != null ? String(a.type) : null,
|
|
10438
|
+
ts: a.t != null ? parseInt(a.t, 10) || 0 : 0,
|
|
10439
|
+
viewsCount: 0, forwardsCount: 0, reactionCounts: null,
|
|
10440
|
+
raw: null, decoded: null
|
|
10441
|
+
};
|
|
10442
|
+
for (const sub of (Array.isArray(child.content) ? child.content : [])) {
|
|
10443
|
+
if (!sub) continue;
|
|
10444
|
+
const sa = sub.attrs || {};
|
|
10445
|
+
if (sub.description === 'plaintext') {
|
|
10446
|
+
const buf = getNodeContent(sub);
|
|
10447
|
+
if (buf && buf.length) {
|
|
10448
|
+
msg.raw = buf;
|
|
10449
|
+
try { msg.decoded = decodeMessageContainer(buf); } catch (_) { msg.decoded = null; }
|
|
10450
|
+
}
|
|
10451
|
+
} else if (sub.description === 'views_count') {
|
|
10452
|
+
msg.viewsCount = Number(sa.count) || 0;
|
|
10453
|
+
} else if (sub.description === 'forwards_count') {
|
|
10454
|
+
msg.forwardsCount = Number(sa.count) || 0;
|
|
10455
|
+
} else if (sub.description === 'reactions') {
|
|
10456
|
+
msg.reactionCounts = {};
|
|
10457
|
+
for (const r of (Array.isArray(sub.content) ? sub.content : [])) {
|
|
10458
|
+
if (r && r.attrs && r.attrs.code != null) {
|
|
10459
|
+
msg.reactionCounts[String(r.attrs.code)] = Number(r.attrs.count) || 0;
|
|
10460
|
+
}
|
|
10461
|
+
}
|
|
10462
|
+
}
|
|
10463
|
+
}
|
|
10464
|
+
out.push(msg);
|
|
10465
|
+
}
|
|
10466
|
+
return out;
|
|
10467
|
+
}
|
|
10468
|
+
|
|
10469
|
+
// Throws on no answer and on an <iq type="error">, naming the step.
|
|
10470
|
+
async _iqOrThrow(node, what) {
|
|
10471
|
+
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10472
|
+
const resp = await this._sendIq(node);
|
|
10473
|
+
if (!resp) throw new Error(what + ': no reply from the server');
|
|
10474
|
+
if (resp.attrs && resp.attrs.type === 'error') {
|
|
10475
|
+
const e = findChild(resp, 'error');
|
|
10476
|
+
const code = e && e.attrs && e.attrs.code != null ? String(e.attrs.code) : null;
|
|
10477
|
+
const text = e && e.attrs && e.attrs.text ? String(e.attrs.text) : null;
|
|
10478
|
+
const err = new Error(what + ': refused by the server' +
|
|
10479
|
+
(code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
|
|
10480
|
+
err.code = code; err.text = text;
|
|
10481
|
+
throw err;
|
|
10482
|
+
}
|
|
10483
|
+
return resp;
|
|
10484
|
+
}
|
|
10485
|
+
|
|
10486
|
+
/**
|
|
10487
|
+
* The newest posts of a channel, oldest first within the page.
|
|
10488
|
+
* @param {object} [opts] `{ count, before }` — `before` is a server id to page back from
|
|
10489
|
+
*/
|
|
10490
|
+
async getNewsletterMessages(newsletterJid, opts) {
|
|
10491
|
+
opts = opts || {};
|
|
10492
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10493
|
+
const attrs = { type: 'jid', jid };
|
|
10494
|
+
if (opts.count) attrs.count = String(opts.count);
|
|
10495
|
+
if (opts.before) attrs.before = String(opts.before);
|
|
10496
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10497
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'newsletter'
|
|
10498
|
+
}, [new BinaryNode('messages', attrs, null)]), 'newsletter messages');
|
|
10499
|
+
const messages = findChild(resp, 'messages');
|
|
10500
|
+
if (!messages) throw new Error('newsletter messages: the reply carried no messages');
|
|
10501
|
+
return this._parseNewsletterMessages(messages);
|
|
10502
|
+
}
|
|
10503
|
+
|
|
10504
|
+
/**
|
|
10505
|
+
* What changed on a channel's posts — view and reaction counts, edits.
|
|
10506
|
+
* @param {object} [opts] `{ count, since, after }` — `since` is unix seconds,
|
|
10507
|
+
* `after` a server id
|
|
10508
|
+
*/
|
|
10509
|
+
async getNewsletterMessageUpdates(newsletterJid, opts) {
|
|
10510
|
+
opts = opts || {};
|
|
10511
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10512
|
+
const attrs = {};
|
|
10513
|
+
if (opts.count) attrs.count = String(opts.count);
|
|
10514
|
+
if (opts.since) attrs.since = String(Math.floor(Number(opts.since)));
|
|
10515
|
+
if (opts.after) attrs.after = String(opts.after);
|
|
10516
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10517
|
+
id: this._genMsgId(), to: jid, type: 'get', xmlns: 'newsletter'
|
|
10518
|
+
}, [new BinaryNode('message_updates', attrs, null)]), 'newsletter message updates');
|
|
10519
|
+
const messages = findChild(findChild(resp, 'message_updates'), 'messages');
|
|
10520
|
+
if (!messages) throw new Error('newsletter message updates: the reply carried no messages');
|
|
10521
|
+
return this._parseNewsletterMessages(messages);
|
|
10522
|
+
}
|
|
10523
|
+
|
|
10524
|
+
/**
|
|
10525
|
+
* Ask for a channel's updates to be pushed as they happen. The subscription
|
|
10526
|
+
* lasts as long as the server says — the returned number of seconds — and has
|
|
10527
|
+
* to be asked for again after that. Updates arrive as `newsletter_live_update`.
|
|
10528
|
+
*/
|
|
10529
|
+
async subscribeNewsletterLiveUpdates(newsletterJid) {
|
|
10530
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10531
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10532
|
+
id: this._genMsgId(), to: jid, type: 'set', xmlns: 'newsletter'
|
|
10533
|
+
}, [new BinaryNode('live_updates', {}, null)]), 'newsletter live updates');
|
|
10534
|
+
const live = findChild(resp, 'live_updates');
|
|
10535
|
+
return { durationSecs: live && live.attrs ? Number(live.attrs.duration) || 0 : 0 };
|
|
10536
|
+
}
|
|
10537
|
+
|
|
10538
|
+
/** Count posts as viewed. `serverIds` are the posts' server ids. */
|
|
10539
|
+
async markNewsletterViewed(newsletterJid, serverIds) {
|
|
10540
|
+
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10541
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10542
|
+
const ids = (Array.isArray(serverIds) ? serverIds : [serverIds]).filter(v => v != null);
|
|
10543
|
+
if (!ids.length) throw new Error('markNewsletterViewed: at least one server id is required');
|
|
10544
|
+
this._socket.sendNode(new BinaryNode('receipt', {
|
|
10545
|
+
to: jid, type: 'view', id: this._genMsgId()
|
|
10546
|
+
}, [new BinaryNode('list', {}, ids.map(id => new BinaryNode('item', { server_id: String(id) }, null)))]));
|
|
10547
|
+
}
|
|
10548
|
+
|
|
10549
|
+
/** React to a channel post. An empty `reaction` takes ours back. */
|
|
10550
|
+
async sendNewsletterReaction(newsletterJid, serverId, reaction, opts) {
|
|
10551
|
+
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10552
|
+
if (serverId == null) throw new Error('sendNewsletterReaction: the post\'s server id is required');
|
|
10553
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10554
|
+
const id = (opts && opts.id) || this._genMsgId();
|
|
10555
|
+
const attrs = { to: jid, id, server_id: String(serverId), type: 'reaction' };
|
|
10556
|
+
const reactionAttrs = {};
|
|
10557
|
+
if (reaction) reactionAttrs.code = String(reaction); else attrs.edit = '7';
|
|
10558
|
+
this._socket.sendNode(new BinaryNode('message', attrs, [new BinaryNode('reaction', reactionAttrs, null)]));
|
|
10559
|
+
return { id, to: jid };
|
|
10560
|
+
}
|
|
10561
|
+
|
|
10562
|
+
/** Mute or unmute a channel we follow. */
|
|
10563
|
+
async muteNewsletter(newsletterJid, mute) {
|
|
10564
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10565
|
+
await this._mexQuery(mute === false ? '6068417879924485' : '6274038279359549', { newsletter_id: jid });
|
|
10566
|
+
return { jid, muted: mute !== false };
|
|
10567
|
+
}
|
|
10568
|
+
|
|
10569
|
+
async unmuteNewsletter(newsletterJid) { return this.muteNewsletter(newsletterJid, false); }
|
|
10570
|
+
|
|
10571
|
+
/** The channels this account follows, as the server describes them. */
|
|
10572
|
+
async getSubscribedNewsletters() {
|
|
10573
|
+
const list = await this._mexQuery('6388546374527196', {}, 'xwa2_newsletter_subscribed');
|
|
10574
|
+
return Array.isArray(list) ? list : [];
|
|
10575
|
+
}
|
|
10576
|
+
|
|
10577
|
+
/** A channel's metadata from its invite link or the code at the end of it. */
|
|
10578
|
+
async getNewsletterInfoWithInvite(linkOrCode) {
|
|
10579
|
+
const key = String(linkOrCode || '').replace(/^https?:\/\/(www\.)?whatsapp\.com\/channel\//i, '').trim();
|
|
10580
|
+
if (!key) throw new Error('getNewsletterInfoWithInvite: an invite link or code is required');
|
|
10581
|
+
return this._mexQuery('6563316087068696', {
|
|
10582
|
+
fetch_creation_time: true, fetch_full_image: true, fetch_viewer_metadata: false,
|
|
10583
|
+
input: { key, type: 'INVITE' }
|
|
10584
|
+
}, 'xwa2_newsletter');
|
|
10585
|
+
}
|
|
10586
|
+
|
|
10587
|
+
/**
|
|
10588
|
+
* Post a Message you encoded to a channel you administer.
|
|
10589
|
+
* @param {object} [opts] `{ id, type, mediaType, mediaId, edit }`
|
|
10590
|
+
*/
|
|
10591
|
+
async sendNewsletterMessage(newsletterJid, message, opts) {
|
|
10592
|
+
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10593
|
+
if (!Buffer.isBuffer(message) || !message.length) {
|
|
10594
|
+
throw new Error('sendNewsletterMessage: message must be a non-empty Buffer holding an encoded Message');
|
|
10595
|
+
}
|
|
10596
|
+
opts = opts || {};
|
|
10597
|
+
const jid = makeJid(newsletterJid, 'newsletter');
|
|
10598
|
+
const id = opts.id || this._genMsgId();
|
|
10599
|
+
const attrs = { to: jid, id, type: opts.type || 'text' };
|
|
10600
|
+
if (opts.mediaId) attrs.media_id = String(opts.mediaId);
|
|
10601
|
+
if (opts.edit) attrs.edit = String(opts.edit);
|
|
10602
|
+
const ptAttrs = {};
|
|
10603
|
+
if (opts.mediaType) ptAttrs.mediatype = String(opts.mediaType);
|
|
10604
|
+
this._socket.sendNode(new BinaryNode('message', attrs, [new BinaryNode('plaintext', ptAttrs, message)]));
|
|
10605
|
+
return { id, to: jid };
|
|
10606
|
+
}
|
|
10607
|
+
|
|
10608
|
+
// <notification type="newsletter"><live_updates><messages>…
|
|
10609
|
+
_handleNewsletterNotification(node) {
|
|
10610
|
+
const live = findChild(node, 'live_updates');
|
|
10611
|
+
if (!live) return;
|
|
10612
|
+
const holder = findChild(live, 'messages') || live;
|
|
10613
|
+
const a = node.attrs || {};
|
|
10614
|
+
this.emit('newsletter_live_update', {
|
|
10615
|
+
jid: String(a.from || ''), ts: a.t != null ? parseInt(a.t, 10) || 0 : 0,
|
|
10616
|
+
messages: this._parseNewsletterMessages(holder)
|
|
10617
|
+
});
|
|
10618
|
+
}
|
|
10619
|
+
|
|
10620
|
+
// <notification type="picture"><set|add|delete jid author id/>
|
|
10621
|
+
_handlePictureNotification(node) {
|
|
10622
|
+
const ts = node.attrs && node.attrs.t != null ? parseInt(node.attrs.t, 10) || 0 : 0;
|
|
10623
|
+
for (const child of (Array.isArray(node.content) ? node.content : [])) {
|
|
10624
|
+
if (!child) continue;
|
|
10625
|
+
const tag = child.description;
|
|
10626
|
+
if (tag !== 'set' && tag !== 'add' && tag !== 'delete') continue;
|
|
10627
|
+
const a = child.attrs || {};
|
|
10628
|
+
const jid = a.jid != null ? String(a.jid) : String((node.attrs && node.attrs.from) || '');
|
|
10629
|
+
if (!jid) continue;
|
|
10630
|
+
this.emit('picture_update', {
|
|
10631
|
+
jid, author: a.author != null ? String(a.author) : null,
|
|
10632
|
+
removed: tag === 'delete', pictureId: tag === 'delete' ? null : (a.id != null ? String(a.id) : null), ts
|
|
10633
|
+
});
|
|
10634
|
+
}
|
|
10635
|
+
}
|
|
10636
|
+
|
|
10637
|
+
// <notification type="status" from t><set>text</set>
|
|
10638
|
+
_handleAboutNotification(node) {
|
|
10639
|
+
const set = findChild(node, 'set');
|
|
10640
|
+
const buf = set ? getNodeContent(set) : null;
|
|
10641
|
+
if (!set || buf == null) return;
|
|
10642
|
+
const a = node.attrs || {};
|
|
10643
|
+
this.emit('about_update', {
|
|
10644
|
+
jid: String(a.from || ''), about: buf.toString('utf8'),
|
|
10645
|
+
ts: a.t != null ? parseInt(a.t, 10) || 0 : 0
|
|
10646
|
+
});
|
|
10647
|
+
}
|
|
10648
|
+
|
|
10649
|
+
// ─── Communities, links, bots, labels ─────────────────────────────────────
|
|
10650
|
+
|
|
10651
|
+
/** The groups linked to a community. */
|
|
10652
|
+
async getSubGroups(communityJid) {
|
|
10653
|
+
const jid = makeJid(communityJid, 'g.us');
|
|
10654
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10655
|
+
id: this._genMsgId(), to: jid, type: 'get', xmlns: 'w:g2'
|
|
10656
|
+
}, [new BinaryNode('sub_groups', {}, null)]), 'sub groups');
|
|
10657
|
+
const holder = findChild(resp, 'sub_groups');
|
|
10658
|
+
if (!holder) throw new Error('sub groups: the reply carried no sub_groups');
|
|
10659
|
+
return (Array.isArray(holder.content) ? holder.content : [])
|
|
10660
|
+
.filter(c => c && c.description === 'group' && c.attrs && c.attrs.id)
|
|
10661
|
+
.map(c => {
|
|
10662
|
+
const a = c.attrs;
|
|
10663
|
+
const id = String(a.id);
|
|
10664
|
+
return {
|
|
10665
|
+
jid: id.includes('@') ? id : id + '@g.us',
|
|
10666
|
+
subject: a.subject != null ? String(a.subject) : null,
|
|
10667
|
+
subjectTime: a.s_t != null ? parseInt(a.s_t, 10) || 0 : 0,
|
|
10668
|
+
size: a.size != null ? Number(a.size) || 0 : null,
|
|
10669
|
+
isDefaultSubGroup: !!findChild(c, 'default_sub_group')
|
|
10670
|
+
};
|
|
10671
|
+
});
|
|
10672
|
+
}
|
|
10673
|
+
|
|
10674
|
+
/** Everyone in any group of a community. Only its admins may ask. */
|
|
10675
|
+
async getLinkedGroupsParticipants(communityJid) {
|
|
10676
|
+
const jid = makeJid(communityJid, 'g.us');
|
|
10677
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10678
|
+
id: this._genMsgId(), to: jid, type: 'get', xmlns: 'w:g2'
|
|
10679
|
+
}, [new BinaryNode('linked_groups_participants', {}, null)]), 'linked groups participants');
|
|
10680
|
+
const holder = findChild(resp, 'linked_groups_participants');
|
|
10681
|
+
if (!holder) throw new Error('linked groups participants: the reply carried none');
|
|
10682
|
+
return (Array.isArray(holder.content) ? holder.content : [])
|
|
10683
|
+
.filter(c => c && c.description === 'participant' && c.attrs && c.attrs.jid)
|
|
10684
|
+
.map(c => {
|
|
10685
|
+
const a = c.attrs;
|
|
10686
|
+
const pJid = String(a.jid), pn = a.phone_number ? String(a.phone_number) : null;
|
|
10687
|
+
const lid = a.lid ? String(a.lid) : null;
|
|
10688
|
+
const lidUser = (pJid.endsWith('@lid') ? pJid : lid || '').split('@')[0].split(':')[0];
|
|
10689
|
+
const pnUser = (pJid.endsWith('@lid') ? pn || '' : pJid).split('@')[0].split(':')[0];
|
|
10690
|
+
if (lidUser && pnUser && this._lidToPn && this._pnToLid) {
|
|
10691
|
+
this._lidToPn.set(lidUser, pnUser); this._pnToLid.set(pnUser, lidUser);
|
|
10692
|
+
}
|
|
10693
|
+
return { jid: pJid, phoneNumber: pn, lid };
|
|
10694
|
+
});
|
|
10695
|
+
}
|
|
10696
|
+
|
|
10697
|
+
/** Where a wa.me/message/… business link points, and the text it prefills. */
|
|
10698
|
+
async resolveBusinessMessageLink(linkOrCode) {
|
|
10699
|
+
const code = String(linkOrCode || '')
|
|
10700
|
+
.replace(/^https?:\/\/(wa\.me\/message\/|api\.whatsapp\.com\/message\/)/i, '').split(/[?#]/)[0].trim();
|
|
10701
|
+
if (!code) throw new Error('resolveBusinessMessageLink: a link or code is required');
|
|
10702
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10703
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'w:qr'
|
|
10704
|
+
}, [new BinaryNode('qr', { code }, null)]), 'business message link');
|
|
10705
|
+
const qr = findChild(resp, 'qr');
|
|
10706
|
+
if (!qr) throw new Error('business message link: the reply carried no qr');
|
|
10707
|
+
const a = qr.attrs || {};
|
|
10708
|
+
const msg = findChild(qr, 'message'), biz = findChild(qr, 'business');
|
|
10709
|
+
const b = (biz && biz.attrs) || {};
|
|
10710
|
+
const msgBuf = msg ? getNodeContent(msg) : null;
|
|
10711
|
+
return {
|
|
10712
|
+
jid: a.jid != null ? String(a.jid) : null,
|
|
10713
|
+
pushName: a.notify != null ? String(a.notify) : null,
|
|
10714
|
+
message: msgBuf ? msgBuf.toString('utf8') : null,
|
|
10715
|
+
isSigned: String(b.is_signed) === 'true',
|
|
10716
|
+
verifiedName: b.verified_name != null ? String(b.verified_name) : null,
|
|
10717
|
+
verifiedLevel: b.verified_level != null ? String(b.verified_level) : null
|
|
10718
|
+
};
|
|
10719
|
+
}
|
|
10720
|
+
|
|
10721
|
+
/** Our own contact link, as wa.me/qr/…; `revoke` replaces it with a new one. */
|
|
10722
|
+
async getContactQrLink(revoke) {
|
|
10723
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10724
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'set', xmlns: 'w:qr'
|
|
10725
|
+
}, [new BinaryNode('qr', { type: 'contact', action: revoke ? 'revoke' : 'get' }, null)]), 'contact link');
|
|
10726
|
+
const qr = findChild(resp, 'qr');
|
|
10727
|
+
const code = qr && qr.attrs && qr.attrs.code != null ? String(qr.attrs.code) : null;
|
|
10728
|
+
if (!code) throw new Error('contact link: the reply carried no code');
|
|
10729
|
+
return { code, link: 'https://wa.me/qr/' + code };
|
|
10730
|
+
}
|
|
10731
|
+
|
|
10732
|
+
/** Whose contact a wa.me/qr/… link is. */
|
|
10733
|
+
async resolveContactQrLink(linkOrCode) {
|
|
10734
|
+
const code = String(linkOrCode || '')
|
|
10735
|
+
.replace(/^https?:\/\/(wa\.me\/qr\/|api\.whatsapp\.com\/qr\/)/i, '').split(/[?#]/)[0].trim();
|
|
10736
|
+
if (!code) throw new Error('resolveContactQrLink: a link or code is required');
|
|
10737
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10738
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'w:qr'
|
|
10739
|
+
}, [new BinaryNode('qr', { code }, null)]), 'contact link');
|
|
10740
|
+
const qr = findChild(resp, 'qr');
|
|
10741
|
+
if (!qr) throw new Error('contact link: the reply carried no qr');
|
|
10742
|
+
const a = qr.attrs || {};
|
|
10743
|
+
return {
|
|
10744
|
+
jid: a.jid != null ? String(a.jid) : null,
|
|
10745
|
+
pushName: a.notify != null ? String(a.notify) : null,
|
|
10746
|
+
type: a.type != null ? String(a.type) : null
|
|
10747
|
+
};
|
|
10748
|
+
}
|
|
10749
|
+
|
|
10750
|
+
/** The Meta AI bots the server lists: `[{ jid, personaId }]`. */
|
|
10751
|
+
async getBotList() {
|
|
10752
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10753
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'bot'
|
|
10754
|
+
}, [new BinaryNode('bot', { v: '2' }, null)]), 'bot list');
|
|
10755
|
+
const botNode = findChild(resp, 'bot');
|
|
10756
|
+
if (!botNode) throw new Error('bot list: the reply carried no bot node');
|
|
10757
|
+
const out = [];
|
|
10758
|
+
for (const section of (Array.isArray(botNode.content) ? botNode.content : [])) {
|
|
10759
|
+
if (!section || section.description !== 'section' || !section.attrs || section.attrs.type !== 'all') continue;
|
|
10760
|
+
for (const bot of (Array.isArray(section.content) ? section.content : [])) {
|
|
10761
|
+
if (!bot || bot.description !== 'bot' || !bot.attrs || bot.attrs.jid == null) continue;
|
|
10762
|
+
out.push({ jid: String(bot.attrs.jid), personaId: bot.attrs.persona_id != null ? String(bot.attrs.persona_id) : null });
|
|
10763
|
+
}
|
|
10764
|
+
}
|
|
10765
|
+
return out;
|
|
10766
|
+
}
|
|
10767
|
+
|
|
10768
|
+
/** Create, rename or recolour a label, or delete it with `{ deleted: true }`. */
|
|
10769
|
+
async editLabel(labelId, opts) {
|
|
10770
|
+
opts = opts || {};
|
|
10771
|
+
if (labelId == null || labelId === '') throw new Error('editLabel: a label id is required');
|
|
10772
|
+
await this._sendAppStatePatch(AppMutations.labelEditPatch(labelId, opts.name, opts.color, opts.deleted));
|
|
10773
|
+
this.emit('label_edit', { labelId: String(labelId), name: opts.name || '', color: opts.color || 0, deleted: !!opts.deleted, synced: true });
|
|
10774
|
+
}
|
|
10775
|
+
|
|
10776
|
+
/** Put a label on a chat, or take it off with `labeled: false`. */
|
|
10777
|
+
async labelChat(jid, labelId, labeled) {
|
|
10778
|
+
const jidFull = makeJid(jid);
|
|
10779
|
+
await this._sendAppStatePatch(AppMutations.labelChatPatch(jidFull, labelId, labeled !== false));
|
|
10780
|
+
this.emit('label_association', { labelId: String(labelId), jid: jidFull, msgId: null, labeled: labeled !== false, synced: true });
|
|
10781
|
+
}
|
|
10782
|
+
|
|
10783
|
+
/** Put a label on one message, or take it off with `labeled: false`. */
|
|
10784
|
+
async labelMessage(jid, labelId, msgId, labeled) {
|
|
10785
|
+
const jidFull = makeJid(jid);
|
|
10786
|
+
if (!msgId) throw new Error('labelMessage: a message id is required');
|
|
10787
|
+
await this._sendAppStatePatch(AppMutations.labelMessagePatch(jidFull, labelId, msgId, labeled !== false));
|
|
10788
|
+
this.emit('label_association', { labelId: String(labelId), jid: jidFull, msgId, labeled: labeled !== false, synced: true });
|
|
10789
|
+
}
|
|
10790
|
+
|
|
10791
|
+
/**
|
|
10792
|
+
* Delete one message on this account's devices only.
|
|
10793
|
+
* @param {object} [opts] `{ timestamp, deleteMedia }` — the message's time in
|
|
10794
|
+
* unix seconds, and whether its media goes too
|
|
10795
|
+
*/
|
|
10796
|
+
async deleteMessageForMe(jid, msgId, fromMe, opts) {
|
|
10797
|
+
opts = opts || {};
|
|
10798
|
+
const jidFull = makeJid(jid);
|
|
10799
|
+
if (!msgId) throw new Error('deleteMessageForMe: a message id is required');
|
|
10800
|
+
await this._sendAppStatePatch(AppMutations.deleteMessageForMePatch(
|
|
10801
|
+
jidFull, msgId, !!fromMe, opts.timestamp, opts.deleteMedia));
|
|
10802
|
+
this.emit('message_deleted_for_me', { jid: jidFull, msgId, fromMe: !!fromMe, deleteMedia: !!opts.deleteMedia, synced: true });
|
|
10803
|
+
}
|
|
10804
|
+
|
|
10805
|
+
/**
|
|
10806
|
+
* A sticker pack's listing from WhatsApp's static store: its name, publisher
|
|
10807
|
+
* and stickers. `packId` is the id in a sticker pack link.
|
|
10808
|
+
*/
|
|
10809
|
+
async fetchStickerPack(packId) {
|
|
10810
|
+
const id = String(packId || '').trim();
|
|
10811
|
+
if (!/^[A-Za-z0-9._-]+$/.test(id)) throw new Error('fetchStickerPack: a sticker pack id is required');
|
|
10812
|
+
const url = 'https://static.whatsapp.net/sticker?lottie=1&cat=sticker_pack_data&id=' +
|
|
10813
|
+
encodeURIComponent(id) + '&lg=en';
|
|
10814
|
+
const body = await new Promise((resolve, reject) => {
|
|
10815
|
+
const req = require('https').get(url, { headers: { Origin: 'https://web.whatsapp.com' } }, (res) => {
|
|
10816
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
10817
|
+
res.resume();
|
|
10818
|
+
return reject(new Error('fetchStickerPack: the store answered ' + res.statusCode));
|
|
10819
|
+
}
|
|
10820
|
+
const chunks = []; let size = 0;
|
|
10821
|
+
res.on('data', (c) => {
|
|
10822
|
+
size += c.length;
|
|
10823
|
+
if (size > 4 * 1024 * 1024) { req.destroy(new Error('fetchStickerPack: the listing is too large')); return; }
|
|
10824
|
+
chunks.push(c);
|
|
10825
|
+
});
|
|
10826
|
+
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
10827
|
+
res.on('error', reject);
|
|
10828
|
+
});
|
|
10829
|
+
req.setTimeout(30000, () => req.destroy(new Error('fetchStickerPack: timed out')));
|
|
10830
|
+
req.on('error', reject);
|
|
10831
|
+
});
|
|
10832
|
+
let packs;
|
|
10833
|
+
try { packs = JSON.parse(body); } catch (_) { throw new Error('fetchStickerPack: the store did not answer with JSON'); }
|
|
10834
|
+
if (!Array.isArray(packs) || !packs.length) throw new Error('fetchStickerPack: no sticker pack found');
|
|
10835
|
+
return packs[0];
|
|
10836
|
+
}
|
|
10837
|
+
|
|
10838
|
+
/**
|
|
10839
|
+
* Register a Web Push subscription, so the server wakes this client through
|
|
10840
|
+
* the browser's push service. `auth` and `p256dh` are the subscription's keys.
|
|
10841
|
+
*/
|
|
10842
|
+
async registerWebPush(subscription) {
|
|
10843
|
+
const sub = subscription || {};
|
|
10844
|
+
if (!sub.endpoint || !sub.auth || !sub.p256dh) {
|
|
10845
|
+
throw new Error('registerWebPush: endpoint, auth and p256dh are required');
|
|
10846
|
+
}
|
|
10847
|
+
const b64 = (v) => (Buffer.isBuffer(v) ? v : Buffer.from(String(v).replace(/-/g, '+').replace(/_/g, '/'), 'base64')).toString('base64');
|
|
10848
|
+
await this._iqOrThrow(new BinaryNode('iq', {
|
|
10849
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'set', xmlns: 'urn:xmpp:whatsapp:push'
|
|
10850
|
+
}, [new BinaryNode('config', {
|
|
10851
|
+
platform: 'web', endpoint: String(sub.endpoint), auth: b64(sub.auth), p256dh: b64(sub.p256dh)
|
|
10852
|
+
}, null)]), 'web push registration');
|
|
10853
|
+
}
|
|
10854
|
+
|
|
10855
|
+
/** The push settings the server holds for this device, as attributes. */
|
|
10856
|
+
async getPushConfig() {
|
|
10857
|
+
const resp = await this._iqOrThrow(new BinaryNode('iq', {
|
|
10858
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'urn:xmpp:whatsapp:push'
|
|
10859
|
+
}, [new BinaryNode('settings', {}, null)]), 'push settings');
|
|
10860
|
+
const settings = findChild(resp, 'settings');
|
|
10861
|
+
return Object.assign({}, (settings && settings.attrs) || {});
|
|
10862
|
+
}
|
|
10863
|
+
|
|
10864
|
+
/**
|
|
10865
|
+
* Tell our own phone that a history sync blob could not be fetched, so it
|
|
10866
|
+
* uploads it again. `mediaKey` is the one the history notification carried.
|
|
10867
|
+
*/
|
|
10868
|
+
async sendHistorySyncServerErrorReceipt(msgId, mediaKey) {
|
|
10869
|
+
if (!this._socket || !this._connected) throw new Error('Not connected');
|
|
10870
|
+
const { encryptRetryReceipt } = require('./messages/MediaRetry');
|
|
10871
|
+
const { ciphertext, iv } = encryptRetryReceipt(String(msgId), mediaKey);
|
|
10872
|
+
this._socket.sendNode(new BinaryNode('receipt', {
|
|
10873
|
+
id: String(msgId), type: 'server-error', to: toNonAdJid(this._ownDeviceJid()), category: 'peer'
|
|
10874
|
+
}, [new BinaryNode('encrypt', {}, [
|
|
10875
|
+
new BinaryNode('enc_p', {}, ciphertext), new BinaryNode('enc_iv', {}, iv)
|
|
10876
|
+
])]));
|
|
10078
10877
|
}
|
|
10079
10878
|
|
|
10080
10879
|
// ──────────────────────────────────────────────────────────────────────────
|