zahan-baileys 1.0.0 → 1.1.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/EXPERIMENTAL.md +50 -0
- package/NOTICE.md +1 -1
- package/README.md +88 -13
- package/package.json +1 -1
- package/src/Socket/index.js +15 -0
- package/src/Socket/messages-recv.d.ts +5 -0
- package/src/Socket/messages-recv.js +26 -11
- package/src/Socket/messages-send.d.ts +9 -0
- package/src/Socket/messages-send.js +30 -2
- package/src/Store/make-in-memory-store.js +11 -2
- package/src/Types/Content.d.ts +45 -1
- package/src/Utils/decode-wa-message.d.ts +5 -0
- package/src/Utils/decode-wa-message.js +7 -3
- package/src/Utils/event-buffer.js +44 -1
- package/src/Utils/messages.d.ts +4 -0
- package/src/Utils/messages.js +195 -6
- package/src/Utils/process-message.js +53 -2
- package/src/Utils/view-once.d.ts +3 -0
- package/src/Utils/view-once.js +86 -21
- package/src/index.d.ts +4 -1
package/EXPERIMENTAL.md
CHANGED
|
@@ -306,6 +306,56 @@ router; the payloads have not been observed on the wire.
|
|
|
306
306
|
|
|
307
307
|
---
|
|
308
308
|
|
|
309
|
+
## Sticker reactions
|
|
310
|
+
|
|
311
|
+
`sock.sendStickerReaction` / `sock.reactWithSticker`, `sendMessage(jid, { stickerReact })`,
|
|
312
|
+
`sendMessage(jid, { react: { key, sticker } })`, `getStickerReaction`,
|
|
313
|
+
`isStickerReactionMessage`, `updateMessageWithStickerReaction`, and the
|
|
314
|
+
`messages.sticker-reaction` event.
|
|
315
|
+
|
|
316
|
+
Source: WA Web `2.3000.1057574009` (`vinikjkkj/wa-diff` commit `64ce895c6af7`,
|
|
317
|
+
2026-12-05 — `web.whatsapp.com` was not reachable from the build sandbox).
|
|
318
|
+
|
|
319
|
+
- `WAE2E_pb.js` (`WAWebAssociationProtoUtils.js`): `MessageContextInfo.messageAssociation` (field 10)
|
|
320
|
+
is `{ associationType, parentMessageKey, messageIndex }` with `STICKER_ANNOTATION = 11`.
|
|
321
|
+
`ReactionMessage` still has only fields 1–4; sticker reactions are not a `ReactionMessage`
|
|
322
|
+
extension.
|
|
323
|
+
- `WAWebStickersGenerateStickerMessageProto.js`: a sticker reaction is a regular
|
|
324
|
+
`Message.stickerMessage` (or `lottieStickerMessage.message.stickerMessage` for Lottie) carrying
|
|
325
|
+
`stickerSentTs`, `emojis` joined with a single space, `isAnimated`, `isLottie`, and media
|
|
326
|
+
hashes/keys, alongside top-level `messageContextInfo.messageAssociation`.
|
|
327
|
+
- `WAWebSendMsgMetaNode.js`: parses `<meta message_association_type="sticker_annotation">` on
|
|
328
|
+
receive, but throws `Invalid outgoing association type` when asked to send it — WA Web cannot
|
|
329
|
+
originate sticker reactions (mobile clients send them).
|
|
330
|
+
- `WAWebStickerAnnotationAssociationProcessor.js`: exempt from parent/child sender equality;
|
|
331
|
+
produces `kind: "associatedSticker"` with `viewMode: HIDDEN` (not a chat message). Multiple and
|
|
332
|
+
duplicate stickers per sender are permitted (the 20-per-message cap reported in mobile betas is
|
|
333
|
+
client UX, not enforced on receive here).
|
|
334
|
+
- `WAWebRevoke.js`: `canRevokeOutsideWindow` allows `fromMe && subtype === "sender_revoke"` for
|
|
335
|
+
`STICKER_ANNOTATION`, so removing your own sticker reaction revokes the sticker reaction's own
|
|
336
|
+
message key (`{ delete: stickerReactionMsg.key }`).
|
|
337
|
+
|
|
338
|
+
On outgoing stanzas this implementation adds `<meta message_association_type="sticker_annotation"
|
|
339
|
+
decrypt-fail="hide">` and `decrypt-fail="hide"` on the `<enc>` node (merged into any caller-supplied
|
|
340
|
+
`<meta>`). The `decrypt-fail="hide"` attribute is **assumed**, not proven: WA Web's outgoing
|
|
341
|
+
`WASmaxOutMessagePublishMetaHideDecryptionPlaceholderMixin` and legacy `WASendMsgRPC.js` set it for
|
|
342
|
+
emoji reactions/edits/invisible messages, while incoming `decryptFailAttributeFromProtobuf` does not
|
|
343
|
+
list `STICKER_ANNOTATION`. `generateWAMessageContent` attaches `messageContextInfo.messageSecret`, matching
|
|
344
|
+
`WAWebE2EProtoGenerator.js` (attaches `messageSecret` whenever `isMsgTypeReportingTokenCompatible`
|
|
345
|
+
holds; `WAWebMessagePluginGenerateReportingTokenContent.js` excludes reaction/reaction_enc/
|
|
346
|
+
event_response/poll_update/revoked/pin/keep-in-chat, not `associatedSticker`). The `<reporting>` node
|
|
347
|
+
is only emitted when `calculateReportingTokenContent` yields non-empty bytes, as in
|
|
348
|
+
`WAWebReportingTokenUtils.js`; whether servers require a reporting token on sticker reactions has not
|
|
349
|
+
been confirmed against live acks. Forwarding a sticker reaction via `{ forward }` strips
|
|
350
|
+
`messageContextInfo` so it forwards as an ordinary sticker.
|
|
351
|
+
|
|
352
|
+
**Verification: Offline.** Protobuf round-trip, future-proof/Lottie unwrapping, LID/PN parent-key
|
|
353
|
+
normalization, relay hints, multi-sticker accumulation, revoke lookup, event-buffer folding, and
|
|
354
|
+
store updates are covered in `test/sticker-reaction.test.js`. No live server send/receive has been
|
|
355
|
+
performed.
|
|
356
|
+
|
|
357
|
+
---
|
|
358
|
+
|
|
309
359
|
## Keeping up with WhatsApp Web
|
|
310
360
|
|
|
311
361
|
```bash
|
package/NOTICE.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
**Zahan Baileys** (`zahan-baileys`) is an independently maintained Baileys
|
|
4
4
|
distribution, maintained by **SAHAN OFC** in **Sri Lanka**.
|
|
5
5
|
|
|
6
|
-
- Version: 1.0.
|
|
6
|
+
- Version: 1.0.1
|
|
7
7
|
- Official website: <https://www.sahanhost.qzz.io>
|
|
8
8
|
- Repository: <https://github.com/Shan-droid770/zahan-baileys>
|
|
9
9
|
|
package/README.md
CHANGED
|
@@ -89,6 +89,7 @@ For questions, collaboration, bug reports, or anything else, reach out through t
|
|
|
89
89
|
| 🖱️ Interactive buttons | Quick reply, URL, copy, call, list/select, location, and other native-flow buttons. |
|
|
90
90
|
| 🧱 Integrated MessageBuilder | `Button`, `ButtonV2`, `Carousel`, `AIRich`, and `Toolkit` all ship in the same package. |
|
|
91
91
|
| 🖼️ Albums | Send several images or videos as a single album message. |
|
|
92
|
+
| 🎭 Sticker reactions | React to chats and groups with static or animated WebP stickers, reuse stickers you already have, and receive additions/removals. |
|
|
92
93
|
| 📢 Channels | Create, follow, edit, react to, and read WhatsApp Channels. |
|
|
93
94
|
| 👥 Groups | Group creation, member management, metadata, descriptions, and more. |
|
|
94
95
|
| 🪪 LID / PN addressing | Supports the newer LID addressing while also exposing the PN/JID alternative WhatsApp provides. |
|
|
@@ -114,6 +115,7 @@ New here? This is the whole library in one view. Each row links to the section t
|
|
|
114
115
|
| Send AI-style cards | `AIRich`, A2UI | [AIRich](#-airich), [A2UI Cards](#-a2ui-cards) |
|
|
115
116
|
| Read rich messages sent by other bots | `readRichMessage` | [Reading Rich Messages Back](#reading-rich-messages-back) |
|
|
116
117
|
| Post several photos as one message | album message | [Album Messages](#-album-messages) |
|
|
118
|
+
| React with a sticker | `sock.sendStickerReaction`, `stickerReact` | [Sticker Reactions](#sticker-reactions) |
|
|
117
119
|
| Manage channels | channel helpers | [Newsletter / Channels](#-newsletter--channels) |
|
|
118
120
|
| Manage groups | `groupCreate`, `groupParticipantsUpdate`, … | [Group Management](#-group-management) |
|
|
119
121
|
| Manage communities | community helpers | [Communities](#-communities) |
|
|
@@ -162,6 +164,7 @@ New here? This is the whole library in one view. Each row links to the section t
|
|
|
162
164
|
- [LID / PN / JID Addressing](#-lid--pn--jid-addressing)
|
|
163
165
|
- [Sending Messages](#-sending-messages)
|
|
164
166
|
- [Sending rate limit](#sending-rate-limit)
|
|
167
|
+
- [Sticker Reactions](#sticker-reactions)
|
|
165
168
|
- [External Ad Reply](#-external-ad-reply)
|
|
166
169
|
- [Rich Link Cards](#-rich-link-cards)
|
|
167
170
|
- [Integrated MessageBuilder](#-integrated-messagebuilder)
|
|
@@ -859,8 +862,8 @@ sock.ev.process(async (events) => {
|
|
|
859
862
|
Important event groups:
|
|
860
863
|
|
|
861
864
|
- **Connection and credentials:** `connection.update`, `creds.update`, `messaging-history.set`, `connection.newMessageCount`.
|
|
862
|
-
- **Messages:** `messages.upsert`, `messages.update`, `messages.delete`, `messages.reaction`, `messages.media-update`, `message-receipt.update`.
|
|
863
|
-
- **View once:** `viewonce.retrieved
|
|
865
|
+
- **Messages:** `messages.upsert`, `messages.update`, `messages.delete`, `messages.reaction`, `messages.sticker-reaction`, `messages.media-update`, `message-receipt.update`.
|
|
866
|
+
- **View once:** `viewonce.unavailable` when WhatsApp withholds a live view-once payload from this companion; `viewonce.retrieved` and `viewonce.failed` when the retrieval listener opens or cannot open a view-once message.
|
|
864
867
|
- **Chats and contacts:** `chats.upsert`, `chats.update`, `chats.delete`, `contacts.upsert`, `contacts.update`, `presence.update`.
|
|
865
868
|
- **Groups and communities:** `groups.upsert`, `groups.update`, `group-participants.update`, `group.join-request`, `communities.update`.
|
|
866
869
|
- **Channels:** `newsletter.reaction`, `newsletter.view`, `newsletter-participants.update`, `newsletter-settings.update`.
|
|
@@ -1084,6 +1087,59 @@ const stream = await sock.downloadSoundStickerAudio(msg, 'stream')
|
|
|
1084
1087
|
|
|
1085
1088
|
The native audio field is preserved when the message is normalized. For caller-supplied Ogg/Opus, pass `seconds` if you already know its duration; otherwise the library attempts metadata detection. `sendMessage(jid, { soundSticker: { video, ... } })` is also supported.
|
|
1086
1089
|
|
|
1090
|
+
### Sticker Reactions
|
|
1091
|
+
|
|
1092
|
+
React to any message in a 1:1 chat or group with a static or animated WebP sticker. Wire format follows WA Web `2.3000.1057574009`: a normal `stickerMessage` carrying `messageContextInfo.messageAssociation` with `associationType: 11` (`STICKER_ANNOTATION`) and `parentMessageKey`. WhatsApp Web parses sticker reactions itself but does not originate them (mobile clients do), so live server delivery has **not** been verified — see [EXPERIMENTAL.md](EXPERIMENTAL.md).
|
|
1093
|
+
|
|
1094
|
+
```js
|
|
1095
|
+
// Helper: Buffer, file path, { url }, or stream
|
|
1096
|
+
const reaction = await sock.sendStickerReaction(jid, msg, { url: './laugh.webp' })
|
|
1097
|
+
|
|
1098
|
+
// Same via sendMessage — `remoteJid` on `key` defaults to `jid`
|
|
1099
|
+
await sock.sendMessage(jid, {
|
|
1100
|
+
stickerReact: {
|
|
1101
|
+
key: msg.key,
|
|
1102
|
+
sticker: { url: './fire.webp' },
|
|
1103
|
+
isAnimated: false,
|
|
1104
|
+
emojis: ['🔥'],
|
|
1105
|
+
accessibilityLabel: 'Fire sticker'
|
|
1106
|
+
}
|
|
1107
|
+
})
|
|
1108
|
+
|
|
1109
|
+
// `react` with sticker media also works; `react: { key, text: '🔥' }` still sends an emoji reaction
|
|
1110
|
+
await sock.sendMessage(jid, {
|
|
1111
|
+
react: { key: msg.key, sticker: { url: './party.webp' } }
|
|
1112
|
+
})
|
|
1113
|
+
|
|
1114
|
+
// Reuse an already-received or uploaded sticker without re-uploading
|
|
1115
|
+
const existingSticker = msg.message?.stickerMessage // or an IStickerMessage with directPath + mediaKey + hashes
|
|
1116
|
+
if (existingSticker) {
|
|
1117
|
+
await sock.sendStickerReaction(jid, targetMsg, existingSticker)
|
|
1118
|
+
}
|
|
1119
|
+
```
|
|
1120
|
+
|
|
1121
|
+
- **Receiving:** `isRealMessage()` returns `false` for sticker reactions, so they don't become chat previews or unread counts. `processMessage` normalizes `parentMessageKey` (LID/PN and 1:1 `fromMe`) and emits `messages.sticker-reaction`:
|
|
1122
|
+
|
|
1123
|
+
```js
|
|
1124
|
+
sock.ev.on('messages.sticker-reaction', (updates) => {
|
|
1125
|
+
for (const { key, stickerReaction } of updates) {
|
|
1126
|
+
// key = parent message key; stickerReaction.key = this tap's own message key
|
|
1127
|
+
if (stickerReaction.revoked) console.log('Removed sticker from', key.id)
|
|
1128
|
+
else console.log('Sticker added:', stickerReaction.stickerMessage?.directPath)
|
|
1129
|
+
}
|
|
1130
|
+
})
|
|
1131
|
+
```
|
|
1132
|
+
|
|
1133
|
+
- **Multiple per sender:** unlike emoji reactions, one user can attach several stickers (including duplicates) to the same message. Bookkeeping is keyed by each sticker reaction's own `key.id`, not by sender.
|
|
1134
|
+
- **Helpers & bookkeeping:** `getStickerReaction(msgOrContent)` and `isStickerReactionMessage(msgOrContent)` unwrap future-proof and `lottieStickerMessage` wrappers. `updateMessageWithStickerReaction(parentMsg, stickerReaction)` maintains `parentMsg.stickerReactions` (plain JS array on the in-memory message, folded automatically by the event buffer and `makeInMemoryStore`).
|
|
1135
|
+
- **Removing your sticker reaction:** revoke the sticker reaction message's **own** key via `{ delete: reaction.key }`, matching `WAWebRevoke.js` (`fromMe` + `sender_revoke` allowed outside the revoke window for `STICKER_ANNOTATION`):
|
|
1136
|
+
|
|
1137
|
+
```js
|
|
1138
|
+
await sock.sendMessage(jid, { delete: reaction.key })
|
|
1139
|
+
```
|
|
1140
|
+
|
|
1141
|
+
- **Limitations:** not supported in newsletters or `status@broadcast`. Sticker media is not re-encoded — supply a valid `.webp` (animated WebP supported).
|
|
1142
|
+
|
|
1087
1143
|
### Location
|
|
1088
1144
|
|
|
1089
1145
|
```js
|
|
@@ -2799,14 +2855,24 @@ feature stores that payload when someone reacts with **any emoji** or replies to
|
|
|
2799
2855
|
default (`viewOnceRetrieval: true`) and uses a bounded, 24-hour cache, so it does not grow with
|
|
2800
2856
|
traffic.
|
|
2801
2857
|
|
|
2802
|
-
**
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
`
|
|
2808
|
-
|
|
2809
|
-
|
|
2858
|
+
**WhatsApp companion restriction (current protocol):** WhatsApp now withholds new incoming view-once
|
|
2859
|
+
payloads from Web-class companions. Instead of `<enc>` with the media and `mediaKey`, the stanza
|
|
2860
|
+
carries `<unavailable type="view_once"/>`. WhatsApp Web itself renders *"You received a view once
|
|
2861
|
+
photo/video/voice message. For added privacy, you can only open it on your phone."*
|
|
2862
|
+
(`WAWebViewOnceSunset.react`), skips placeholder-resend for `view_once_unavailable_fanout`
|
|
2863
|
+
(`WAWebNonMessageDataRequestPlaceholderMessageResendUtils.js`), and `WACompanionReg.pb` has no
|
|
2864
|
+
pairing capability flag for it. **No version bump, browser spoof, media retry, or re-upload request
|
|
2865
|
+
can recover a withheld view-once payload.** Retrieval still works whenever the payload and `mediaKey`
|
|
2866
|
+
were actually delivered (for example, already-cached messages or own-device payloads), and sending
|
|
2867
|
+
`viewOnce: true` is unaffected.
|
|
2868
|
+
|
|
2869
|
+
When `<unavailable type="view_once"/>` arrives, zahan-baileys acks it positively without sending
|
|
2870
|
+
Signal retry receipts, placeholder resends, or NACKs (matching `WAWebHandleMsgV2`), marks
|
|
2871
|
+
`key.isViewOnce = true` and `unavailableType = 'view_once'`, delivers the stub through
|
|
2872
|
+
`messages.upsert`, and emits `viewonce.unavailable` once for live (`notify`) messages.
|
|
2873
|
+
`downloadViewOnce` rejects with status `422` and `error.data.reason === 'view-once-payload-unavailable'`,
|
|
2874
|
+
and reacting/replying to a remembered withheld stub emits `viewonce.failed` with that same error
|
|
2875
|
+
instead of failing silently. Use `isUnavailableViewOnceMessage(msg)` to detect these stubs directly.
|
|
2810
2876
|
|
|
2811
2877
|
```js
|
|
2812
2878
|
const socket = makeWASocket({
|
|
@@ -2823,21 +2889,30 @@ const socket = makeWASocket({
|
|
|
2823
2889
|
singleUse: false,
|
|
2824
2890
|
recover: true, // re-request media WhatsApp has already expired
|
|
2825
2891
|
downloadOptions: {}, // passed to the downloader untouched
|
|
2826
|
-
onRetrieved: ({ key, type, mimetype }) => console.log('opened', key.id, type)
|
|
2892
|
+
onRetrieved: ({ key, type, mimetype }) => console.log('opened', key.id, type),
|
|
2893
|
+
onUnavailable: ({ key, chat }) => console.log('withheld by WhatsApp companion policy', chat, key.id)
|
|
2827
2894
|
}
|
|
2828
2895
|
})
|
|
2829
2896
|
```
|
|
2830
2897
|
|
|
2831
2898
|
```js
|
|
2832
|
-
// disable
|
|
2899
|
+
// disable the react/reply auto-resend listener entirely (viewonce.unavailable still fires)
|
|
2833
2900
|
makeWASocket({ auth: state, viewOnceRetrieval: false })
|
|
2834
2901
|
```
|
|
2835
2902
|
|
|
2836
|
-
Listen for
|
|
2903
|
+
Listen for events instead of using callbacks:
|
|
2837
2904
|
|
|
2838
2905
|
```js
|
|
2839
2906
|
socket.ev.on('viewonce.retrieved', ({ key, chat, type }) => console.log(chat, key.id, type))
|
|
2840
2907
|
socket.ev.on('viewonce.failed', ({ key, error }) => console.log('could not open', key.id, error.message))
|
|
2908
|
+
|
|
2909
|
+
// Typical bot response under the current companion policy: ask for a normal resend or alert the owner
|
|
2910
|
+
socket.ev.on('viewonce.unavailable', async ({ key, chat }) => {
|
|
2911
|
+
if (key.fromMe) return
|
|
2912
|
+
await socket.sendMessage(chat, {
|
|
2913
|
+
text: 'WhatsApp only delivers view-once media to phones now. Please resend it as a normal photo/video.'
|
|
2914
|
+
})
|
|
2915
|
+
})
|
|
2841
2916
|
```
|
|
2842
2917
|
|
|
2843
2918
|
Open media yourself:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zahan-baileys",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Zahan Baileys — a modern WhatsApp Multi-Device library for Node.js with an integrated MessageBuilder, interactive messages, channels and VoIP support. Maintained by SAHAN OFC in Sri Lanka.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"types": "src/index.d.ts",
|
package/src/Socket/index.js
CHANGED
|
@@ -17,6 +17,7 @@ import { applyPerformanceProfileConfig, createPerformanceManager } from '../Util
|
|
|
17
17
|
import { bindChatTheme } from '../Utils/chat-theme.js';
|
|
18
18
|
import { bindPaymentActions } from '../Utils/payment-send.js';
|
|
19
19
|
import { createSessionAutoBackup } from '../Utils/session-auto-backup.js';
|
|
20
|
+
import { createPluginManager, collectSocketDiagnostics } from '../Utils/plugins.js';
|
|
20
21
|
import { makeCommunitiesSocket } from './communities.js';
|
|
21
22
|
|
|
22
23
|
const makeWASocket = (config) => {
|
|
@@ -160,6 +161,20 @@ const makeWASocket = (config) => {
|
|
|
160
161
|
sock.sendVideoSoundSticker = (jid, video, soundStickerOptions = {}, sendOptions = {}) => sock.sendMessage(jid, {
|
|
161
162
|
soundSticker: { ...soundStickerOptions, video }
|
|
162
163
|
}, sendOptions);
|
|
164
|
+
sock.sendStickerReaction = (jid, target, sticker, sendOptions = {}) => {
|
|
165
|
+
let stickerReact;
|
|
166
|
+
if (sticker && typeof sticker === 'object' && ('sticker' in sticker || 'stickerMessage' in sticker) && !('directPath' in sticker && 'mediaKey' in sticker)) {
|
|
167
|
+
stickerReact = { ...sticker, key: target };
|
|
168
|
+
}
|
|
169
|
+
else if (sticker && typeof sticker === 'object' && ((sticker.directPath && sticker.mediaKey) || (sticker.key && sticker.message))) {
|
|
170
|
+
stickerReact = { stickerMessage: sticker, key: target };
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
stickerReact = { sticker, key: target };
|
|
174
|
+
}
|
|
175
|
+
return sock.sendMessage(jid, { stickerReact }, sendOptions);
|
|
176
|
+
};
|
|
177
|
+
sock.reactWithSticker = sock.sendStickerReaction;
|
|
163
178
|
sock.downloadSoundStickerAudio = (message, type = 'buffer', options = {}, helperOptions = {}) => {
|
|
164
179
|
const audioMessage = getSoundStickerAudioMessage(message?.message ?? message);
|
|
165
180
|
if (!audioMessage) {
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
/* Zahan Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
|
|
2
|
+
export function getUnavailableMessageDisposition(node: any, msg: any): {
|
|
3
|
+
action: 'ack' | 'placeholder-resend';
|
|
4
|
+
reason: string;
|
|
5
|
+
emitUpsert: boolean;
|
|
6
|
+
} | null;
|
|
2
7
|
export function makeMessagesRecvSocket(config: any): {
|
|
3
8
|
sendMessageAck: (node: any, errorCode: any) => Promise<void>;
|
|
4
9
|
sendRetryRequest: (node: any, forceIncludeKeys?: boolean, decryptionError?: Record<string, any>) => Promise<void>;
|
|
@@ -17,6 +17,23 @@ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcemen
|
|
|
17
17
|
function isValidEnforcementType(value) {
|
|
18
18
|
return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
|
|
19
19
|
}
|
|
20
|
+
export const getUnavailableMessageDisposition = (node, msg) => {
|
|
21
|
+
const unavailableNode = getBinaryNodeChild(node, 'unavailable');
|
|
22
|
+
if (!unavailableNode || msg?.message) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const type = unavailableNode.attrs?.type;
|
|
26
|
+
if (type === 'view_once' || msg?.key?.isViewOnce === true) {
|
|
27
|
+
return { action: 'ack', reason: 'view_once', emitUpsert: true };
|
|
28
|
+
}
|
|
29
|
+
if (type === 'hosted' || type === 'sender_drop' || unavailableNode.attrs?.hosted === 'true') {
|
|
30
|
+
return { action: 'ack', reason: type || 'hosted', emitUpsert: false };
|
|
31
|
+
}
|
|
32
|
+
if (!getBinaryNodeChild(node, 'enc')) {
|
|
33
|
+
return { action: 'placeholder-resend', reason: type || 'fanout', emitUpsert: false };
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
};
|
|
20
37
|
export const makeMessagesRecvSocket = (config) => {
|
|
21
38
|
const { logger, retryRequestDelayMs, maxMsgRetryCount, ackRetryDelayMs, maxAckRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
|
|
22
39
|
const sock = makeMessagesSocket(config);
|
|
@@ -1340,7 +1357,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1340
1357
|
};
|
|
1341
1358
|
const handleMessage = async (node) => {
|
|
1342
1359
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1343
|
-
|
|
1344
1360
|
if (encNode?.attrs.type === 'msmsg') {
|
|
1345
1361
|
logger.debug({ key: node.attrs.key }, 'ignored msmsg');
|
|
1346
1362
|
await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
|
|
@@ -1376,17 +1392,16 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1376
1392
|
acked = true;
|
|
1377
1393
|
return sendMessageAck(node, NACK_REASONS.ParsingError);
|
|
1378
1394
|
}
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
|
|
1387
|
-
acked = true;
|
|
1388
|
-
return sendMessageAck(node);
|
|
1395
|
+
const unavailableDisposition = getUnavailableMessageDisposition(node, msg);
|
|
1396
|
+
if (unavailableDisposition?.action === 'ack') {
|
|
1397
|
+
logger.debug({ msgId: msg.key.id, reason: unavailableDisposition.reason }, 'acking unavailable message without retry');
|
|
1398
|
+
acked = true;
|
|
1399
|
+
await sendMessageAck(node);
|
|
1400
|
+
if (!unavailableDisposition.emitUpsert) {
|
|
1401
|
+
return;
|
|
1389
1402
|
}
|
|
1403
|
+
}
|
|
1404
|
+
else if (unavailableDisposition?.action === 'placeholder-resend' || msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
|
|
1390
1405
|
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1391
1406
|
if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
|
|
1392
1407
|
logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
|
|
@@ -11,6 +11,15 @@ export function buildMemberLabelMessage(jid: string, memberLabel?: string | null
|
|
|
11
11
|
content: undefined;
|
|
12
12
|
};
|
|
13
13
|
};
|
|
14
|
+
export function buildStickerReactionRelayHints(message: any): {
|
|
15
|
+
metaAttrs: {
|
|
16
|
+
message_association_type: 'sticker_annotation';
|
|
17
|
+
'decrypt-fail': 'hide';
|
|
18
|
+
};
|
|
19
|
+
encAttrs: {
|
|
20
|
+
'decrypt-fail': 'hide';
|
|
21
|
+
};
|
|
22
|
+
} | null;
|
|
14
23
|
export function makeMessagesSocket(config: any): {
|
|
15
24
|
userDevicesCache: any;
|
|
16
25
|
devicesMutex: {
|
|
@@ -4,7 +4,7 @@ import { Boom } from '@hapi/boom';
|
|
|
4
4
|
import { randomBytes } from 'crypto';
|
|
5
5
|
import { proto } from '../../WAProto/index.js';
|
|
6
6
|
import { DEFAULT_CACHE_LIMITS, DEFAULT_CACHE_TTLS, MAX_OUTBOUND_RESEND_ENTRIES, MEMBER_LABEL_MAX_LENGTH, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
7
|
-
import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getPollOptionHash, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, aiLabelDecision, makeSessionRecovery, MessageRetryManager, shouldApplyAiLabel, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds, withAiLabel } from '../Utils/index.js';
|
|
7
|
+
import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getPollOptionHash, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, aiLabelDecision, isStickerReactionMessage, makeSessionRecovery, MessageRetryManager, shouldApplyAiLabel, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds, withAiLabel } from '../Utils/index.js';
|
|
8
8
|
import { AssociationType } from '../Types/index.js';
|
|
9
9
|
import { makeStatusMentionMessage } from '../Utils/modern-messages.js';
|
|
10
10
|
import { commitSenderKeyDelivery, pickSenderKeyRecipients, senderKeyResetSummary } from '../Utils/sender-key-memory.js';
|
|
@@ -42,6 +42,20 @@ export const buildMemberLabelMessage = (jid, memberLabel) => {
|
|
|
42
42
|
}
|
|
43
43
|
};
|
|
44
44
|
};
|
|
45
|
+
export const buildStickerReactionRelayHints = (message) => {
|
|
46
|
+
if (!isStickerReactionMessage(message)) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
metaAttrs: {
|
|
51
|
+
message_association_type: 'sticker_annotation',
|
|
52
|
+
'decrypt-fail': 'hide'
|
|
53
|
+
},
|
|
54
|
+
encAttrs: {
|
|
55
|
+
'decrypt-fail': 'hide'
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
};
|
|
45
59
|
export const makeMessagesSocket = (config) => {
|
|
46
60
|
const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
|
|
47
61
|
const sock = makeNewsletterSocket(config);
|
|
@@ -506,11 +520,15 @@ export const makeMessagesSocket = (config) => {
|
|
|
506
520
|
await authState.keys.transaction(async () => {
|
|
507
521
|
|
|
508
522
|
const innerMessage = normalizeMessageContent(message);
|
|
523
|
+
const stickerReactionHints = buildStickerReactionRelayHints(innerMessage);
|
|
509
524
|
const mediaType = getMediaType(innerMessage);
|
|
510
525
|
if (mediaType) {
|
|
511
526
|
extraAttrs['mediatype'] = mediaType;
|
|
512
527
|
}
|
|
513
528
|
if (isNewsletter) {
|
|
529
|
+
if (stickerReactionHints) {
|
|
530
|
+
throw new Boom('sticker reactions are not supported in newsletters', { statusCode: 400 });
|
|
531
|
+
}
|
|
514
532
|
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
|
|
515
533
|
const bytes = encodeNewsletterMessage(patched);
|
|
516
534
|
|
|
@@ -563,7 +581,11 @@ export const makeMessagesSocket = (config) => {
|
|
|
563
581
|
|
|
564
582
|
const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
|
|
565
583
|
const isPollUpdate = innerMessage?.pollUpdateMessage;
|
|
566
|
-
|
|
584
|
+
const callerMetaNode = stickerReactionHints && additionalNodes?.find?.(node => node?.tag === 'meta');
|
|
585
|
+
if (callerMetaNode) {
|
|
586
|
+
callerMetaNode.attrs = { ...(callerMetaNode.attrs || {}), ...stickerReactionHints.metaAttrs };
|
|
587
|
+
}
|
|
588
|
+
if (isNeedMetaAttrs || isGroupStatus || isPollUpdate || (stickerReactionHints && !callerMetaNode)) {
|
|
567
589
|
const metaAttrs = {};
|
|
568
590
|
if (isNeedMetaAttrs) {
|
|
569
591
|
metaAttrs.content_type = 'add_on';
|
|
@@ -574,12 +596,18 @@ export const makeMessagesSocket = (config) => {
|
|
|
574
596
|
if (isGroupStatus) {
|
|
575
597
|
metaAttrs.is_group_status = 'true';
|
|
576
598
|
}
|
|
599
|
+
if (stickerReactionHints) {
|
|
600
|
+
Object.assign(metaAttrs, stickerReactionHints.metaAttrs);
|
|
601
|
+
}
|
|
577
602
|
binaryNodeContent.push({
|
|
578
603
|
tag: 'meta',
|
|
579
604
|
attrs: metaAttrs,
|
|
580
605
|
content: undefined
|
|
581
606
|
});
|
|
582
607
|
}
|
|
608
|
+
if (stickerReactionHints) {
|
|
609
|
+
Object.assign(extraAttrs, stickerReactionHints.encAttrs);
|
|
610
|
+
}
|
|
583
611
|
if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
|
|
584
612
|
extraAttrs['decrypt-fail'] = 'hide';
|
|
585
613
|
}
|
|
@@ -5,7 +5,7 @@ import { writeFileSync, readFileSync, existsSync } from 'fs';
|
|
|
5
5
|
import { WAProto } from '../Types/index.js';
|
|
6
6
|
import { LabelAssociationType } from '../Types/LabelAssociation.js';
|
|
7
7
|
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
|
|
8
|
-
import { md5, toNumber, updateMessageWithReceipt, updateMessageWithReaction } from '../Utils/index.js';
|
|
8
|
+
import { isRealMessage, md5, toNumber, updateMessageWithReceipt, updateMessageWithReaction, updateMessageWithStickerReaction } from '../Utils/index.js';
|
|
9
9
|
import { jidDecode, jidNormalizedUser } from '../WABinary/index.js';
|
|
10
10
|
import { makeOrderedDictionary } from './make-ordered-dictionary.js';
|
|
11
11
|
import { ObjectRepository } from './object-repository.js';
|
|
@@ -184,7 +184,7 @@ export const makeInMemoryStore = (config = {}) => {
|
|
|
184
184
|
const list = assertMessageList(jid);
|
|
185
185
|
list.upsert(msg, 'append');
|
|
186
186
|
trimMessageList(list);
|
|
187
|
-
if (type === 'notify' && !chats.get(jid)) {
|
|
187
|
+
if (type === 'notify' && !chats.get(jid) && isRealMessage(msg)) {
|
|
188
188
|
ev.emit('chats.upsert', [
|
|
189
189
|
{
|
|
190
190
|
id: jid,
|
|
@@ -292,6 +292,15 @@ export const makeInMemoryStore = (config = {}) => {
|
|
|
292
292
|
}
|
|
293
293
|
}
|
|
294
294
|
});
|
|
295
|
+
ev.on('messages.sticker-reaction', (stickerReactions) => {
|
|
296
|
+
for (const { key, stickerReaction } of stickerReactions) {
|
|
297
|
+
const obj = messages[jidNormalizedUser(key.remoteJidAlt || key.remoteJid)];
|
|
298
|
+
const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
|
|
299
|
+
if (msg) {
|
|
300
|
+
updateMessageWithStickerReaction(msg, stickerReaction);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
});
|
|
295
304
|
};
|
|
296
305
|
const toJSON = () => ({
|
|
297
306
|
chats,
|
package/src/Types/Content.d.ts
CHANGED
|
@@ -51,7 +51,9 @@ export interface AnyMessageContent {
|
|
|
51
51
|
react?: {
|
|
52
52
|
text: string;
|
|
53
53
|
key: any;
|
|
54
|
-
|
|
54
|
+
senderTimestampMs?: number;
|
|
55
|
+
} | StickerReactionContent;
|
|
56
|
+
stickerReact?: StickerReactionContent;
|
|
55
57
|
delete?: any;
|
|
56
58
|
edit?: any;
|
|
57
59
|
forward?: any;
|
|
@@ -63,6 +65,48 @@ export interface AnyMessageContent {
|
|
|
63
65
|
[key: string]: any;
|
|
64
66
|
}
|
|
65
67
|
|
|
68
|
+
export interface StickerReactionContent {
|
|
69
|
+
/** Target message key, or the full target WAMessage. `remoteJid` defaults to the chat JID. */
|
|
70
|
+
key: any;
|
|
71
|
+
/** WebP sticker bytes, file path, `{ url }`, or stream. Uploaded unless `stickerMessage` reuses existing media. */
|
|
72
|
+
sticker?: any;
|
|
73
|
+
/** Already-uploaded sticker metadata (or a sticker WAMessage) to reuse without re-uploading. */
|
|
74
|
+
stickerMessage?: any;
|
|
75
|
+
/** Shorthand media URL when `sticker` is omitted. */
|
|
76
|
+
url?: string;
|
|
77
|
+
mimetype?: string;
|
|
78
|
+
width?: number;
|
|
79
|
+
height?: number;
|
|
80
|
+
isAnimated?: boolean;
|
|
81
|
+
isAvatar?: boolean;
|
|
82
|
+
isAiSticker?: boolean;
|
|
83
|
+
isLottie?: boolean;
|
|
84
|
+
pngThumbnail?: Uint8Array;
|
|
85
|
+
firstFrameLength?: number;
|
|
86
|
+
firstFrameSidecar?: Uint8Array;
|
|
87
|
+
accessibilityLabel?: string;
|
|
88
|
+
emojis?: string | string[];
|
|
89
|
+
stickerSentTs?: number;
|
|
90
|
+
[key: string]: any;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface StickerReaction {
|
|
94
|
+
/** Key of the sticker reaction message itself (unique per tap, multiple per author allowed). */
|
|
95
|
+
key: any;
|
|
96
|
+
parentKey?: any;
|
|
97
|
+
stickerMessage?: import('../../WAProto/index.js').proto.Message.IStickerMessage;
|
|
98
|
+
associationType?: number;
|
|
99
|
+
messageIndex?: number;
|
|
100
|
+
senderTimestampMs?: number;
|
|
101
|
+
revoked?: boolean;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface StickerReactionUpdate {
|
|
105
|
+
/** Key of the parent message that received the sticker. */
|
|
106
|
+
key: any;
|
|
107
|
+
stickerReaction: StickerReaction;
|
|
108
|
+
}
|
|
109
|
+
|
|
66
110
|
export interface SoundStickerContent {
|
|
67
111
|
/** Existing WebP sticker bytes/path/URL. Optional when `video` is supplied. */
|
|
68
112
|
sticker?: any;
|
|
@@ -16,7 +16,9 @@ export function decodeMessageNode(stanza: any, meId: any, meLid: any): {
|
|
|
16
16
|
participantAlt: any;
|
|
17
17
|
participantUsername: any;
|
|
18
18
|
addressingMode: any;
|
|
19
|
+
isViewOnce?: boolean;
|
|
19
20
|
};
|
|
21
|
+
unavailableType?: string;
|
|
20
22
|
category: any;
|
|
21
23
|
messageTimestamp: number;
|
|
22
24
|
pushName: any;
|
|
@@ -39,6 +41,7 @@ export function extractNewsletterMessageMeta(stanza: any): {
|
|
|
39
41
|
originalTimestamp?: number;
|
|
40
42
|
} | undefined;
|
|
41
43
|
export const NO_MESSAGE_FOUND_ERROR_TEXT: "Message absent from node";
|
|
44
|
+
export const VIEW_ONCE_UNAVAILABLE_TEXT: "View-once payload unavailable from WhatsApp companion device";
|
|
42
45
|
export const MISSING_KEYS_ERROR_TEXT: "Key used already or never filled";
|
|
43
46
|
export const ACCOUNT_RESTRICTED_TEXT: "Your account has been restricted";
|
|
44
47
|
export namespace DECRYPTION_RETRY_CONFIG {
|
|
@@ -88,7 +91,9 @@ export function decryptMessageNode(stanza: any, meId: any, meLid: any, repositor
|
|
|
88
91
|
participantAlt: any;
|
|
89
92
|
participantUsername: any;
|
|
90
93
|
addressingMode: any;
|
|
94
|
+
isViewOnce?: boolean;
|
|
91
95
|
};
|
|
96
|
+
unavailableType?: string;
|
|
92
97
|
category: any;
|
|
93
98
|
messageTimestamp: number;
|
|
94
99
|
pushName: any;
|
|
@@ -79,6 +79,7 @@ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJi
|
|
|
79
79
|
}
|
|
80
80
|
};
|
|
81
81
|
export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
|
|
82
|
+
export const VIEW_ONCE_UNAVAILABLE_TEXT = 'View-once payload unavailable from WhatsApp companion device';
|
|
82
83
|
export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
|
|
83
84
|
export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
|
|
84
85
|
|
|
@@ -280,8 +281,11 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
|
|
|
280
281
|
logger?.warn?.({ err, key: fullMessage.key }, 'could not read the verified business name, leaving it unset');
|
|
281
282
|
}
|
|
282
283
|
}
|
|
283
|
-
if (tag === 'unavailable'
|
|
284
|
-
fullMessage.
|
|
284
|
+
if (tag === 'unavailable') {
|
|
285
|
+
fullMessage.unavailableType = attrs.type || (attrs.hosted === 'true' ? 'hosted' : 'fanout');
|
|
286
|
+
if (attrs.type === 'view_once') {
|
|
287
|
+
fullMessage.key.isViewOnce = true;
|
|
288
|
+
}
|
|
285
289
|
}
|
|
286
290
|
if (attrs.count && tag === 'enc') {
|
|
287
291
|
fullMessage.retryCount = Number(attrs.count);
|
|
@@ -363,7 +367,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
|
|
|
363
367
|
if (!decryptables) {
|
|
364
368
|
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
|
|
365
369
|
fullMessage.messageStubParameters = [fullMessage.key?.isViewOnce
|
|
366
|
-
?
|
|
370
|
+
? VIEW_ONCE_UNAVAILABLE_TEXT
|
|
367
371
|
: NO_MESSAGE_FOUND_ERROR_TEXT];
|
|
368
372
|
}
|
|
369
373
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import EventEmitter from 'events';
|
|
3
3
|
import { WAMessageStatus } from '../Types/index.js';
|
|
4
4
|
import { trimUndefined } from './generics.js';
|
|
5
|
-
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js';
|
|
5
|
+
import { getStickerReaction, updateMessageWithReaction, updateMessageWithReceipt, updateMessageWithStickerReaction } from './messages.js';
|
|
6
6
|
import { isRealMessage, shouldIncrementChatUnread } from './process-message.js';
|
|
7
7
|
const BUFFERABLE_EVENT = [
|
|
8
8
|
'messaging-history.set',
|
|
@@ -15,6 +15,7 @@ const BUFFERABLE_EVENT = [
|
|
|
15
15
|
'messages.update',
|
|
16
16
|
'messages.delete',
|
|
17
17
|
'messages.reaction',
|
|
18
|
+
'messages.sticker-reaction',
|
|
18
19
|
'message-receipt.update',
|
|
19
20
|
'groups.update'
|
|
20
21
|
];
|
|
@@ -253,6 +254,7 @@ const makeBufferData = () => {
|
|
|
253
254
|
messageUpserts: {},
|
|
254
255
|
messageUpdates: {},
|
|
255
256
|
messageReactions: {},
|
|
257
|
+
messageStickerReactions: {},
|
|
256
258
|
messageDeletes: {},
|
|
257
259
|
messageReceipts: {},
|
|
258
260
|
groupUpdates: {}
|
|
@@ -453,6 +455,12 @@ eventData, logger) {
|
|
|
453
455
|
Object.assign(message, data.messageUpdates[key].update);
|
|
454
456
|
delete data.messageUpdates[key];
|
|
455
457
|
}
|
|
458
|
+
if (data.messageStickerReactions[key]) {
|
|
459
|
+
for (const stickerReaction of data.messageStickerReactions[key].stickerReactions) {
|
|
460
|
+
updateMessageWithStickerReaction(message, stickerReaction);
|
|
461
|
+
}
|
|
462
|
+
delete data.messageStickerReactions[key];
|
|
463
|
+
}
|
|
456
464
|
if (data.historySets.messages[key]) {
|
|
457
465
|
data.historySets.messages[key] = message;
|
|
458
466
|
}
|
|
@@ -470,6 +478,15 @@ eventData, logger) {
|
|
|
470
478
|
const keyStr = stringifyMessageKey(key);
|
|
471
479
|
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
|
|
472
480
|
if (existing) {
|
|
481
|
+
if (update.message === null) {
|
|
482
|
+
const revokedSticker = getStickerReaction(existing);
|
|
483
|
+
if (revokedSticker) {
|
|
484
|
+
bufferStickerReaction(revokedSticker.parentKey, {
|
|
485
|
+
key: existing.key || key,
|
|
486
|
+
revoked: true
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
}
|
|
473
490
|
Object.assign(existing, update);
|
|
474
491
|
|
|
475
492
|
if (update.status === WAMessageStatus.READ && !key.fromMe) {
|
|
@@ -518,6 +535,11 @@ eventData, logger) {
|
|
|
518
535
|
}
|
|
519
536
|
}
|
|
520
537
|
break;
|
|
538
|
+
case 'messages.sticker-reaction':
|
|
539
|
+
for (const { key, stickerReaction } of eventData) {
|
|
540
|
+
bufferStickerReaction(key, stickerReaction);
|
|
541
|
+
}
|
|
542
|
+
break;
|
|
521
543
|
case 'message-receipt.update':
|
|
522
544
|
const receipts = eventData;
|
|
523
545
|
for (const { key, receipt } of receipts) {
|
|
@@ -545,6 +567,22 @@ eventData, logger) {
|
|
|
545
567
|
default:
|
|
546
568
|
throw new Error(`"${event}" cannot be buffered`);
|
|
547
569
|
}
|
|
570
|
+
function bufferStickerReaction(key, stickerReaction) {
|
|
571
|
+
const keyStr = stringifyMessageKey(key);
|
|
572
|
+
const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
|
|
573
|
+
if (existing) {
|
|
574
|
+
updateMessageWithStickerReaction(existing, stickerReaction);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const bucket = data.messageStickerReactions[keyStr] ||
|
|
578
|
+
(data.messageStickerReactions[keyStr] = { key, stickerReactions: [] });
|
|
579
|
+
const reactionId = stickerReaction?.key?.id;
|
|
580
|
+
const hadPending = bucket.stickerReactions.some(entry => entry?.key?.id === reactionId);
|
|
581
|
+
updateMessageWithStickerReaction(bucket, stickerReaction);
|
|
582
|
+
if (stickerReaction.revoked && !hadPending) {
|
|
583
|
+
bucket.stickerReactions.push(stickerReaction);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
548
586
|
function absorbingChatUpdate(existing) {
|
|
549
587
|
const chatId = existing.id || '';
|
|
550
588
|
const update = data.chatUpdates[chatId];
|
|
@@ -625,6 +663,11 @@ function consolidateEvents(data) {
|
|
|
625
663
|
if (messageReactionList.length) {
|
|
626
664
|
map['messages.reaction'] = messageReactionList;
|
|
627
665
|
}
|
|
666
|
+
const messageStickerReactionList = Object.values(data.messageStickerReactions)
|
|
667
|
+
.flatMap(({ key, stickerReactions }) => stickerReactions.map(stickerReaction => ({ key, stickerReaction })));
|
|
668
|
+
if (messageStickerReactionList.length) {
|
|
669
|
+
map['messages.sticker-reaction'] = messageStickerReactionList;
|
|
670
|
+
}
|
|
628
671
|
const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
|
|
629
672
|
if (messageReceiptList.length) {
|
|
630
673
|
map['message-receipt.update'] = messageReceiptList;
|
package/src/Utils/messages.d.ts
CHANGED
|
@@ -54,6 +54,10 @@ export function extractMessageContent(content: any): any;
|
|
|
54
54
|
export function getDevice(id: any): "unknown" | "android" | "web" | "ios" | "desktop";
|
|
55
55
|
export function updateMessageWithReceipt(msg: any, receipt: any): void;
|
|
56
56
|
export function updateMessageWithReaction(msg: any, reaction: any): void;
|
|
57
|
+
export function normalizeStickerReactionKey(target: any, fallbackJid?: string): proto.MessageKey;
|
|
58
|
+
export function getStickerReaction(messageOrContent: any): import('../Types/Content.js').StickerReaction | undefined;
|
|
59
|
+
export function isStickerReactionMessage(messageOrContent: any): boolean;
|
|
60
|
+
export function updateMessageWithStickerReaction(msg: any, stickerReaction: import('../Types/Content.js').StickerReaction): void;
|
|
57
61
|
export function updateMessageWithPollUpdate(msg: any, update: any): void;
|
|
58
62
|
export function updateMessageWithEventResponse(msg: any, update: any): void;
|
|
59
63
|
export function aggregateMessageKeysNotFromMe(keys: any): any[];
|
package/src/Utils/messages.js
CHANGED
|
@@ -8,7 +8,7 @@ import { BIZ_BOT_SUPPORT_PAYLOAD, CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_U
|
|
|
8
8
|
import { ButtonHeaderType, ButtonType, CarouselCardType, ListType, WAMessageStatus, WAProto } from '../Types/index.js';
|
|
9
9
|
import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
|
|
10
10
|
import { sha256 } from './crypto.js';
|
|
11
|
-
import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
|
|
11
|
+
import { generateMessageIDV2, getKeyAuthor, toNumber, unixTimestampSeconds } from './generics.js';
|
|
12
12
|
import { downloadContentFromMessage, encryptedStream, extractImageThumb, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
|
|
13
13
|
import { createVideoSoundSticker } from './sound-sticker.js';
|
|
14
14
|
import { shouldIncludeReportingToken } from './reporting-utils.js';
|
|
@@ -680,7 +680,8 @@ export const generateForwardMessageContent = (message, forceForward) => {
|
|
|
680
680
|
|
|
681
681
|
content = normalizeMessageContent(content);
|
|
682
682
|
content = proto.Message.decode(proto.Message.encode(content).finish());
|
|
683
|
-
|
|
683
|
+
delete content.messageContextInfo;
|
|
684
|
+
let key = getContentType(content) || Object.keys(content)[0];
|
|
684
685
|
let score = content?.[key]?.contextInfo?.forwardingScore || 0;
|
|
685
686
|
score += message.key.fromMe && !forceForward ? 0 : 1;
|
|
686
687
|
if (key === 'conversation') {
|
|
@@ -732,6 +733,132 @@ export const hasValidCarouselHeader = (message) => {
|
|
|
732
733
|
message.videoMessage ||
|
|
733
734
|
message.productMessage);
|
|
734
735
|
};
|
|
736
|
+
|
|
737
|
+
const STICKER_MEDIA_OPTION_KEYS = [
|
|
738
|
+
'mimetype',
|
|
739
|
+
'width',
|
|
740
|
+
'height',
|
|
741
|
+
'isAnimated',
|
|
742
|
+
'isAvatar',
|
|
743
|
+
'isAiSticker',
|
|
744
|
+
'isLottie',
|
|
745
|
+
'pngThumbnail',
|
|
746
|
+
'firstFrameLength',
|
|
747
|
+
'firstFrameSidecar'
|
|
748
|
+
];
|
|
749
|
+
|
|
750
|
+
const normalizeStickerEmojis = (emojis) => {
|
|
751
|
+
if (emojis === undefined || emojis === null) {
|
|
752
|
+
return undefined;
|
|
753
|
+
}
|
|
754
|
+
if (Array.isArray(emojis)) {
|
|
755
|
+
return emojis.map(String).filter(Boolean).join(' ');
|
|
756
|
+
}
|
|
757
|
+
return String(emojis);
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
export const normalizeStickerReactionKey = (target, fallbackJid) => {
|
|
761
|
+
const key = target?.key && typeof target.key === 'object' ? target.key : target;
|
|
762
|
+
if (!key || typeof key !== 'object' || !String(key.id ?? '').trim()) {
|
|
763
|
+
throw new Boom('sticker reaction target key needs an id', { statusCode: 400 });
|
|
764
|
+
}
|
|
765
|
+
const remoteJid = jidNormalizedUser(key.remoteJid || fallbackJid || '');
|
|
766
|
+
if (!remoteJid) {
|
|
767
|
+
throw new Boom('sticker reaction target key needs a remoteJid', { statusCode: 400 });
|
|
768
|
+
}
|
|
769
|
+
if (isJidNewsletter(remoteJid) || isJidStatusBroadcast(remoteJid)) {
|
|
770
|
+
throw new Boom('sticker reactions are not supported in newsletters or status broadcasts', { statusCode: 400 });
|
|
771
|
+
}
|
|
772
|
+
const participant = key.participant || target?.participant;
|
|
773
|
+
return WAProto.MessageKey.create(trimEmptyValues({
|
|
774
|
+
remoteJid,
|
|
775
|
+
fromMe: !!key.fromMe,
|
|
776
|
+
id: String(key.id),
|
|
777
|
+
participant: participant ? jidNormalizedUser(participant) : undefined
|
|
778
|
+
}));
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
const unwrapStickerMessage = (value) => {
|
|
782
|
+
if (!value || typeof value !== 'object') {
|
|
783
|
+
return undefined;
|
|
784
|
+
}
|
|
785
|
+
if (value.key && value.message) {
|
|
786
|
+
return normalizeMessageContent(value.message)?.stickerMessage;
|
|
787
|
+
}
|
|
788
|
+
if (value.stickerMessage) {
|
|
789
|
+
return normalizeMessageContent(value)?.stickerMessage;
|
|
790
|
+
}
|
|
791
|
+
return value;
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
const prepareStickerReactionMessage = async (input, options) => {
|
|
795
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
796
|
+
throw new Boom('stickerReact must be an object with key and sticker', { statusCode: 400 });
|
|
797
|
+
}
|
|
798
|
+
const chatJid = options?.jid ? jidNormalizedUser(options.jid) : undefined;
|
|
799
|
+
if (chatJid && (isJidNewsletter(chatJid) || isJidStatusBroadcast(chatJid))) {
|
|
800
|
+
throw new Boom('sticker reactions are not supported in newsletters or status broadcasts', { statusCode: 400 });
|
|
801
|
+
}
|
|
802
|
+
const parentMessageKey = normalizeStickerReactionKey(input.key ?? input.target, chatJid);
|
|
803
|
+
const directCandidate = input.stickerMessage ?? input.sticker;
|
|
804
|
+
const candidate = unwrapStickerMessage(directCandidate);
|
|
805
|
+
const reuseUploaded = candidate?.directPath && candidate?.mediaKey
|
|
806
|
+
? candidate
|
|
807
|
+
: input.directPath && input.mediaKey
|
|
808
|
+
? input
|
|
809
|
+
: undefined;
|
|
810
|
+
let stickerMessage;
|
|
811
|
+
if (reuseUploaded) {
|
|
812
|
+
if (!reuseUploaded.fileSha256 || !reuseUploaded.fileEncSha256) {
|
|
813
|
+
throw new Boom('reusing an uploaded sticker needs fileSha256 and fileEncSha256', { statusCode: 400 });
|
|
814
|
+
}
|
|
815
|
+
const { contextInfo: _contextInfo, ...media } = reuseUploaded;
|
|
816
|
+
const emojis = normalizeStickerEmojis(input.emojis) ??
|
|
817
|
+
(Array.isArray(media.emojis) ? media.emojis.join(' ') : media.emojis);
|
|
818
|
+
stickerMessage = WAProto.Message.StickerMessage.fromObject(trimEmptyValues({
|
|
819
|
+
...media,
|
|
820
|
+
mimetype: input.mimetype ?? media.mimetype ?? 'image/webp',
|
|
821
|
+
mediaKeyTimestamp: media.mediaKeyTimestamp ?? unixTimestampSeconds(),
|
|
822
|
+
stickerSentTs: input.stickerSentTs ?? Date.now(),
|
|
823
|
+
isAnimated: input.isAnimated ?? media.isAnimated,
|
|
824
|
+
isLottie: input.isLottie ?? media.isLottie,
|
|
825
|
+
accessibilityLabel: input.accessibilityLabel ?? media.accessibilityLabel,
|
|
826
|
+
emojis
|
|
827
|
+
}));
|
|
828
|
+
}
|
|
829
|
+
else {
|
|
830
|
+
const mediaInput = input.sticker ?? (input.url ? { url: input.url } : input.stream ? { stream: input.stream } : undefined);
|
|
831
|
+
if (!mediaInput) {
|
|
832
|
+
throw new Boom('stickerReact needs sticker media (Buffer, path, url or stream) or an uploaded stickerMessage', { statusCode: 400 });
|
|
833
|
+
}
|
|
834
|
+
const mediaOptions = {};
|
|
835
|
+
for (const field of STICKER_MEDIA_OPTION_KEYS) {
|
|
836
|
+
if (input[field] !== undefined) {
|
|
837
|
+
mediaOptions[field] = input[field];
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
const prepared = await prepareWAMessageMedia({ ...mediaOptions, sticker: mediaInput }, options);
|
|
841
|
+
stickerMessage = prepared.stickerMessage;
|
|
842
|
+
stickerMessage.stickerSentTs = input.stickerSentTs ?? Date.now();
|
|
843
|
+
if (input.accessibilityLabel !== undefined && input.accessibilityLabel !== null) {
|
|
844
|
+
stickerMessage.accessibilityLabel = String(input.accessibilityLabel);
|
|
845
|
+
}
|
|
846
|
+
const emojis = normalizeStickerEmojis(input.emojis);
|
|
847
|
+
if (emojis !== undefined) {
|
|
848
|
+
stickerMessage.emojis = emojis;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return {
|
|
852
|
+
stickerMessage,
|
|
853
|
+
messageContextInfo: {
|
|
854
|
+
messageAssociation: WAProto.MessageAssociation.create({
|
|
855
|
+
associationType: WAProto.MessageAssociation.AssociationType.STICKER_ANNOTATION,
|
|
856
|
+
parentMessageKey
|
|
857
|
+
})
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
};
|
|
861
|
+
|
|
735
862
|
export const generateWAMessageContent = async (message, options) => {
|
|
736
863
|
var _a, _b;
|
|
737
864
|
let m = {};
|
|
@@ -905,11 +1032,19 @@ export const generateWAMessageContent = async (message, options) => {
|
|
|
905
1032
|
else if (hasNonNullishProperty(message, 'location')) {
|
|
906
1033
|
m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
|
|
907
1034
|
}
|
|
1035
|
+
else if (hasNonNullishProperty(message, 'stickerReact')) {
|
|
1036
|
+
m = await prepareStickerReactionMessage(message.stickerReact, options);
|
|
1037
|
+
}
|
|
908
1038
|
else if (hasNonNullishProperty(message, 'react')) {
|
|
909
|
-
if (
|
|
910
|
-
message.react
|
|
1039
|
+
if (hasNonNullishProperty(message.react, 'sticker') || hasNonNullishProperty(message.react, 'stickerMessage')) {
|
|
1040
|
+
m = await prepareStickerReactionMessage(message.react, options);
|
|
1041
|
+
}
|
|
1042
|
+
else {
|
|
1043
|
+
if (!message.react.senderTimestampMs) {
|
|
1044
|
+
message.react.senderTimestampMs = Date.now();
|
|
1045
|
+
}
|
|
1046
|
+
m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
|
|
911
1047
|
}
|
|
912
|
-
m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
|
|
913
1048
|
}
|
|
914
1049
|
else if (hasNonNullishProperty(message, 'delete')) {
|
|
915
1050
|
m.protocolMessage = {
|
|
@@ -1756,7 +1891,7 @@ export const generateWAMessageContent = async (message, options) => {
|
|
|
1756
1891
|
}
|
|
1757
1892
|
if (hasOptionalProperty(message, 'messageAssociation') && !!message.messageAssociation) {
|
|
1758
1893
|
m.messageContextInfo = m.messageContextInfo || {};
|
|
1759
|
-
m.messageContextInfo.messageAssociation = message.messageAssociation;
|
|
1894
|
+
m.messageContextInfo.messageAssociation = WAProto.MessageAssociation.fromObject(message.messageAssociation);
|
|
1760
1895
|
}
|
|
1761
1896
|
if (shouldIncludeReportingToken(m)) {
|
|
1762
1897
|
m.messageContextInfo = m.messageContextInfo || {};
|
|
@@ -1984,6 +2119,37 @@ export const updateMessageWithReceipt = (msg, receipt) => {
|
|
|
1984
2119
|
}
|
|
1985
2120
|
};
|
|
1986
2121
|
|
|
2122
|
+
export const getStickerReaction = (messageOrContent) => {
|
|
2123
|
+
if (!messageOrContent || typeof messageOrContent !== 'object') {
|
|
2124
|
+
return undefined;
|
|
2125
|
+
}
|
|
2126
|
+
const isWebMessage = !!messageOrContent.key && !!messageOrContent.message;
|
|
2127
|
+
const content = normalizeMessageContent(isWebMessage ? messageOrContent.message : messageOrContent);
|
|
2128
|
+
const association = content?.messageContextInfo?.messageAssociation;
|
|
2129
|
+
const associationType = association?.associationType;
|
|
2130
|
+
const isStickerAnnotation = associationType === WAProto.MessageAssociation.AssociationType.STICKER_ANNOTATION ||
|
|
2131
|
+
associationType === 'STICKER_ANNOTATION';
|
|
2132
|
+
if (!isStickerAnnotation || !association?.parentMessageKey || !content?.stickerMessage) {
|
|
2133
|
+
return undefined;
|
|
2134
|
+
}
|
|
2135
|
+
const messageTimestampMs = isWebMessage && messageOrContent.messageTimestamp != null
|
|
2136
|
+
? toNumber(messageOrContent.messageTimestamp) * 1000
|
|
2137
|
+
: undefined;
|
|
2138
|
+
const stickerSentMs = content.stickerMessage.stickerSentTs != null
|
|
2139
|
+
? toNumber(content.stickerMessage.stickerSentTs)
|
|
2140
|
+
: undefined;
|
|
2141
|
+
return trimEmptyValues({
|
|
2142
|
+
key: isWebMessage ? messageOrContent.key : undefined,
|
|
2143
|
+
parentKey: association.parentMessageKey,
|
|
2144
|
+
stickerMessage: content.stickerMessage,
|
|
2145
|
+
associationType: WAProto.MessageAssociation.AssociationType.STICKER_ANNOTATION,
|
|
2146
|
+
messageIndex: association.messageIndex ?? undefined,
|
|
2147
|
+
senderTimestampMs: messageTimestampMs || stickerSentMs
|
|
2148
|
+
});
|
|
2149
|
+
};
|
|
2150
|
+
|
|
2151
|
+
export const isStickerReactionMessage = (messageOrContent) => !!getStickerReaction(messageOrContent);
|
|
2152
|
+
|
|
1987
2153
|
export const updateMessageWithReaction = (msg, reaction) => {
|
|
1988
2154
|
const authorID = getKeyAuthor(reaction.key);
|
|
1989
2155
|
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
|
|
@@ -1992,6 +2158,29 @@ export const updateMessageWithReaction = (msg, reaction) => {
|
|
|
1992
2158
|
msg.reactions = reactions;
|
|
1993
2159
|
};
|
|
1994
2160
|
|
|
2161
|
+
export const updateMessageWithStickerReaction = (msg, stickerReaction) => {
|
|
2162
|
+
const reactionId = stickerReaction?.key?.id;
|
|
2163
|
+
if (!reactionId) {
|
|
2164
|
+
return;
|
|
2165
|
+
}
|
|
2166
|
+
const existing = msg.stickerReactions || [];
|
|
2167
|
+
const index = existing.findIndex(entry => entry?.key?.id === reactionId);
|
|
2168
|
+
if (stickerReaction.revoked || !stickerReaction.stickerMessage) {
|
|
2169
|
+
if (index !== -1) {
|
|
2170
|
+
msg.stickerReactions = existing.filter((_, i) => i !== index);
|
|
2171
|
+
}
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
if (index === -1) {
|
|
2175
|
+
msg.stickerReactions = [...existing, stickerReaction];
|
|
2176
|
+
}
|
|
2177
|
+
else {
|
|
2178
|
+
const next = [...existing];
|
|
2179
|
+
next[index] = stickerReaction;
|
|
2180
|
+
msg.stickerReactions = next;
|
|
2181
|
+
}
|
|
2182
|
+
};
|
|
2183
|
+
|
|
1995
2184
|
export const updateMessageWithPollUpdate = (msg, update) => {
|
|
1996
2185
|
const authorID = getKeyAuthor(update.pollUpdateMessageKey);
|
|
1997
2186
|
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Boom } from '@hapi/boom';
|
|
3
3
|
import { proto } from '../../WAProto/index.js';
|
|
4
4
|
import { WAMessageStubType } from '../Types/index.js';
|
|
5
|
-
import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
|
|
5
|
+
import { getContentType, getStickerReaction, isStickerReactionMessage, normalizeMessageContent } from '../Utils/messages.js';
|
|
6
6
|
import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
|
|
7
7
|
import { aesDecryptGCM, hmacSign } from './crypto.js';
|
|
8
8
|
import { getKeyAuthor, toNumber } from './generics.js';
|
|
@@ -85,6 +85,12 @@ export const cleanMessage = (message, meId, meLid) => {
|
|
|
85
85
|
if (content?.pollUpdateMessage) {
|
|
86
86
|
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
|
|
87
87
|
}
|
|
88
|
+
if (content?.messageContextInfo?.messageAssociation?.parentMessageKey) {
|
|
89
|
+
normaliseKey(content.messageContextInfo.messageAssociation.parentMessageKey);
|
|
90
|
+
}
|
|
91
|
+
if (content?.protocolMessage?.type === proto.Message.ProtocolMessage.Type.REVOKE && content.protocolMessage.key) {
|
|
92
|
+
normaliseKey(content.protocolMessage.key);
|
|
93
|
+
}
|
|
88
94
|
function normaliseKey(msgKey) {
|
|
89
95
|
|
|
90
96
|
if (!message.key.fromMe) {
|
|
@@ -112,7 +118,8 @@ export const isRealMessage = (message) => {
|
|
|
112
118
|
hasSomeContent &&
|
|
113
119
|
!normalizedContent?.protocolMessage &&
|
|
114
120
|
!normalizedContent?.reactionMessage &&
|
|
115
|
-
!normalizedContent?.pollUpdateMessage
|
|
121
|
+
!normalizedContent?.pollUpdateMessage &&
|
|
122
|
+
!isStickerReactionMessage(normalizedContent));
|
|
116
123
|
};
|
|
117
124
|
export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
|
|
118
125
|
|
|
@@ -243,6 +250,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
|
|
|
243
250
|
}
|
|
244
251
|
}
|
|
245
252
|
const content = normalizeMessageContent(message.message);
|
|
253
|
+
const stickerReaction = getStickerReaction(message);
|
|
246
254
|
|
|
247
255
|
if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
|
|
248
256
|
chat.archived = false;
|
|
@@ -322,6 +330,10 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
|
|
|
322
330
|
}
|
|
323
331
|
break;
|
|
324
332
|
case proto.Message.ProtocolMessage.Type.REVOKE:
|
|
333
|
+
const revokedKey = {
|
|
334
|
+
...protocolMsg.key,
|
|
335
|
+
remoteJid: protocolMsg.key.remoteJid || message.key.remoteJid
|
|
336
|
+
};
|
|
325
337
|
ev.emit('messages.update', [
|
|
326
338
|
{
|
|
327
339
|
key: {
|
|
@@ -331,6 +343,31 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
|
|
|
331
343
|
update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
|
|
332
344
|
}
|
|
333
345
|
]);
|
|
346
|
+
if (getMessage) {
|
|
347
|
+
try {
|
|
348
|
+
const revokedMsg = await getMessage(revokedKey);
|
|
349
|
+
const revokedSticker = revokedMsg && getStickerReaction(revokedMsg);
|
|
350
|
+
if (revokedSticker) {
|
|
351
|
+
const parentKey = {
|
|
352
|
+
...revokedSticker.parentKey,
|
|
353
|
+
remoteJid: jidNormalizedUser(revokedSticker.parentKey.remoteJid || message.key.remoteJid)
|
|
354
|
+
};
|
|
355
|
+
ev.emit('messages.sticker-reaction', [
|
|
356
|
+
{
|
|
357
|
+
key: parentKey,
|
|
358
|
+
stickerReaction: {
|
|
359
|
+
key: revokedMsg.key || revokedKey,
|
|
360
|
+
revoked: true,
|
|
361
|
+
senderTimestampMs: toNumber(message.messageTimestamp) * 1000
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
]);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
catch (err) {
|
|
368
|
+
logger?.debug({ err, revokedKey }, 'failed to look up revoked sticker reaction');
|
|
369
|
+
}
|
|
370
|
+
}
|
|
334
371
|
break;
|
|
335
372
|
case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
|
|
336
373
|
Object.assign(chat, {
|
|
@@ -445,6 +482,20 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
|
|
|
445
482
|
}
|
|
446
483
|
]);
|
|
447
484
|
}
|
|
485
|
+
else if (stickerReaction) {
|
|
486
|
+
ev.emit('messages.sticker-reaction', [
|
|
487
|
+
{
|
|
488
|
+
key: stickerReaction.parentKey,
|
|
489
|
+
stickerReaction: {
|
|
490
|
+
key: message.key,
|
|
491
|
+
stickerMessage: stickerReaction.stickerMessage,
|
|
492
|
+
senderTimestampMs: stickerReaction.senderTimestampMs,
|
|
493
|
+
associationType: stickerReaction.associationType,
|
|
494
|
+
...(stickerReaction.messageIndex != null ? { messageIndex: stickerReaction.messageIndex } : {})
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
]);
|
|
498
|
+
}
|
|
448
499
|
else if (content?.encEventResponseMessage) {
|
|
449
500
|
const encEventResponse = content.encEventResponseMessage;
|
|
450
501
|
const creationMsgKey = encEventResponse.eventCreationMessageKey;
|
package/src/Utils/view-once.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export const DEFAULT_VIEW_ONCE_TRIGGER_EMOJIS: readonly string[];
|
|
|
12
12
|
export const DEFAULT_VIEW_ONCE_CACHE_SIZE: number;
|
|
13
13
|
export const DEFAULT_VIEW_ONCE_TTL_MS: number;
|
|
14
14
|
export function isViewOnceMessage(message: any): boolean;
|
|
15
|
+
export function isUnavailableViewOnceMessage(message: any): boolean;
|
|
15
16
|
export function hasDownloadableViewOnceMedia(message: any): boolean;
|
|
16
17
|
export function unwrapViewOnce(message: any): any;
|
|
17
18
|
export function getViewOnceMediaType(message: any): 'image' | 'video' | 'audio' | undefined;
|
|
@@ -28,6 +29,7 @@ export function describeViewOnce(message: any): {
|
|
|
28
29
|
} | undefined;
|
|
29
30
|
export type ViewOnceStore = {
|
|
30
31
|
remember(message: any): boolean;
|
|
32
|
+
rememberUnavailable?(message: any): boolean;
|
|
31
33
|
get(jid: string, id: string): any;
|
|
32
34
|
getById?(id: string, preferredJid?: string): any;
|
|
33
35
|
delete(jid: string, id: string): number;
|
|
@@ -78,6 +80,7 @@ export type ViewOnceRetrievalOptions = {
|
|
|
78
80
|
forwardToJid?: string;
|
|
79
81
|
allowFromMe?: boolean;
|
|
80
82
|
onRetrieved?: (info: any) => void | Promise<void>;
|
|
83
|
+
onUnavailable?: (info: any) => void | Promise<void>;
|
|
81
84
|
shouldRetrieve?: (info: any) => boolean | Promise<boolean>;
|
|
82
85
|
download?: (message: any, type: string, options: any, ctx: any) => Promise<any>;
|
|
83
86
|
downloadOptions?: Record<string, any>;
|
package/src/Utils/view-once.js
CHANGED
|
@@ -139,6 +139,8 @@ export const unwrapViewOnce = (message) => {
|
|
|
139
139
|
|
|
140
140
|
export const isViewOnceMessage = (message) => !!unwrapViewOnce(message);
|
|
141
141
|
|
|
142
|
+
export const isUnavailableViewOnceMessage = (message) => Boolean(message?.key?.isViewOnce === true && !isViewOnceMessage(message?.message ?? message));
|
|
143
|
+
|
|
142
144
|
export const hasDownloadableViewOnceMedia = (message) => {
|
|
143
145
|
const content = unwrapViewOnce(message?.message ?? message);
|
|
144
146
|
const info = extractViewOnceMedia(content);
|
|
@@ -242,36 +244,52 @@ export const makeViewOnceStore = ({ max = DEFAULT_VIEW_ONCE_CACHE_SIZE, ttlMs =
|
|
|
242
244
|
}
|
|
243
245
|
};
|
|
244
246
|
|
|
245
|
-
const
|
|
246
|
-
const
|
|
247
|
-
const
|
|
248
|
-
if (!id || !chat || !message?.message || !isViewOnceMessage(message.message)) {
|
|
249
|
-
return false;
|
|
250
|
-
}
|
|
251
|
-
const normalizedChat = jidNormalizedUser(chat);
|
|
252
|
-
const primaryKey = storeKey(normalizedChat, id);
|
|
253
|
-
const existing = cache.get(primaryKey);
|
|
254
|
-
if (existing && hasDownloadableViewOnceMedia(existing.message) && !hasDownloadableViewOnceMedia(message.message)) {
|
|
255
|
-
return false;
|
|
256
|
-
}
|
|
247
|
+
const putEntry = (message) => {
|
|
248
|
+
const normalizedChat = jidNormalizedUser(message.key.remoteJid);
|
|
249
|
+
const primaryKey = storeKey(normalizedChat, message.key.id);
|
|
257
250
|
const entry = {
|
|
258
251
|
key: { ...message.key, remoteJid: normalizedChat },
|
|
259
252
|
message: message.message
|
|
260
253
|
};
|
|
261
254
|
cache.set(primaryKey, entry);
|
|
262
|
-
let idSet = byId.get(id);
|
|
255
|
+
let idSet = byId.get(message.key.id);
|
|
263
256
|
if (!idSet) {
|
|
264
257
|
idSet = new Set();
|
|
265
|
-
byId.set(id, idSet);
|
|
258
|
+
byId.set(message.key.id, idSet);
|
|
266
259
|
}
|
|
267
260
|
idSet.add(primaryKey);
|
|
268
261
|
if (typeof message.key.remoteJidAlt === 'string' && message.key.remoteJidAlt) {
|
|
269
|
-
altKeys.set(storeKey(message.key.remoteJidAlt, id), primaryKey);
|
|
262
|
+
altKeys.set(storeKey(message.key.remoteJidAlt, message.key.id), primaryKey);
|
|
270
263
|
}
|
|
271
264
|
pruneStaleIndexes();
|
|
272
265
|
return true;
|
|
273
266
|
};
|
|
274
267
|
|
|
268
|
+
const remember = (message) => {
|
|
269
|
+
const id = message?.key?.id;
|
|
270
|
+
const chat = message?.key?.remoteJid;
|
|
271
|
+
if (!id || !chat || !message?.message || !isViewOnceMessage(message.message)) {
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
const existing = cache.get(storeKey(jidNormalizedUser(chat), id));
|
|
275
|
+
if (existing && hasDownloadableViewOnceMedia(existing.message) && !hasDownloadableViewOnceMedia(message.message)) {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
return putEntry(message);
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const rememberUnavailable = (message) => {
|
|
282
|
+
const id = message?.key?.id;
|
|
283
|
+
const chat = message?.key?.remoteJid;
|
|
284
|
+
if (!id || !chat || !isUnavailableViewOnceMessage(message)) {
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
if (cache.get(storeKey(jidNormalizedUser(chat), id))) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
return putEntry({ key: message.key, message: undefined });
|
|
291
|
+
};
|
|
292
|
+
|
|
275
293
|
const get = (jid, id) => {
|
|
276
294
|
if (!jid || !id) {
|
|
277
295
|
return undefined;
|
|
@@ -364,6 +382,7 @@ export const makeViewOnceStore = ({ max = DEFAULT_VIEW_ONCE_CACHE_SIZE, ttlMs =
|
|
|
364
382
|
|
|
365
383
|
return {
|
|
366
384
|
remember,
|
|
385
|
+
rememberUnavailable,
|
|
367
386
|
get,
|
|
368
387
|
getById,
|
|
369
388
|
delete: remove,
|
|
@@ -409,7 +428,13 @@ const buildCleanViewOnceMedia = (originalMessage, mediaKeyName, media) => {
|
|
|
409
428
|
|
|
410
429
|
const resolveTargetsSync = ({ jids, ids, store, messageRetryManager, requireDownloadable = true }) => {
|
|
411
430
|
const matches = (msg) => {
|
|
412
|
-
if (!msg
|
|
431
|
+
if (!msg) {
|
|
432
|
+
return false;
|
|
433
|
+
}
|
|
434
|
+
if (isUnavailableViewOnceMessage(msg)) {
|
|
435
|
+
return !requireDownloadable;
|
|
436
|
+
}
|
|
437
|
+
if (!isViewOnceMessage(msg.message ?? msg)) {
|
|
413
438
|
return false;
|
|
414
439
|
}
|
|
415
440
|
return !requireDownloadable || hasDownloadableViewOnceMedia(msg.message ?? msg);
|
|
@@ -471,6 +496,17 @@ const resolveTargetsAsync = async ({ jids, ids, participant, store, messageRetry
|
|
|
471
496
|
id,
|
|
472
497
|
...(participant ? { participant } : {})
|
|
473
498
|
});
|
|
499
|
+
if (!requireDownloadable && isUnavailableViewOnceMessage(loaded)) {
|
|
500
|
+
const unavailableEntry = {
|
|
501
|
+
key: {
|
|
502
|
+
...loaded.key,
|
|
503
|
+
remoteJid: jidNormalizedUser(loaded.key.remoteJid || jid)
|
|
504
|
+
},
|
|
505
|
+
message: undefined
|
|
506
|
+
};
|
|
507
|
+
store?.rememberUnavailable?.(unavailableEntry);
|
|
508
|
+
return unavailableEntry;
|
|
509
|
+
}
|
|
474
510
|
const loadedMessage = loaded?.message ?? (loaded && !loaded.key && isViewOnceMessage(loaded) ? loaded : undefined);
|
|
475
511
|
if (!loadedMessage || !isViewOnceMessage(loadedMessage)) {
|
|
476
512
|
continue;
|
|
@@ -480,9 +516,9 @@ const resolveTargetsAsync = async ({ jids, ids, participant, store, messageRetry
|
|
|
480
516
|
}
|
|
481
517
|
const normalized = {
|
|
482
518
|
key: {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
519
|
+
id,
|
|
520
|
+
...(loaded?.key || {}),
|
|
521
|
+
remoteJid: jidNormalizedUser(loaded?.key?.remoteJid || jid)
|
|
486
522
|
},
|
|
487
523
|
message: loadedMessage
|
|
488
524
|
};
|
|
@@ -868,6 +904,7 @@ const VIEW_ONCE_DEFAULTS = Object.freeze({
|
|
|
868
904
|
forwardToJid: undefined,
|
|
869
905
|
allowFromMe: false,
|
|
870
906
|
onRetrieved: undefined,
|
|
907
|
+
onUnavailable: undefined,
|
|
871
908
|
shouldRetrieve: undefined,
|
|
872
909
|
logger: undefined,
|
|
873
910
|
download: undefined,
|
|
@@ -930,7 +967,22 @@ export const bindViewOnceCache = (sock, options = {}) => {
|
|
|
930
967
|
const onUpsert = (event) => {
|
|
931
968
|
const messages = Array.isArray(event?.messages) ? event.messages : [];
|
|
932
969
|
for (const message of messages) {
|
|
933
|
-
if (!message?.
|
|
970
|
+
if (!message?.key?.remoteJid || message.key.remoteJid === 'status@broadcast') {
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
if (isUnavailableViewOnceMessage(message)) {
|
|
974
|
+
const isNew = store.rememberUnavailable?.(message) ?? false;
|
|
975
|
+
if (isNew && event.type === 'notify') {
|
|
976
|
+
sock.ev?.emit?.('viewonce.unavailable', {
|
|
977
|
+
key: message.key,
|
|
978
|
+
chat: message.key.remoteJid,
|
|
979
|
+
participant: message.key.participant,
|
|
980
|
+
message
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
if (!message?.message) {
|
|
934
986
|
continue;
|
|
935
987
|
}
|
|
936
988
|
if (isViewOnceMessage(message.message)) {
|
|
@@ -1050,7 +1102,20 @@ export const bindViewOnceRetrieval = (sock, config = {}) => {
|
|
|
1050
1102
|
return sent;
|
|
1051
1103
|
}
|
|
1052
1104
|
catch (error) {
|
|
1053
|
-
|
|
1105
|
+
if (error?.data?.reason === 'view-once-payload-unavailable') {
|
|
1106
|
+
logger?.debug?.({ key: stored?.key }, 'view-once payload was withheld from this companion device');
|
|
1107
|
+
}
|
|
1108
|
+
else {
|
|
1109
|
+
logger?.warn?.({ error, key: stored?.key }, 'failed to open a view-once message');
|
|
1110
|
+
}
|
|
1111
|
+
if (error?.data?.reason === 'view-once-payload-unavailable' && typeof options.onUnavailable === 'function') {
|
|
1112
|
+
try {
|
|
1113
|
+
await options.onUnavailable({ key: stored?.key, chat, source, trigger, error });
|
|
1114
|
+
}
|
|
1115
|
+
catch (callbackError) {
|
|
1116
|
+
logger?.warn?.({ error: callbackError, key: stored?.key }, 'view-once onUnavailable callback failed');
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1054
1119
|
sock.ev?.emit?.('viewonce.failed', { key: stored?.key, chat, source, error });
|
|
1055
1120
|
return undefined;
|
|
1056
1121
|
}
|
package/src/index.d.ts
CHANGED
|
@@ -15,13 +15,14 @@ export * from "./Voip/index.js";
|
|
|
15
15
|
import baseMakeWASocket from './Socket/index.js';
|
|
16
16
|
import type { NewsletterStatusFetchOptions, NewsletterStatusList, NewsletterStatusSendOptions, NewsletterStatusSendResult, NewsletterStatusStanzaResult, NewsletterStatusUpdatesFetchOptions } from './Utils/newsletter-status.js';
|
|
17
17
|
import type { StatusSendOptions } from './Utils/status-send.js';
|
|
18
|
-
import type { AnyMessageContent, CheckNumbersOptions, ContactCheckResult, DownloadMediaHelperOptions, DownloadMediaOptions, MediaDownloadType, SendMessageOptions, SendQueueStats, SoundStickerContent } from './Types/Content.js';
|
|
18
|
+
import type { AnyMessageContent, CheckNumbersOptions, ContactCheckResult, DownloadMediaHelperOptions, DownloadMediaOptions, MediaDownloadType, SendMessageOptions, SendQueueStats, SoundStickerContent, StickerReactionContent } from './Types/Content.js';
|
|
19
19
|
import type { ViewOnceRetrievalOptions, ViewOnceStore } from './Utils/view-once.js';
|
|
20
20
|
import type { getResourceUsage, trimMemory } from './Utils/resource-guard.js';
|
|
21
21
|
import type { PerformanceManager, PerformanceStats } from './Utils/performance.js';
|
|
22
22
|
import type { MultiSessionManager, MultiSessionManagerOptions } from './Utils/multi-session-manager.js';
|
|
23
23
|
import type { SessionRecoveryRequest, SessionRecoveryResult, SessionRecoveryStats } from './Utils/session-recovery.js';
|
|
24
24
|
type BaseWASocket = ReturnType<typeof baseMakeWASocket>;
|
|
25
|
+
export type SendStickerReaction = (jid: string, target: any, sticker: any | Omit<StickerReactionContent, 'key'>, options?: SendMessageOptions) => Promise<import('../WAProto/index.js').proto.WebMessageInfo | undefined>;
|
|
25
26
|
export type WASocket = BaseWASocket & {
|
|
26
27
|
sendMessage: (jid: string | string[], content: AnyMessageContent | string, options?: SendMessageOptions) => Promise<import('../WAProto/index.js').proto.WebMessageInfo | undefined>;
|
|
27
28
|
sendAiMessage: (jid: string, content: AnyMessageContent | string, options?: SendMessageOptions) => Promise<import('../WAProto/index.js').proto.WebMessageInfo | undefined>;
|
|
@@ -34,6 +35,8 @@ export type WASocket = BaseWASocket & {
|
|
|
34
35
|
sendSoundSticker: (jid: string, soundSticker: SoundStickerContent, options?: SendMessageOptions) => Promise<any>;
|
|
35
36
|
sendVideoSoundSticker: (jid: string, video: any, stickerOptions?: Omit<SoundStickerContent, 'video' | 'sticker' | 'audio'>, sendOptions?: SendMessageOptions) => Promise<any>;
|
|
36
37
|
downloadSoundStickerAudio: (message: any, type?: MediaDownloadType, options?: DownloadMediaOptions, helperOptions?: DownloadMediaHelperOptions) => Promise<any>;
|
|
38
|
+
sendStickerReaction: SendStickerReaction;
|
|
39
|
+
reactWithSticker: SendStickerReaction;
|
|
37
40
|
clearMediaCache: () => void;
|
|
38
41
|
mediaCacheStats: () => {
|
|
39
42
|
entries: number;
|