@oxidezap/baileyrs 0.3.7 → 0.3.9
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 +56 -8
- package/lib/Bridge/history-sync-wire.d.ts +2 -2
- package/lib/Bridge/history-sync-wire.js +4 -4
- package/lib/Bridge/schema.js +7 -1
- package/lib/Bridge/types.d.ts +7 -1
- package/lib/Compatibility/auth-state.d.ts +30 -0
- package/lib/Compatibility/auth-state.js +96 -0
- package/lib/Compatibility/encode-proto-core.d.ts +31 -0
- package/lib/Compatibility/encode-proto-core.js +51 -0
- package/lib/Compatibility/encode-proto.d.ts +0 -29
- package/lib/Compatibility/encode-proto.js +3 -50
- package/lib/Compatibility/host-auth-state.d.ts +6 -0
- package/lib/Compatibility/host-auth-state.js +162 -0
- package/lib/Compatibility/internal/auth-state.d.ts +3 -7
- package/lib/Compatibility/internal/auth-state.js +34 -1
- package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
- package/lib/Compatibility/internal/host-auth-state.js +14 -0
- package/lib/Compatibility/legacy-store/device.js +5 -5
- package/lib/Compatibility/message-ids.d.ts +17 -0
- package/lib/Compatibility/message-ids.js +47 -0
- package/lib/Compatibility/message-relay.d.ts +2 -2
- package/lib/Compatibility/message-relay.js +4 -4
- package/lib/Compatibility/proto-runtime.js +33 -11
- package/lib/Compatibility/socket-results.d.ts +1 -1
- package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
- package/lib/Compatibility/tagged-message-waiter.js +5 -5
- package/lib/Compatibility/usync/adapter.d.ts +1 -1
- package/lib/Compatibility/websocket-client.d.ts +11 -3
- package/lib/Compatibility/websocket-client.js +84 -11
- package/lib/Defaults/index.d.ts +8 -8
- package/lib/Defaults/index.js +8 -8
- package/lib/Media/content.d.ts +28 -0
- package/lib/Media/content.js +129 -0
- package/lib/Media/core.d.ts +34 -0
- package/lib/Media/core.js +120 -0
- package/lib/Media/mutations.d.ts +24 -0
- package/lib/Media/mutations.js +38 -0
- package/lib/Runtime/aes-gcm.d.ts +4 -0
- package/lib/Runtime/aes-gcm.js +11 -0
- package/lib/Runtime/bridge.d.ts +44 -0
- package/lib/Runtime/bridge.js +76 -0
- package/lib/Runtime/buffer.d.ts +9 -0
- package/lib/Runtime/buffer.js +22 -0
- package/lib/Runtime/bytes.d.ts +61 -0
- package/lib/Runtime/bytes.js +270 -0
- package/lib/Runtime/host.d.ts +22 -0
- package/lib/Runtime/host.js +43 -0
- package/lib/Runtime/long.d.ts +33 -0
- package/lib/Runtime/long.js +64 -0
- package/lib/Runtime/node-media-processors.d.ts +4 -0
- package/lib/Runtime/node-media-processors.js +29 -0
- package/lib/Runtime/node-media.d.ts +28 -0
- package/lib/Runtime/node-media.js +115 -0
- package/lib/Runtime/node.d.ts +14 -0
- package/lib/Runtime/node.js +81 -0
- package/lib/Runtime/paths.d.ts +4 -0
- package/lib/Runtime/paths.js +7 -0
- package/lib/Runtime/stream.d.ts +11 -0
- package/lib/Runtime/stream.js +25 -0
- package/lib/Runtime/types.d.ts +98 -0
- package/lib/Runtime/types.js +13 -0
- package/lib/Socket/core.d.ts +312 -0
- package/lib/Socket/core.js +1134 -0
- package/lib/Socket/events-core.d.ts +75 -0
- package/lib/Socket/events-core.js +1058 -0
- package/lib/Socket/events.d.ts +1 -63
- package/lib/Socket/events.js +4 -1047
- package/lib/Socket/groups.js +4 -3
- package/lib/Socket/index.d.ts +521 -103
- package/lib/Socket/index.js +10 -1007
- package/lib/Socket/messages-core.d.ts +41 -0
- package/lib/Socket/messages-core.js +270 -0
- package/lib/Socket/messages.d.ts +9 -36
- package/lib/Socket/messages.js +3 -260
- package/lib/Socket/newsletter.js +3 -3
- package/lib/Socket/profile.js +1 -1
- package/lib/Socket/terminal-close-reporter.d.ts +2 -0
- package/lib/Socket/terminal-close-reporter.js +3 -3
- package/lib/Socket/transport.d.ts +2 -0
- package/lib/Socket/transport.js +16 -1
- package/lib/Socket/types.d.ts +2 -0
- package/lib/Types/Auth.d.ts +11 -0
- package/lib/Types/Message.d.ts +1 -1
- package/lib/Types/Socket.d.ts +2 -2
- package/lib/Types/index.d.ts +6 -1
- package/lib/Utils/browser-utils.d.ts +4 -0
- package/lib/Utils/browser-utils.js +53 -2
- package/lib/Utils/crypto.d.ts +1 -0
- package/lib/Utils/crypto.js +1 -0
- package/lib/Utils/event-buffer.d.ts +6 -1
- package/lib/Utils/event-buffer.js +28 -27
- package/lib/Utils/link-preview.d.ts +4 -3
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +35 -6
- package/lib/Utils/messages-core.d.ts +174 -0
- package/lib/Utils/messages-core.js +1042 -0
- package/lib/Utils/messages-media-core.d.ts +73 -0
- package/lib/Utils/messages-media-core.js +319 -0
- package/lib/Utils/messages-media.d.ts +1 -72
- package/lib/Utils/messages-media.js +9 -358
- package/lib/Utils/messages.d.ts +1 -166
- package/lib/Utils/messages.js +7 -1040
- package/lib/Utils/optional-peer.js +14 -5
- package/lib/Utils/process-history-message-core.d.ts +36 -0
- package/lib/Utils/process-history-message-core.js +187 -0
- package/lib/Utils/process-history-message.d.ts +5 -43
- package/lib/Utils/process-history-message.js +11 -197
- package/lib/Utils/process-message-core.d.ts +29 -0
- package/lib/Utils/process-message-core.js +112 -0
- package/lib/Utils/process-message.d.ts +4 -24
- package/lib/Utils/process-message.js +6 -111
- package/lib/WABinary/generic-utils.js +7 -5
- package/lib/host-shared.d.ts +74 -0
- package/lib/host-shared.js +15 -0
- package/lib/host-socket-operations.d.ts +3 -0
- package/lib/host-socket-operations.js +2 -0
- package/lib/host-surface.d.ts +21 -0
- package/lib/host-surface.js +35 -0
- package/lib/host-types.d.ts +356 -0
- package/lib/host-types.js +2 -0
- package/lib/host.d.ts +33 -0
- package/lib/host.js +31 -0
- package/lib/node-surface.d.ts +9 -0
- package/lib/node-surface.js +15 -0
- package/lib/surface.d.ts +5 -0
- package/lib/surface.js +6 -0
- package/lib/wasm.d.ts +27 -0
- package/lib/wasm.js +27 -0
- package/package.json +18 -6
|
@@ -0,0 +1,1042 @@
|
|
|
1
|
+
import { BufferRuntime } from '../Runtime/buffer.js';
|
|
2
|
+
import LongRuntime from 'long';
|
|
3
|
+
import { toBridgeMediaType } from '../Compatibility/media-type.js';
|
|
4
|
+
import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
5
|
+
import { WAMessageStatus, WAProto } from '../Types/index.js';
|
|
6
|
+
import { proto } from '../WAProto/runtime.js';
|
|
7
|
+
import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
|
|
8
|
+
import { assertArgumentDomain } from './argument-domain.js';
|
|
9
|
+
import { Boom } from './boom.js';
|
|
10
|
+
import { getKeyAuthorPortable, randomBytes, sha256Sync, toNumber, unixTimestampSeconds, utf8Encode, hexEncode } from '../Runtime/bytes.js';
|
|
11
|
+
import { readableFromWeb } from '../Runtime/stream.js';
|
|
12
|
+
import { generateThumbnail, getAudioDuration, getAudioWaveform, getStream, toBuffer } from './messages-media-core.js';
|
|
13
|
+
const MIMETYPE_MAP = {
|
|
14
|
+
image: 'image/jpeg',
|
|
15
|
+
video: 'video/mp4',
|
|
16
|
+
document: 'application/pdf',
|
|
17
|
+
audio: 'audio/ogg; codecs=opus',
|
|
18
|
+
sticker: 'image/webp',
|
|
19
|
+
'product-catalog-image': 'image/jpeg'
|
|
20
|
+
};
|
|
21
|
+
const MessageTypeProto = {
|
|
22
|
+
image: WAProto.Message.ImageMessage,
|
|
23
|
+
video: WAProto.Message.VideoMessage,
|
|
24
|
+
audio: WAProto.Message.AudioMessage,
|
|
25
|
+
sticker: WAProto.Message.StickerMessage,
|
|
26
|
+
document: WAProto.Message.DocumentMessage
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Uses a regex to test whether the string contains a URL, and returns the URL if it does.
|
|
30
|
+
* @param text eg. hello https://google.com
|
|
31
|
+
* @returns the URL, eg. https://google.com
|
|
32
|
+
*/
|
|
33
|
+
export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
|
|
34
|
+
export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
|
|
35
|
+
if (!getUrlInfo)
|
|
36
|
+
return;
|
|
37
|
+
const url = extractUrlFromText(text);
|
|
38
|
+
if (url) {
|
|
39
|
+
try {
|
|
40
|
+
const urlInfo = await getUrlInfo(url);
|
|
41
|
+
return urlInfo;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
// ignore if fails
|
|
45
|
+
logger?.warn({ trace: error.stack }, 'url generation failed');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const assertColor = (color) => {
|
|
50
|
+
if (typeof color === 'number') {
|
|
51
|
+
return color > 0 ? color : 0xffffffff + Number(color) + 1;
|
|
52
|
+
}
|
|
53
|
+
let hex = color.trim().replace('#', '');
|
|
54
|
+
if (hex.length <= 6) {
|
|
55
|
+
hex = 'FF' + hex.padStart(6, '0');
|
|
56
|
+
}
|
|
57
|
+
return parseInt(hex, 16);
|
|
58
|
+
};
|
|
59
|
+
export const prepareWAMessageMedia = async (message, options) => {
|
|
60
|
+
const logger = options.logger;
|
|
61
|
+
let mediaType;
|
|
62
|
+
for (const key of MEDIA_KEYS) {
|
|
63
|
+
if (key in message) {
|
|
64
|
+
mediaType = key;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!mediaType) {
|
|
68
|
+
throw new Boom('Invalid media type', { statusCode: 400 });
|
|
69
|
+
}
|
|
70
|
+
const messageRecord = message;
|
|
71
|
+
const uploadData = {
|
|
72
|
+
...message,
|
|
73
|
+
media: messageRecord[mediaType]
|
|
74
|
+
};
|
|
75
|
+
delete uploadData[mediaType];
|
|
76
|
+
// check if cacheable + generate cache key
|
|
77
|
+
const cacheableKey = typeof uploadData.media === 'object' &&
|
|
78
|
+
'url' in uploadData.media &&
|
|
79
|
+
!!uploadData.media.url &&
|
|
80
|
+
!!options.mediaCache &&
|
|
81
|
+
mediaType + ':' + uploadData.media.url.toString();
|
|
82
|
+
if (mediaType === 'document' && !uploadData.fileName) {
|
|
83
|
+
uploadData.fileName = 'file';
|
|
84
|
+
}
|
|
85
|
+
if (!uploadData.mimetype) {
|
|
86
|
+
uploadData.mimetype = MIMETYPE_MAP[mediaType];
|
|
87
|
+
}
|
|
88
|
+
if (cacheableKey) {
|
|
89
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey);
|
|
90
|
+
if (mediaBuff) {
|
|
91
|
+
logger?.debug({ cacheableKey }, 'got media cache hit');
|
|
92
|
+
const obj = proto.Message.decode(mediaBuff);
|
|
93
|
+
const key = `${mediaType}Message`;
|
|
94
|
+
// `obj[key]` is a discriminated-union slot; cache hits always store
|
|
95
|
+
// a media submessage (not e.g. `conversation: string`), so cast to
|
|
96
|
+
// `object` for `Object.assign`'s benefit.
|
|
97
|
+
Object.assign(obj[key], { ...uploadData, media: undefined });
|
|
98
|
+
return obj;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Read media into buffer — needed for both upload and metadata extraction
|
|
102
|
+
const { stream } = await getStream(uploadData.media, options.options);
|
|
103
|
+
const buffer = await toBuffer(stream);
|
|
104
|
+
const effectiveMediaType = options.mediaTypeOverride || mediaType;
|
|
105
|
+
const bridgeMediaType = toBridgeMediaType(effectiveMediaType);
|
|
106
|
+
// Run upload + metadata extraction in parallel
|
|
107
|
+
let uploadResult;
|
|
108
|
+
if (options.processMedia) {
|
|
109
|
+
// User-provided processing pipeline (streaming encrypt, custom thumbnails, etc.)
|
|
110
|
+
const { upload, metadata } = await options.processMedia(buffer, bridgeMediaType, options.waClient);
|
|
111
|
+
uploadResult = upload;
|
|
112
|
+
if (metadata) {
|
|
113
|
+
if (metadata.jpegThumbnail !== undefined)
|
|
114
|
+
uploadData.jpegThumbnail = metadata.jpegThumbnail;
|
|
115
|
+
if (metadata.width !== undefined)
|
|
116
|
+
uploadData.width = metadata.width;
|
|
117
|
+
if (metadata.height !== undefined)
|
|
118
|
+
uploadData.height = metadata.height;
|
|
119
|
+
if (metadata.seconds !== undefined)
|
|
120
|
+
uploadData.seconds = metadata.seconds;
|
|
121
|
+
if (metadata.waveform !== undefined)
|
|
122
|
+
uploadData.waveform = metadata.waveform;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else if (options.upload) {
|
|
126
|
+
// Legacy upstream-Baileys compat: { upload: sock.waUploadToServer }.
|
|
127
|
+
// Same plaintext-in / UploadMediaResult-out contract as waClient.uploadMedia.
|
|
128
|
+
const [result] = await Promise.all([
|
|
129
|
+
options.upload(buffer, { mediaType: effectiveMediaType }),
|
|
130
|
+
extractBuiltInMetadata(buffer, mediaType, uploadData, options)
|
|
131
|
+
]);
|
|
132
|
+
uploadResult = result;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
// Default: in-memory encrypt + upload via Rust, built-in metadata extraction
|
|
136
|
+
const [result] = await Promise.all([
|
|
137
|
+
options.waClient.uploadMedia(buffer, bridgeMediaType),
|
|
138
|
+
extractBuiltInMetadata(buffer, mediaType, uploadData, options)
|
|
139
|
+
]);
|
|
140
|
+
uploadResult = result;
|
|
141
|
+
}
|
|
142
|
+
// Coerce any string-form `jpegThumbnail` (the legacy upstream Baileys output)
|
|
143
|
+
// into bytes — the bridge's ts-proto encoder reads `.byteLength` directly
|
|
144
|
+
// and throws `invalid uint32: undefined` on strings. Done here (not at
|
|
145
|
+
// extraction time) so values arriving via `processMedia`, link-preview
|
|
146
|
+
// builders, or direct user input go through the same coercion.
|
|
147
|
+
if (typeof uploadData.jpegThumbnail === 'string') {
|
|
148
|
+
uploadData.jpegThumbnail = BufferRuntime.from(uploadData.jpegThumbnail, 'base64');
|
|
149
|
+
}
|
|
150
|
+
const obj = WAProto.Message.fromObject({
|
|
151
|
+
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
152
|
+
url: uploadResult.url,
|
|
153
|
+
directPath: uploadResult.directPath,
|
|
154
|
+
mediaKey: uploadResult.mediaKey,
|
|
155
|
+
fileEncSha256: uploadResult.fileEncSha256,
|
|
156
|
+
fileSha256: uploadResult.fileSha256,
|
|
157
|
+
fileLength: uploadResult.fileLength,
|
|
158
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
159
|
+
...uploadData,
|
|
160
|
+
media: undefined
|
|
161
|
+
})
|
|
162
|
+
});
|
|
163
|
+
if (uploadData.ptv) {
|
|
164
|
+
obj.ptvMessage = obj.videoMessage;
|
|
165
|
+
delete obj.videoMessage;
|
|
166
|
+
}
|
|
167
|
+
if (obj.stickerMessage) {
|
|
168
|
+
obj.stickerMessage.stickerSentTs = Date.now();
|
|
169
|
+
}
|
|
170
|
+
if (cacheableKey) {
|
|
171
|
+
logger?.debug({ cacheableKey }, 'set cache');
|
|
172
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
|
|
173
|
+
}
|
|
174
|
+
return obj;
|
|
175
|
+
};
|
|
176
|
+
/** Extract metadata (thumbnail, duration, waveform) from buffer using built-in JS libraries */
|
|
177
|
+
async function extractBuiltInMetadata(buffer, mediaType, uploadData, options) {
|
|
178
|
+
try {
|
|
179
|
+
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData.jpegThumbnail === 'undefined';
|
|
180
|
+
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
|
|
181
|
+
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
|
|
182
|
+
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
|
|
183
|
+
if (requiresThumbnailComputation) {
|
|
184
|
+
const { thumbnail, originalImageDimensions } = await generateThumbnail(buffer, mediaType, options);
|
|
185
|
+
uploadData.jpegThumbnail = thumbnail;
|
|
186
|
+
if (!uploadData.width && originalImageDimensions) {
|
|
187
|
+
uploadData.width = originalImageDimensions.width;
|
|
188
|
+
uploadData.height = originalImageDimensions.height;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (requiresDurationComputation) {
|
|
192
|
+
uploadData.seconds = await getAudioDuration(buffer);
|
|
193
|
+
}
|
|
194
|
+
if (requiresWaveformProcessing) {
|
|
195
|
+
uploadData.waveform = await getAudioWaveform(buffer, options.logger);
|
|
196
|
+
}
|
|
197
|
+
if (requiresAudioBackground) {
|
|
198
|
+
uploadData.backgroundArgb = await assertColor(options.backgroundColor);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
options.logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
|
|
206
|
+
ephemeralExpiration = ephemeralExpiration || 0;
|
|
207
|
+
const content = {
|
|
208
|
+
ephemeralMessage: {
|
|
209
|
+
message: {
|
|
210
|
+
protocolMessage: {
|
|
211
|
+
type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
212
|
+
ephemeralExpiration
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
return WAProto.Message.fromObject(content);
|
|
218
|
+
};
|
|
219
|
+
/**
|
|
220
|
+
* Generate forwarded message content like WA does
|
|
221
|
+
* @param message the message to forward
|
|
222
|
+
* @param options.forceForward will show the message as forwarded even if it is from you
|
|
223
|
+
*/
|
|
224
|
+
export const generateForwardMessageContent = (message, forceForward) => {
|
|
225
|
+
let content = message.message;
|
|
226
|
+
if (!content) {
|
|
227
|
+
throw new Boom('no content in message', { statusCode: 400 });
|
|
228
|
+
}
|
|
229
|
+
content = normalizeMessageContent(content);
|
|
230
|
+
// Shallow clone of the outer map — one entry on it is rewritten below.
|
|
231
|
+
content = { ...content };
|
|
232
|
+
let key = Object.keys(content)[0];
|
|
233
|
+
let score = content?.[key]?.contextInfo?.forwardingScore || 0;
|
|
234
|
+
score += message.key.fromMe && !forceForward ? 0 : 1;
|
|
235
|
+
const contextInfo = score > 0 ? { forwardingScore: score, isForwarded: true } : {};
|
|
236
|
+
// The nested message object is the *caller's*, reached through the shallow
|
|
237
|
+
// clone above, so writing `contextInfo` onto it wrote into their argument.
|
|
238
|
+
// And it replaces rather than merges: a caller who forwarded a quoted message
|
|
239
|
+
// found `stanzaId` and `participant` gone from their own object afterwards.
|
|
240
|
+
// Upstream leaves the argument untouched.
|
|
241
|
+
//
|
|
242
|
+
// Rebuilt rather than deep-copied, and only the one object being written.
|
|
243
|
+
// Upstream's copy is `proto.Message.decode(proto.Message.encode(content))` —
|
|
244
|
+
// a full serialise/parse round trip on a hot send path — which is not worth
|
|
245
|
+
// paying to fix an aliasing bug.
|
|
246
|
+
if (key === 'conversation') {
|
|
247
|
+
// This object is created here, so nothing of the caller's is aliased and
|
|
248
|
+
// the `contextInfo` goes straight in. Same allocation count as before.
|
|
249
|
+
content.extendedTextMessage = { text: content[key], contextInfo };
|
|
250
|
+
delete content.conversation;
|
|
251
|
+
key = 'extendedTextMessage';
|
|
252
|
+
return content;
|
|
253
|
+
}
|
|
254
|
+
const nested = content[key];
|
|
255
|
+
// A plain object is the only thing worth copying, and the only thing that can
|
|
256
|
+
// be the caller's to damage. Anything else — an absent slot on an empty
|
|
257
|
+
// message, a primitive, an array — keeps the original assignment, which
|
|
258
|
+
// throws for exactly the inputs it threw for before and that upstream throws
|
|
259
|
+
// for too. Spreading those instead invented a property named `"undefined"`
|
|
260
|
+
// where upstream raised a TypeError.
|
|
261
|
+
if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) {
|
|
262
|
+
// One shallow spread, of exactly the object being modified. This is the
|
|
263
|
+
// whole cost of the fix, and it is unavoidable: not writing into the
|
|
264
|
+
// caller's object means writing into a different one.
|
|
265
|
+
content[key] = { ...nested, contextInfo };
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
nested.contextInfo = contextInfo;
|
|
269
|
+
}
|
|
270
|
+
return content;
|
|
271
|
+
};
|
|
272
|
+
export const hasNonNullishProperty = (message, key) => {
|
|
273
|
+
return (typeof message === 'object' &&
|
|
274
|
+
message !== null &&
|
|
275
|
+
key in message &&
|
|
276
|
+
message[key] !== null &&
|
|
277
|
+
message[key] !== undefined);
|
|
278
|
+
};
|
|
279
|
+
function hasOptionalProperty(obj, key) {
|
|
280
|
+
return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
|
|
281
|
+
}
|
|
282
|
+
export const generateWAMessageContent = async (message, options) => {
|
|
283
|
+
var _a, _b;
|
|
284
|
+
let m = {};
|
|
285
|
+
if (hasNonNullishProperty(message, 'text')) {
|
|
286
|
+
const extContent = { text: message.text };
|
|
287
|
+
let urlInfo = message.linkPreview;
|
|
288
|
+
// Gate on the resolver before awaiting: without one the helper resolves
|
|
289
|
+
// to undefined anyway, and every plain text send would still pay for a
|
|
290
|
+
// promise plus a microtask turn.
|
|
291
|
+
if (typeof urlInfo === 'undefined' && options.getUrlInfo) {
|
|
292
|
+
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
|
|
293
|
+
}
|
|
294
|
+
if (urlInfo) {
|
|
295
|
+
extContent.matchedText = urlInfo['matched-text'];
|
|
296
|
+
extContent.jpegThumbnail = urlInfo.jpegThumbnail;
|
|
297
|
+
extContent.description = urlInfo.description;
|
|
298
|
+
extContent.title = urlInfo.title;
|
|
299
|
+
extContent.previewType = 0;
|
|
300
|
+
const img = urlInfo.highQualityThumbnail;
|
|
301
|
+
if (img) {
|
|
302
|
+
extContent.thumbnailDirectPath = img.directPath;
|
|
303
|
+
extContent.mediaKey = img.mediaKey;
|
|
304
|
+
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
|
|
305
|
+
extContent.thumbnailWidth = img.width;
|
|
306
|
+
extContent.thumbnailHeight = img.height;
|
|
307
|
+
extContent.thumbnailSha256 = img.fileSha256;
|
|
308
|
+
extContent.thumbnailEncSha256 = img.fileEncSha256;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (options.backgroundColor) {
|
|
312
|
+
extContent.backgroundArgb = await assertColor(options.backgroundColor);
|
|
313
|
+
}
|
|
314
|
+
if (options.font) {
|
|
315
|
+
extContent.font = options.font;
|
|
316
|
+
}
|
|
317
|
+
m.extendedTextMessage = extContent;
|
|
318
|
+
}
|
|
319
|
+
else if (hasNonNullishProperty(message, 'contacts')) {
|
|
320
|
+
const contactLen = message.contacts.contacts.length;
|
|
321
|
+
if (!contactLen) {
|
|
322
|
+
throw new Boom('require atleast 1 contact', { statusCode: 400 });
|
|
323
|
+
}
|
|
324
|
+
if (contactLen === 1) {
|
|
325
|
+
m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else if (hasNonNullishProperty(message, 'location')) {
|
|
332
|
+
m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
|
|
333
|
+
}
|
|
334
|
+
else if (hasNonNullishProperty(message, 'react')) {
|
|
335
|
+
if (!message.react.senderTimestampMs) {
|
|
336
|
+
message.react.senderTimestampMs = Date.now();
|
|
337
|
+
}
|
|
338
|
+
m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
|
|
339
|
+
}
|
|
340
|
+
else if (hasNonNullishProperty(message, 'delete')) {
|
|
341
|
+
m.protocolMessage = {
|
|
342
|
+
key: message.delete,
|
|
343
|
+
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
else if (hasNonNullishProperty(message, 'forward')) {
|
|
347
|
+
m = generateForwardMessageContent(message.forward, message.force);
|
|
348
|
+
}
|
|
349
|
+
else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
|
|
350
|
+
const exp = typeof message.disappearingMessagesInChat === 'boolean'
|
|
351
|
+
? message.disappearingMessagesInChat
|
|
352
|
+
? WA_DEFAULT_EPHEMERAL
|
|
353
|
+
: 0
|
|
354
|
+
: message.disappearingMessagesInChat;
|
|
355
|
+
m = prepareDisappearingMessageSettingContent(exp);
|
|
356
|
+
}
|
|
357
|
+
else if (hasNonNullishProperty(message, 'groupInvite')) {
|
|
358
|
+
m.groupInviteMessage = {};
|
|
359
|
+
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
|
|
360
|
+
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
|
|
361
|
+
m.groupInviteMessage.caption = message.groupInvite.text;
|
|
362
|
+
m.groupInviteMessage.groupJid = message.groupInvite.jid;
|
|
363
|
+
m.groupInviteMessage.groupName = message.groupInvite.subject;
|
|
364
|
+
//TODO: use built-in interface and get disappearing mode info etc.
|
|
365
|
+
//TODO: cache / use store!?
|
|
366
|
+
if (options.getProfilePicUrl) {
|
|
367
|
+
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
|
|
368
|
+
if (pfpUrl) {
|
|
369
|
+
const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
|
|
370
|
+
if (resp.ok) {
|
|
371
|
+
const buf = BufferRuntime.from(await resp.arrayBuffer());
|
|
372
|
+
m.groupInviteMessage.jpegThumbnail = buf;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
else if (hasNonNullishProperty(message, 'pin')) {
|
|
378
|
+
m.pinInChatMessage = {};
|
|
379
|
+
m.messageContextInfo = {};
|
|
380
|
+
m.pinInChatMessage.key = message.pin;
|
|
381
|
+
m.pinInChatMessage.type = message.type;
|
|
382
|
+
m.pinInChatMessage.senderTimestampMs = Date.now();
|
|
383
|
+
m.messageContextInfo.messageAddOnDurationInSecs =
|
|
384
|
+
message.type === proto.PinInChat.Type.PIN_FOR_ALL ? message.time || 86400 : 0;
|
|
385
|
+
}
|
|
386
|
+
else if (hasNonNullishProperty(message, 'buttonReply')) {
|
|
387
|
+
switch (message.type) {
|
|
388
|
+
case 'template':
|
|
389
|
+
m.templateButtonReplyMessage = {
|
|
390
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
391
|
+
selectedId: message.buttonReply.id,
|
|
392
|
+
selectedIndex: message.buttonReply.index
|
|
393
|
+
};
|
|
394
|
+
break;
|
|
395
|
+
case 'plain':
|
|
396
|
+
m.buttonsResponseMessage = {
|
|
397
|
+
selectedButtonId: message.buttonReply.id,
|
|
398
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
399
|
+
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
|
400
|
+
};
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
|
|
405
|
+
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
|
|
406
|
+
m.ptvMessage = videoMessage;
|
|
407
|
+
}
|
|
408
|
+
else if (hasNonNullishProperty(message, 'product')) {
|
|
409
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
|
|
410
|
+
m.productMessage = WAProto.Message.ProductMessage.create({
|
|
411
|
+
...message,
|
|
412
|
+
product: {
|
|
413
|
+
...message.product,
|
|
414
|
+
productImage: imageMessage
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
else if (hasNonNullishProperty(message, 'listReply')) {
|
|
419
|
+
m.listResponseMessage = { ...message.listReply };
|
|
420
|
+
}
|
|
421
|
+
else if (hasNonNullishProperty(message, 'event')) {
|
|
422
|
+
m.eventMessage = {};
|
|
423
|
+
const startTime = Math.floor(message.event.startDate.getTime() / 1000);
|
|
424
|
+
if (message.event.call && options.getCallLink) {
|
|
425
|
+
const token = await options.getCallLink(message.event.call, { startTime });
|
|
426
|
+
m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
|
|
427
|
+
}
|
|
428
|
+
m.eventMessage.name = message.event.name;
|
|
429
|
+
m.eventMessage.description = message.event.description;
|
|
430
|
+
m.eventMessage.startTime = startTime;
|
|
431
|
+
m.eventMessage.endTime = message.event.endDate ? Math.floor(message.event.endDate.getTime() / 1000) : undefined;
|
|
432
|
+
m.eventMessage.isCanceled = message.event.isCancelled ?? false;
|
|
433
|
+
m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
|
|
434
|
+
m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
|
|
435
|
+
m.eventMessage.location = message.event.location;
|
|
436
|
+
// The sender's copy of the key that encrypts responses to this event;
|
|
437
|
+
// `decryptEventResponse` takes it as `eventEncKey`. WhatsApp Web writes it
|
|
438
|
+
// on the sender at creation (`WAWebSendEventCreationMsgAction`) and refuses
|
|
439
|
+
// to build an event edit without it (`WAWebCreateEncryptedEventEditMsgData`
|
|
440
|
+
// throws `EventCreationValidationError`).
|
|
441
|
+
//
|
|
442
|
+
// The core settles `messageSecret` on relay for messages that reach it
|
|
443
|
+
// without one — see the comment in `Socket/messages.ts` — but it settles it
|
|
444
|
+
// on the wire, where the caller never sees it. That is right for the
|
|
445
|
+
// reporting token and wrong for a key the caller has to keep.
|
|
446
|
+
//
|
|
447
|
+
// Written after `m.eventMessage`, for the reason spelled out on the poll
|
|
448
|
+
// branch below: the blocks that attach `contextInfo` take `Object.keys(m)[0]`
|
|
449
|
+
// as the content key. `event` is not `Mentionable` or `Contextable` today,
|
|
450
|
+
// so this is ordering that stays correct rather than ordering that is
|
|
451
|
+
// currently load-bearing — but it costs nothing and the poll branch shows
|
|
452
|
+
// what getting it wrong looks like.
|
|
453
|
+
//
|
|
454
|
+
// Spread rather than upstream's wholesale assignment: nothing else writes
|
|
455
|
+
// `messageContextInfo` on this branch today, so the two cannot differ, and
|
|
456
|
+
// this cannot silently drop a field a later change puts there.
|
|
457
|
+
m.messageContextInfo = {
|
|
458
|
+
...m.messageContextInfo,
|
|
459
|
+
messageSecret: message.event.messageSecret || BufferRuntime.from((options.runtimeRandomBytes ?? randomBytes)(32))
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
else if (hasNonNullishProperty(message, 'poll')) {
|
|
463
|
+
(_a = message.poll).selectableCount || (_a.selectableCount = 0);
|
|
464
|
+
(_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
|
|
465
|
+
if (!Array.isArray(message.poll.values)) {
|
|
466
|
+
throw new Boom('Invalid poll values', { statusCode: 400 });
|
|
467
|
+
}
|
|
468
|
+
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
|
469
|
+
throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
|
|
470
|
+
statusCode: 400
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
const pollCreationMessage = {
|
|
474
|
+
name: message.poll.name,
|
|
475
|
+
selectableOptionsCount: message.poll.selectableCount,
|
|
476
|
+
options: message.poll.values.map(optionName => ({ optionName }))
|
|
477
|
+
};
|
|
478
|
+
if (message.poll.toAnnouncementGroup) {
|
|
479
|
+
// poll v2 is for community announcement groups (single select and multiple)
|
|
480
|
+
m.pollCreationMessageV2 = pollCreationMessage;
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
if (message.poll.selectableCount === 1) {
|
|
484
|
+
//poll v3 is for single select polls
|
|
485
|
+
m.pollCreationMessageV3 = pollCreationMessage;
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
// poll for multiple choice polls
|
|
489
|
+
m.pollCreationMessage = pollCreationMessage;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
// The key that encrypts the votes. `decryptPollVote` takes it as
|
|
493
|
+
// `pollEncKey`, and without it here the poll goes out fine but its own
|
|
494
|
+
// sender can never read the votes: the copy they store — the message
|
|
495
|
+
// `sendMessage` returns and emits as `messages.upsert` — is this object,
|
|
496
|
+
// and only `key.id` is patched from the relay result. WhatsApp Web writes it
|
|
497
|
+
// on the sender at creation too (`WAWebPollsSendPollCreationMsgAction`) and
|
|
498
|
+
// reuses the stored one for poll edits
|
|
499
|
+
// (`WAWebPollsGeneratePollEditMessageProto`).
|
|
500
|
+
//
|
|
501
|
+
// After the payload, not before, and that ordering is load-bearing: the
|
|
502
|
+
// `mentions` and `contextInfo` blocks below pick their target with
|
|
503
|
+
// `Object.keys(m)[0]`, so a `messageContextInfo` written first becomes the
|
|
504
|
+
// content key they attach to. `contextInfo` is not a field of
|
|
505
|
+
// `IMessageContextInfo`, so the encoder drops it and a poll sent with
|
|
506
|
+
// mentions loses them silently. `poll` is `Mentionable & Contextable`, so
|
|
507
|
+
// that is a combination callers can and do write. Upstream assigns it
|
|
508
|
+
// before the payload and has exactly that bug; measured on
|
|
509
|
+
// `{poll, mentions:['x@s.whatsapp.net']}`, its output carries no
|
|
510
|
+
// `mentionedJid` at all.
|
|
511
|
+
m.messageContextInfo = {
|
|
512
|
+
...m.messageContextInfo,
|
|
513
|
+
messageSecret: message.poll.messageSecret || BufferRuntime.from((options.runtimeRandomBytes ?? randomBytes)(32))
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
|
|
517
|
+
m.protocolMessage = {
|
|
518
|
+
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
|
|
522
|
+
m.requestPhoneNumberMessage = {};
|
|
523
|
+
}
|
|
524
|
+
else if (hasNonNullishProperty(message, 'limitSharing')) {
|
|
525
|
+
m.protocolMessage = {
|
|
526
|
+
type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
|
|
527
|
+
limitSharing: {
|
|
528
|
+
sharingLimited: message.limitSharing === true,
|
|
529
|
+
trigger: 1,
|
|
530
|
+
limitSharingSettingTimestamp: Date.now(),
|
|
531
|
+
initiatedByMe: true
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
else {
|
|
536
|
+
m = await prepareWAMessageMedia(message, options);
|
|
537
|
+
}
|
|
538
|
+
if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
|
539
|
+
m = { viewOnceMessage: { message: m } };
|
|
540
|
+
}
|
|
541
|
+
if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
|
|
542
|
+
(hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
|
|
543
|
+
const messageType = Object.keys(m)[0];
|
|
544
|
+
const key = m[messageType];
|
|
545
|
+
// `contextInfo` is declared by the proto schema but isn't an own
|
|
546
|
+
// property on freshly-built messages — create-if-absent, then merge.
|
|
547
|
+
if (key && typeof key === 'object') {
|
|
548
|
+
const target = key;
|
|
549
|
+
const ci = (target.contextInfo ?? (target.contextInfo = {}));
|
|
550
|
+
if (message.mentions?.length) {
|
|
551
|
+
ci.mentionedJid = message.mentions;
|
|
552
|
+
}
|
|
553
|
+
if (message.mentionAll) {
|
|
554
|
+
ci.nonJidMentions = 1;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
if (hasOptionalProperty(message, 'edit')) {
|
|
559
|
+
m = {
|
|
560
|
+
protocolMessage: {
|
|
561
|
+
key: message.edit,
|
|
562
|
+
editedMessage: m,
|
|
563
|
+
timestampMs: Date.now(),
|
|
564
|
+
type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
|
|
569
|
+
const messageType = Object.keys(m)[0];
|
|
570
|
+
const key = m[messageType];
|
|
571
|
+
if (key) {
|
|
572
|
+
key.contextInfo = key.contextInfo ? Object.assign(key.contextInfo, message.contextInfo) : message.contextInfo;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
return WAProto.Message.create(m);
|
|
576
|
+
};
|
|
577
|
+
export const generateWAMessageFromContent = (jid, message, options) => {
|
|
578
|
+
const innerMessage = normalizeMessageContent(message);
|
|
579
|
+
const timestamp = unixTimestampSeconds(options.timestamp);
|
|
580
|
+
const { quoted, userJid } = options;
|
|
581
|
+
// Only the quote and ephemeral branches read the content key, and a plain
|
|
582
|
+
// send takes neither, so resolve it on demand instead of on every send.
|
|
583
|
+
let key;
|
|
584
|
+
if (quoted && !isJidNewsletter(jid)) {
|
|
585
|
+
const contentKey = getContentType(innerMessage);
|
|
586
|
+
key = contentKey;
|
|
587
|
+
const participant = quoted.key.fromMe
|
|
588
|
+
? userJid // TODO: Add support for LIDs
|
|
589
|
+
: quoted.participant || quoted.key.participant || quoted.key.remoteJid;
|
|
590
|
+
let quotedMsg = normalizeMessageContent(quoted.message);
|
|
591
|
+
const msgType = getContentType(quotedMsg);
|
|
592
|
+
// strip any redundant properties
|
|
593
|
+
quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
|
|
594
|
+
const quotedContent = quotedMsg[msgType];
|
|
595
|
+
if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
|
|
596
|
+
delete quotedContent.contextInfo;
|
|
597
|
+
}
|
|
598
|
+
const contextInfo = ('contextInfo' in innerMessage[contentKey] && innerMessage[contentKey]?.contextInfo) || {};
|
|
599
|
+
contextInfo.participant = jidNormalizedUser(participant);
|
|
600
|
+
contextInfo.stanzaId = quoted.key.id;
|
|
601
|
+
contextInfo.quotedMessage = quotedMsg;
|
|
602
|
+
// if a participant is quoted, then it must be a group
|
|
603
|
+
// hence, remoteJid of group must also be entered
|
|
604
|
+
if (jid !== quoted.key.remoteJid) {
|
|
605
|
+
contextInfo.remoteJid = quoted.key.remoteJid;
|
|
606
|
+
}
|
|
607
|
+
if (contextInfo && innerMessage[contentKey]) {
|
|
608
|
+
/* @ts-ignore */
|
|
609
|
+
innerMessage[contentKey].contextInfo = contextInfo;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (
|
|
613
|
+
// if we want to send a disappearing message
|
|
614
|
+
!!options?.ephemeralExpiration &&
|
|
615
|
+
// newsletters don't support ephemeral messages
|
|
616
|
+
!isJidNewsletter(jid)) {
|
|
617
|
+
const contentKey = key ?? getContentType(innerMessage);
|
|
618
|
+
// skip protocol messages -- delete, toggle disappear message -- and
|
|
619
|
+
// content already converted to a disappearing message
|
|
620
|
+
if (contentKey !== 'protocolMessage' && contentKey !== 'ephemeralMessage') {
|
|
621
|
+
/* @ts-ignore */
|
|
622
|
+
innerMessage[contentKey].contextInfo = {
|
|
623
|
+
...innerMessage[contentKey].contextInfo,
|
|
624
|
+
expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
|
|
625
|
+
//ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
// `create` copies into a fresh instance; content built by
|
|
630
|
+
// `generateWAMessageContent` already is one, and the branches above mutate
|
|
631
|
+
// it in place regardless, so copying it again only duplicates the tree.
|
|
632
|
+
if (!(message instanceof WAProto.Message))
|
|
633
|
+
message = WAProto.Message.create(message);
|
|
634
|
+
// Direct construction instead of a `WebMessageInfo.fromObject` envelope:
|
|
635
|
+
// every value is already in its runtime type (`message` came from
|
|
636
|
+
// `Message.create` above), so the schema walk would only re-derive them.
|
|
637
|
+
// `new` keeps protobufjs parity, including the constructor's own
|
|
638
|
+
// `messageStubParameters` array. The `Long` cast mirrors the published
|
|
639
|
+
// facade shape for 64-bit fields (source-side WAProto types them as plain
|
|
640
|
+
// numbers via the bridge shapes).
|
|
641
|
+
const messageKey = new WAProto.MessageKey();
|
|
642
|
+
messageKey.remoteJid = jid;
|
|
643
|
+
messageKey.fromMe = true;
|
|
644
|
+
messageKey.id = options?.messageId || ''; // Rust generates the real message ID
|
|
645
|
+
const wm = new WAProto.WebMessageInfo();
|
|
646
|
+
wm.key = messageKey;
|
|
647
|
+
wm.message = message;
|
|
648
|
+
wm.messageTimestamp = (options.runtimeLong ?? LongRuntime).fromValue(timestamp);
|
|
649
|
+
// TODO: Add support for LIDs
|
|
650
|
+
const participant = isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined;
|
|
651
|
+
if (participant !== undefined)
|
|
652
|
+
wm.participant = participant;
|
|
653
|
+
wm.status = WAMessageStatus.PENDING;
|
|
654
|
+
return wm;
|
|
655
|
+
};
|
|
656
|
+
export const generateWAMessage = async (jid, content, options) => {
|
|
657
|
+
const contentOptions = options.messageId && options.logger
|
|
658
|
+
? { ...options, logger: options.logger.child({ msgId: options.messageId }) }
|
|
659
|
+
: options;
|
|
660
|
+
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, contentOptions), options);
|
|
661
|
+
};
|
|
662
|
+
/**
|
|
663
|
+
* The content keys that carry almost every message on a live socket, settled by
|
|
664
|
+
* identity before the structural predicate runs. Every name here already
|
|
665
|
+
* satisfies that predicate, so this only shortcuts the substring scan; it never
|
|
666
|
+
* changes which key wins.
|
|
667
|
+
*/
|
|
668
|
+
const isCommonContentKey = (key) => {
|
|
669
|
+
switch (key) {
|
|
670
|
+
case 'conversation':
|
|
671
|
+
case 'extendedTextMessage':
|
|
672
|
+
case 'imageMessage':
|
|
673
|
+
case 'videoMessage':
|
|
674
|
+
case 'audioMessage':
|
|
675
|
+
case 'stickerMessage':
|
|
676
|
+
case 'documentMessage':
|
|
677
|
+
case 'reactionMessage':
|
|
678
|
+
case 'protocolMessage':
|
|
679
|
+
case 'pollCreationMessage':
|
|
680
|
+
return true;
|
|
681
|
+
default:
|
|
682
|
+
return false;
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
/** Get the key to access the true type of content */
|
|
686
|
+
export const getContentType = (content) => {
|
|
687
|
+
if (!content) {
|
|
688
|
+
return undefined;
|
|
689
|
+
}
|
|
690
|
+
// The answer stays positional (the first own key naming content wins), but
|
|
691
|
+
// the scan is an indexed loop with an early return instead of `Array.find`,
|
|
692
|
+
// so no closure is allocated and the common keys never reach `includes`.
|
|
693
|
+
//
|
|
694
|
+
// Deliberately still `Object.keys` and not `for..in`: a decoded
|
|
695
|
+
// `WAProto.Message` inherits a default for every field of the schema, so
|
|
696
|
+
// `for..in` would enumerate ~100 prototype keys per call (and would have to
|
|
697
|
+
// filter them back out with `hasOwn` to stay positional) where `Object.keys`
|
|
698
|
+
// yields only the handful that were actually set.
|
|
699
|
+
const keys = Object.keys(content);
|
|
700
|
+
for (let i = 0; i < keys.length; i++) {
|
|
701
|
+
const key = keys[i];
|
|
702
|
+
if (isCommonContentKey(key)) {
|
|
703
|
+
return key;
|
|
704
|
+
}
|
|
705
|
+
if (key.includes('Message') && key !== 'senderKeyDistributionMessage') {
|
|
706
|
+
return key;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return undefined;
|
|
710
|
+
};
|
|
711
|
+
const getFutureProofMessage = (message) => message?.ephemeralMessage ||
|
|
712
|
+
message?.viewOnceMessage ||
|
|
713
|
+
message?.documentWithCaptionMessage ||
|
|
714
|
+
message?.viewOnceMessageV2 ||
|
|
715
|
+
message?.viewOnceMessageV2Extension ||
|
|
716
|
+
message?.editedMessage ||
|
|
717
|
+
message?.associatedChildMessage ||
|
|
718
|
+
message?.groupStatusMessage ||
|
|
719
|
+
message?.groupStatusMessageV2;
|
|
720
|
+
const extractFromTemplateMessage = (msg) => {
|
|
721
|
+
if (msg.imageMessage) {
|
|
722
|
+
return { imageMessage: msg.imageMessage };
|
|
723
|
+
}
|
|
724
|
+
else if (msg.documentMessage) {
|
|
725
|
+
return { documentMessage: msg.documentMessage };
|
|
726
|
+
}
|
|
727
|
+
else if (msg.videoMessage) {
|
|
728
|
+
return { videoMessage: msg.videoMessage };
|
|
729
|
+
}
|
|
730
|
+
else if (msg.locationMessage) {
|
|
731
|
+
return { locationMessage: msg.locationMessage };
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
return {
|
|
735
|
+
conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
/**
|
|
740
|
+
* Normalizes ephemeral, view once messages to regular message content
|
|
741
|
+
* Eg. image messages in ephemeral messages, in view once messages etc.
|
|
742
|
+
* @param content
|
|
743
|
+
* @returns
|
|
744
|
+
*/
|
|
745
|
+
export const normalizeMessageContent = (content) => {
|
|
746
|
+
if (!content) {
|
|
747
|
+
return undefined;
|
|
748
|
+
}
|
|
749
|
+
// set max iterations to prevent an infinite loop
|
|
750
|
+
for (let i = 0; i < 5; i++) {
|
|
751
|
+
const inner = getFutureProofMessage(content);
|
|
752
|
+
if (!inner) {
|
|
753
|
+
break;
|
|
754
|
+
}
|
|
755
|
+
content = inner.message;
|
|
756
|
+
}
|
|
757
|
+
return content;
|
|
758
|
+
};
|
|
759
|
+
/**
|
|
760
|
+
* Extract the true message content from a message
|
|
761
|
+
* Eg. extracts the inner message from a disappearing message/view once message
|
|
762
|
+
*/
|
|
763
|
+
export const extractMessageContent = (content) => {
|
|
764
|
+
content = normalizeMessageContent(content);
|
|
765
|
+
if (content?.buttonsMessage) {
|
|
766
|
+
return extractFromTemplateMessage(content.buttonsMessage);
|
|
767
|
+
}
|
|
768
|
+
if (content?.templateMessage?.hydratedFourRowTemplate) {
|
|
769
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
|
|
770
|
+
}
|
|
771
|
+
if (content?.templateMessage?.hydratedTemplate) {
|
|
772
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
|
|
773
|
+
}
|
|
774
|
+
if (content?.templateMessage?.fourRowTemplate) {
|
|
775
|
+
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
|
|
776
|
+
}
|
|
777
|
+
return content;
|
|
778
|
+
};
|
|
779
|
+
export const MEDIA_DOWNLOAD_TYPES = ['buffer', 'stream'];
|
|
780
|
+
/**
|
|
781
|
+
* Downloads the given message. Throws an error if it's not a media message.
|
|
782
|
+
*
|
|
783
|
+
* Uses the Rust bridge for download — provides CDN failover, automatic auth
|
|
784
|
+
* refresh on 401/404, HMAC-SHA256 integrity verification, and AES-256-CBC
|
|
785
|
+
* decryption, so a bridge client has to reach it.
|
|
786
|
+
*
|
|
787
|
+
* `ctx` is optional, as upstream has it: without one the client registered by
|
|
788
|
+
* the most recent `makeWASocket` is used, the same fallback
|
|
789
|
+
* `downloadContentFromMessage` offers for standalone calls. A host juggling
|
|
790
|
+
* several sockets should pass `ctx` explicitly, because the registration points
|
|
791
|
+
* at whichever client was created last.
|
|
792
|
+
*/
|
|
793
|
+
export const downloadMediaMessage = async (message, type, options, ctx) => {
|
|
794
|
+
// Anything but 'buffer' used to take the stream branch, so a typo returned
|
|
795
|
+
// a Readable to a caller holding it as a Buffer.
|
|
796
|
+
assertArgumentDomain('downloadMediaMessage', 'type', type, MEDIA_DOWNLOAD_TYPES);
|
|
797
|
+
const waClient = ctx?.waClient ?? activeBridgeClient;
|
|
798
|
+
if (!waClient) {
|
|
799
|
+
throw new Boom('downloadMediaMessage: no bridge client available, and the download, its CDN failover and its decryption all happen in the engine. Pass `{ waClient: sock.waClient }`, use `sock.downloadMedia(message, type, options)`, or call after `makeWASocket()` has initialized.', { statusCode: 500 });
|
|
800
|
+
}
|
|
801
|
+
const withClient = { ...ctx, waClient };
|
|
802
|
+
return (await downloadMsg());
|
|
803
|
+
async function downloadMsg() {
|
|
804
|
+
const mContent = extractMessageContent(message.message);
|
|
805
|
+
if (!mContent) {
|
|
806
|
+
throw new Boom('No message present', { statusCode: 400, data: message });
|
|
807
|
+
}
|
|
808
|
+
const contentType = getContentType(mContent);
|
|
809
|
+
let mediaType = String(contentType)?.replace('Message', '');
|
|
810
|
+
const media = mContent[contentType];
|
|
811
|
+
if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
|
812
|
+
throw new Boom(`"${String(contentType)}" message is not a media message`);
|
|
813
|
+
}
|
|
814
|
+
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
|
815
|
+
mediaType = 'thumbnail-link';
|
|
816
|
+
}
|
|
817
|
+
if (!('directPath' in media) || !media.directPath || !('mediaKey' in media) || !media.mediaKey) {
|
|
818
|
+
throw new Boom('Media message missing directPath or mediaKey', { statusCode: 400 });
|
|
819
|
+
}
|
|
820
|
+
const mediaObj = media;
|
|
821
|
+
if (!mediaObj.fileSha256 || !mediaObj.fileEncSha256) {
|
|
822
|
+
throw new Boom('Media message missing fileSha256 or fileEncSha256', { statusCode: 400 });
|
|
823
|
+
}
|
|
824
|
+
const args = [
|
|
825
|
+
mediaObj.directPath,
|
|
826
|
+
mediaObj.mediaKey,
|
|
827
|
+
mediaObj.fileSha256,
|
|
828
|
+
mediaObj.fileEncSha256,
|
|
829
|
+
toNumber(mediaObj.fileLength ?? 0),
|
|
830
|
+
toBridgeMediaType(mediaType)
|
|
831
|
+
];
|
|
832
|
+
if (type === 'buffer') {
|
|
833
|
+
const data = await withClient.waClient.downloadMedia(...args);
|
|
834
|
+
return BufferRuntime.from(data);
|
|
835
|
+
}
|
|
836
|
+
// Stream mode: Web ReadableStream from Rust → Node.js Readable
|
|
837
|
+
const webStream = withClient.waClient.downloadMediaStream(...args);
|
|
838
|
+
return readableFromWeb(webStream);
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
/**
|
|
842
|
+
* Module-level pointer to the most-recently created bridge client. Updated by
|
|
843
|
+
* `makeWASocket` so standalone helpers like {@link downloadContentFromMessage}
|
|
844
|
+
* (which carry no socket reference) can find the bridge without forcing the
|
|
845
|
+
* caller to plumb `waClient` through. Multi-account hosts that juggle several
|
|
846
|
+
* sockets should pass `opts.client` explicitly; otherwise this points at the
|
|
847
|
+
* client created last.
|
|
848
|
+
*/
|
|
849
|
+
let activeBridgeClient;
|
|
850
|
+
let activeBridgeLogger;
|
|
851
|
+
export const _registerActiveBridgeClient = (client, logger) => {
|
|
852
|
+
activeBridgeClient = client;
|
|
853
|
+
activeBridgeLogger = logger;
|
|
854
|
+
};
|
|
855
|
+
/**
|
|
856
|
+
* Drop the module-level pointer when `sock.end()` frees the client it points
|
|
857
|
+
* at. Without this the global keeps a strong reference to a freed
|
|
858
|
+
* `WasmWhatsAppClient`, so the next standalone `downloadContentFromMessage()`
|
|
859
|
+
* call reaches into a null wasm pointer and fails with an opaque
|
|
860
|
+
* wasm-bindgen error instead of the actionable "no bridge client" Boom.
|
|
861
|
+
*
|
|
862
|
+
* Identity-checked on purpose: a multi-account host that ends socket A after
|
|
863
|
+
* creating socket B must not clear B's registration.
|
|
864
|
+
*/
|
|
865
|
+
export const _unregisterActiveBridgeClient = (client) => {
|
|
866
|
+
if (activeBridgeClient !== client)
|
|
867
|
+
return;
|
|
868
|
+
activeBridgeClient = undefined;
|
|
869
|
+
activeBridgeLogger = undefined;
|
|
870
|
+
};
|
|
871
|
+
const noopLogger = {
|
|
872
|
+
level: 'silent',
|
|
873
|
+
child: () => noopLogger,
|
|
874
|
+
trace: () => { },
|
|
875
|
+
debug: () => { },
|
|
876
|
+
info: () => { },
|
|
877
|
+
warn: () => { },
|
|
878
|
+
error: () => { }
|
|
879
|
+
};
|
|
880
|
+
/**
|
|
881
|
+
* Upstream-Baileys-compatible standalone media download. Builds a synthetic
|
|
882
|
+
* `WAMessage` from the supplied media subcontent (image/video/audio/etc fields)
|
|
883
|
+
* and routes it through {@link downloadMediaMessage}, so CDN failover, auth
|
|
884
|
+
* refresh, HMAC verification, and AES-256-CBC decryption all happen inside the
|
|
885
|
+
* Rust bridge — same code path as `sock.downloadMedia`.
|
|
886
|
+
*
|
|
887
|
+
* The bridge client is required. Pass it explicitly via `opts.client` for
|
|
888
|
+
* multi-account hosts; otherwise the helper falls back to the most-recently
|
|
889
|
+
* created bridge client (registered automatically by `makeWASocket`).
|
|
890
|
+
*/
|
|
891
|
+
export const downloadContentFromMessage = async (mediaContent, type, opts = {}) => {
|
|
892
|
+
const client = opts.client ?? activeBridgeClient;
|
|
893
|
+
if (!client) {
|
|
894
|
+
throw new Boom('downloadContentFromMessage: no bridge client available. ' +
|
|
895
|
+
'Pass `opts.client = sock.waClient`, or call after `makeWASocket()` has initialized.', { statusCode: 500 });
|
|
896
|
+
}
|
|
897
|
+
// `url` is seeded because the media guard downstream keys off its presence,
|
|
898
|
+
// and content addressed only by `directPath` (history-sync notifications
|
|
899
|
+
// carry no `url` field at all) would otherwise be rejected as non-media.
|
|
900
|
+
const fakeMessage = {
|
|
901
|
+
key: {},
|
|
902
|
+
message: { [`${type}Message`]: { url: null, ...mediaContent } }
|
|
903
|
+
};
|
|
904
|
+
return downloadMediaMessage(fakeMessage, 'stream', opts, {
|
|
905
|
+
logger: opts.logger ?? activeBridgeLogger ?? noopLogger,
|
|
906
|
+
reuploadRequest: async (m) => m,
|
|
907
|
+
waClient: client
|
|
908
|
+
});
|
|
909
|
+
};
|
|
910
|
+
/** Infer the originating client family from WhatsApp's message-id format. */
|
|
911
|
+
export const getDevice = (id) => /^3A.{18}$/.test(id)
|
|
912
|
+
? 'ios'
|
|
913
|
+
: /^3E.{20}$/.test(id)
|
|
914
|
+
? 'web'
|
|
915
|
+
: /^(.{21}|.{32})$/.test(id)
|
|
916
|
+
? 'android'
|
|
917
|
+
: /^(3F|.{18}$)/.test(id)
|
|
918
|
+
? 'desktop'
|
|
919
|
+
: 'unknown';
|
|
920
|
+
/**
|
|
921
|
+
* Aggregate votes from a poll message.
|
|
922
|
+
*
|
|
923
|
+
* Takes a poll creation message and its accumulated poll updates (from
|
|
924
|
+
* `messages.update` events) and returns the vote tally per option.
|
|
925
|
+
*
|
|
926
|
+
* `pollUpdates` should contain pre-decrypted votes where `vote.selectedOptions`
|
|
927
|
+
* are the SHA-256 hashes of the voted option names.
|
|
928
|
+
*
|
|
929
|
+
* @example
|
|
930
|
+
* ```ts
|
|
931
|
+
* sock.ev.on('messages.update', event => {
|
|
932
|
+
* for (const { key, update } of event) {
|
|
933
|
+
* if (update.pollUpdates) {
|
|
934
|
+
* const pollMsg = await getMessageFromStore(key)
|
|
935
|
+
* const votes = getAggregateVotesInPollMessage({
|
|
936
|
+
* message: pollMsg.message,
|
|
937
|
+
* pollUpdates: pollMsg.pollUpdates
|
|
938
|
+
* })
|
|
939
|
+
* console.log(votes) // [{ name: 'Yes', voters: ['jid1'] }, ...]
|
|
940
|
+
* }
|
|
941
|
+
* }
|
|
942
|
+
* })
|
|
943
|
+
* ```
|
|
944
|
+
*/
|
|
945
|
+
export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
|
|
946
|
+
const opts = message?.pollCreationMessage?.options ||
|
|
947
|
+
message?.pollCreationMessageV2?.options ||
|
|
948
|
+
message?.pollCreationMessageV3?.options ||
|
|
949
|
+
[];
|
|
950
|
+
const voteHashMap = {};
|
|
951
|
+
for (const opt of opts) {
|
|
952
|
+
const name = opt.optionName || '';
|
|
953
|
+
voteHashMap[hexEncode(sha256Sync(utf8Encode(name)))] = { name, voters: [] };
|
|
954
|
+
}
|
|
955
|
+
for (const update of pollUpdates || []) {
|
|
956
|
+
const { vote } = update;
|
|
957
|
+
if (!vote?.selectedOptions?.length)
|
|
958
|
+
continue;
|
|
959
|
+
for (const optionHash of vote.selectedOptions) {
|
|
960
|
+
const hash = hexEncode(optionHash);
|
|
961
|
+
let aggregate = voteHashMap[hash];
|
|
962
|
+
if (!aggregate)
|
|
963
|
+
aggregate = voteHashMap[hash] = { name: 'Unknown', voters: [] };
|
|
964
|
+
aggregate.voters.push(getKeyAuthorPortable(update.pollUpdateMessageKey, meId));
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return Object.values(voteHashMap);
|
|
968
|
+
}
|
|
969
|
+
export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
|
|
970
|
+
const responseMap = {};
|
|
971
|
+
for (const response of ['GOING', 'NOT_GOING', 'MAYBE']) {
|
|
972
|
+
responseMap[response] = { response, responders: [] };
|
|
973
|
+
}
|
|
974
|
+
for (const update of eventResponses || []) {
|
|
975
|
+
// Decrypted event responses carry this convenience field at runtime;
|
|
976
|
+
// it is intentionally not part of the wire protobuf interface.
|
|
977
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
978
|
+
const responseType = update.eventResponse || 'UNKNOWN';
|
|
979
|
+
if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
|
|
980
|
+
responseMap[responseType].responders.push(getKeyAuthorPortable(update.eventResponseMessageKey, meId));
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
return Object.values(responseMap);
|
|
984
|
+
}
|
|
985
|
+
/** Group non-self message keys by chat and participant for bulk receipts. */
|
|
986
|
+
export const aggregateMessageKeysNotFromMe = (keys) => {
|
|
987
|
+
const keyMap = {};
|
|
988
|
+
for (const { remoteJid, id, participant, fromMe } of keys) {
|
|
989
|
+
if (fromMe)
|
|
990
|
+
continue;
|
|
991
|
+
const uniqueKey = `${remoteJid}:${participant || ''}`;
|
|
992
|
+
keyMap[uniqueKey] || (keyMap[uniqueKey] = { jid: remoteJid, participant: participant, messageIds: [] });
|
|
993
|
+
keyMap[uniqueKey].messageIds.push(id);
|
|
994
|
+
}
|
|
995
|
+
return Object.values(keyMap);
|
|
996
|
+
};
|
|
997
|
+
/** Upsert one receipt into a message's `userReceipt` collection. */
|
|
998
|
+
export const updateMessageWithReceipt = (msg, receipt) => {
|
|
999
|
+
msg.userReceipt = msg.userReceipt || [];
|
|
1000
|
+
const existing = msg.userReceipt.find(item => item.userJid === receipt.userJid);
|
|
1001
|
+
if (existing)
|
|
1002
|
+
Object.assign(existing, receipt);
|
|
1003
|
+
else
|
|
1004
|
+
msg.userReceipt.push(receipt);
|
|
1005
|
+
};
|
|
1006
|
+
/** Replace the previous reaction from the same author, then append the latest. */
|
|
1007
|
+
export const updateMessageWithReaction = (msg, reaction) => {
|
|
1008
|
+
const author = getKeyAuthorPortable(reaction.key || {});
|
|
1009
|
+
const reactions = (msg.reactions || []).filter(item => getKeyAuthorPortable(item.key || {}) !== author);
|
|
1010
|
+
reaction.text = reaction.text || '';
|
|
1011
|
+
reactions.push(reaction);
|
|
1012
|
+
msg.reactions = reactions;
|
|
1013
|
+
};
|
|
1014
|
+
/** Replace the previous poll update from the same author. Empty votes remove it. */
|
|
1015
|
+
export const updateMessageWithPollUpdate = (msg, update) => {
|
|
1016
|
+
const author = getKeyAuthorPortable(update.pollUpdateMessageKey);
|
|
1017
|
+
const pollUpdates = (msg.pollUpdates || []).filter(item => getKeyAuthorPortable(item.pollUpdateMessageKey) !== author);
|
|
1018
|
+
if (update.vote?.selectedOptions?.length)
|
|
1019
|
+
pollUpdates.push(update);
|
|
1020
|
+
msg.pollUpdates = pollUpdates;
|
|
1021
|
+
};
|
|
1022
|
+
/** Replace the previous event response from the same author. */
|
|
1023
|
+
export const updateMessageWithEventResponse = (msg, update) => {
|
|
1024
|
+
const author = getKeyAuthorPortable(update.eventResponseMessageKey);
|
|
1025
|
+
const responses = (msg.eventResponses || []).filter(item => getKeyAuthorPortable(item.eventResponseMessageKey) !== author);
|
|
1026
|
+
responses.push(update);
|
|
1027
|
+
msg.eventResponses = responses;
|
|
1028
|
+
};
|
|
1029
|
+
/** Checks whether the message contains one of the upstream media payloads. */
|
|
1030
|
+
export const assertMediaContent = (content) => {
|
|
1031
|
+
content = extractMessageContent(content);
|
|
1032
|
+
const mediaContent = content?.documentMessage ||
|
|
1033
|
+
content?.imageMessage ||
|
|
1034
|
+
content?.videoMessage ||
|
|
1035
|
+
content?.audioMessage ||
|
|
1036
|
+
content?.stickerMessage;
|
|
1037
|
+
if (!mediaContent) {
|
|
1038
|
+
throw new Boom('given message is not a media message', { statusCode: 400, data: content });
|
|
1039
|
+
}
|
|
1040
|
+
return mediaContent;
|
|
1041
|
+
};
|
|
1042
|
+
//# sourceMappingURL=messages-core.js.map
|