@hiroosy/baileys-lite 0.0.1
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 +25 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +115856 -0
- package/engine-requirements.js +11 -0
- package/package.json +27 -0
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +649 -0
- package/src/constants.js +143 -0
- package/src/defaults.js +102 -0
- package/src/foundation/audio-duration.js +530 -0
- package/src/foundation/audio-samples.js +268 -0
- package/src/foundation/boom.js +46 -0
- package/src/foundation/cache.js +142 -0
- package/src/foundation/concurrency.js +87 -0
- package/src/foundation/curve25519.js +221 -0
- package/src/foundation/link-preview.js +320 -0
- package/src/foundation/logger.js +69 -0
- package/src/foundation/long.js +140 -0
- package/src/foundation/protobuf-minimal.js +619 -0
- package/src/foundation/wa-crypto.js +76 -0
- package/src/foundation/zip.js +124 -0
- package/src/index.js +48 -0
- package/src/signal/libsignal.js +1051 -0
- package/src/signal/signal-group.js +487 -0
- package/src/signal/signal-repository.js +646 -0
- package/src/socket/business-communities.js +830 -0
- package/src/socket/chats.js +674 -0
- package/src/socket/groups-newsletter.js +342 -0
- package/src/socket/messages-recv.js +1835 -0
- package/src/socket/messages-send.js +1202 -0
- package/src/socket/socket-core.js +833 -0
- package/src/socket/usync.js +291 -0
- package/src/socket-client/websocket-client.js +124 -0
- package/src/utils/auth-state-core.js +764 -0
- package/src/utils/auth-state-storage.js +316 -0
- package/src/utils/chat-sync.js +1045 -0
- package/src/utils/media.js +841 -0
- package/src/utils/message-compose.js +1609 -0
- package/src/utils/message-processing.js +958 -0
- package/src/utils/wa-protocol-core.js +1283 -0
- package/src/vendor/jpeg-js/LICENSE +25 -0
- package/src/vendor/jpeg-js/decoder.js +1152 -0
- package/src/vendor/jpeg-js/encoder.js +824 -0
- package/src/vendor/pngjs/LICENSE +20 -0
- package/src/vendor/pngjs/bitmapper.js +273 -0
- package/src/vendor/pngjs/bitpacker.js +167 -0
- package/src/vendor/pngjs/constants.js +38 -0
- package/src/vendor/pngjs/crc.js +47 -0
- package/src/vendor/pngjs/filter-pack.js +179 -0
- package/src/vendor/pngjs/filter-parse-sync.js +27 -0
- package/src/vendor/pngjs/filter-parse.js +185 -0
- package/src/vendor/pngjs/format-normaliser.js +101 -0
- package/src/vendor/pngjs/interlace.js +101 -0
- package/src/vendor/pngjs/packer-sync.js +65 -0
- package/src/vendor/pngjs/packer.js +138 -0
- package/src/vendor/pngjs/paeth-predictor.js +22 -0
- package/src/vendor/pngjs/parser-sync.js +121 -0
- package/src/vendor/pngjs/parser.js +299 -0
- package/src/vendor/pngjs/png-sync.js +19 -0
- package/src/vendor/pngjs/sync-inflate.js +174 -0
- package/src/vendor/pngjs/sync-reader.js +54 -0
- package/src/wam/wam-constants.js +22853 -0
- package/src/wam/wam.js +151 -0
|
@@ -0,0 +1,1609 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message composition utilities. Combines what used to be messages.js and
|
|
3
|
+
* rich-message-utils.js. LANGUAGE_KEYWORDS (syntax-highlighting keyword lists)
|
|
4
|
+
* moved here from WABinary/constants.js, where it had been misplaced — it's
|
|
5
|
+
* message-composition data, not WA binary-protocol data.
|
|
6
|
+
*/
|
|
7
|
+
import { getRandomValues, randomBytes, randomUUID } from 'node:crypto'
|
|
8
|
+
import { promises as fs } from 'node:fs'
|
|
9
|
+
import { proto } from '../../WAProto/index.js'
|
|
10
|
+
import { Boom } from '../foundation/boom.js'
|
|
11
|
+
import { zip } from '../foundation/zip.js'
|
|
12
|
+
import {
|
|
13
|
+
AssociationType,
|
|
14
|
+
ButtonHeaderType,
|
|
15
|
+
ButtonType,
|
|
16
|
+
CarouselCardType,
|
|
17
|
+
CodeHighlightType,
|
|
18
|
+
ListType,
|
|
19
|
+
RichSubMessageType,
|
|
20
|
+
WAMessageStatus,
|
|
21
|
+
WAProto
|
|
22
|
+
} from '../constants.js'
|
|
23
|
+
import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../binary/wa-binary.js'
|
|
24
|
+
import { sha256, generateMessageIDV2, getKeyAuthor, unixTimestampSeconds, shouldIncludeReportingToken } from './wa-protocol-core.js'
|
|
25
|
+
import {
|
|
26
|
+
downloadContentFromMessage,
|
|
27
|
+
encryptedStream,
|
|
28
|
+
generateThumbnail,
|
|
29
|
+
getAudioDuration,
|
|
30
|
+
getAudioWaveform,
|
|
31
|
+
getImageProcessingLibrary,
|
|
32
|
+
getRawMediaUploadData,
|
|
33
|
+
getStream,
|
|
34
|
+
toBuffer
|
|
35
|
+
} from './media.js'
|
|
36
|
+
|
|
37
|
+
const LIBRARY_NAME = 'Baileys'
|
|
38
|
+
const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60
|
|
39
|
+
const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/'
|
|
40
|
+
const CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/'
|
|
41
|
+
const MEDIA_KEYS = ['image', 'video', 'audio', 'sticker', 'document']
|
|
42
|
+
export const URL_REGEX = /https:\/\/(?![^:@/\s]+:[^:@/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
|
43
|
+
const LEXER_REGEX =
|
|
44
|
+
/(\/\/.*|\/\*[\s\S]*?\*\/|#.*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[\s\S]*?`)|(\b[a-zA-Z_]\w*\b)(?=\s*\()|(\b[a-zA-Z_]\w*\b)|(\b\d+(?:\.\d+)?\b)|(\s+|[^\w\s]+)/g
|
|
45
|
+
|
|
46
|
+
const CONCURRENCY_LIMIT = 15
|
|
47
|
+
const MIMETYPE_MAP = {
|
|
48
|
+
image: 'image/jpeg',
|
|
49
|
+
video: 'video/mp4',
|
|
50
|
+
document: 'application/pdf',
|
|
51
|
+
audio: 'audio/ogg; codecs=opus',
|
|
52
|
+
sticker: 'image/webp',
|
|
53
|
+
'product-catalog-image': 'image/jpeg'
|
|
54
|
+
}
|
|
55
|
+
const MessageTypeProto = {
|
|
56
|
+
image: WAProto.Message.ImageMessage,
|
|
57
|
+
video: WAProto.Message.VideoMessage,
|
|
58
|
+
audio: WAProto.Message.AudioMessage,
|
|
59
|
+
sticker: WAProto.Message.StickerMessage,
|
|
60
|
+
document: WAProto.Message.DocumentMessage
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/* ------------------------------------------------------------------ */
|
|
64
|
+
/* Code syntax-highlighting keyword lists (for richResponseMessage) */
|
|
65
|
+
/* ------------------------------------------------------------------ */
|
|
66
|
+
|
|
67
|
+
const CPP_KEYWORDS = new Set([
|
|
68
|
+
'alignas','alignof','and','and_eq','asm','auto','bitand','bitor','bool','break','case',
|
|
69
|
+
'catch','char','class','compl','concept','const','consteval','constexpr','constinit',
|
|
70
|
+
'const_cast','continue','co_await','co_return','co_yield','decltype','default','delete',
|
|
71
|
+
'do','double','dynamic_cast','else','enum','explicit','export','extern','false','float',
|
|
72
|
+
'for','friend','goto','if','inline','int','long','mutable','namespace','new','noexcept',
|
|
73
|
+
'not','not_eq','nullptr','operator','or','or_eq','private','protected','public','register',
|
|
74
|
+
'reinterpret_cast','requires','return','short','signed','sizeof','static','static_assert',
|
|
75
|
+
'static_cast','struct','switch','template','this','thread_local','throw','true','try',
|
|
76
|
+
'typedef','typeid','typename','union','unsigned','using','virtual','void','volatile',
|
|
77
|
+
'wchar_t','while','xor','xor_eq'
|
|
78
|
+
])
|
|
79
|
+
const CSS_KEYWORDS = new Set([
|
|
80
|
+
'import','media','font-face','keyframes','supports','charset',
|
|
81
|
+
'important','root','hover','active','focus','visited','before','after',
|
|
82
|
+
'not','nth-child','first-child','last-child','only-child',
|
|
83
|
+
'none','inherit','initial','unset','auto','transparent','currentcolor'
|
|
84
|
+
])
|
|
85
|
+
const GO_KEYWORDS = new Set([
|
|
86
|
+
'break','default','func','interface','select','case','defer','go','map','struct',
|
|
87
|
+
'chan','else','goto','package','switch','const','fallthrough','if','range','type',
|
|
88
|
+
'continue','for','import','return','var','true','false','nil'
|
|
89
|
+
])
|
|
90
|
+
const HTML_KEYWORDS = new Set([
|
|
91
|
+
'html','head','body','title','meta','link','script','style',
|
|
92
|
+
'header','footer','main','section','article','aside','nav',
|
|
93
|
+
'div','span','h1','h2','h3','h4','h5','h6','p','a','img',
|
|
94
|
+
'ul','ol','li','table','tr','td','th','thead','tbody',
|
|
95
|
+
'form','input','button','select','textarea','label','option',
|
|
96
|
+
'canvas','svg','iframe','video','audio','source'
|
|
97
|
+
])
|
|
98
|
+
const JS_KEYWORDS = new Set([
|
|
99
|
+
'import','export','from','default','as',
|
|
100
|
+
'const','let','var','function','class','extends','new',
|
|
101
|
+
'return','if','else','for','while','do','switch','case','break','continue',
|
|
102
|
+
'try','catch','finally','throw',
|
|
103
|
+
'async','await','yield',
|
|
104
|
+
'typeof','instanceof','in','of','delete','void',
|
|
105
|
+
'true','false','null','undefined','NaN','Infinity',
|
|
106
|
+
'this','super','static','get','set',
|
|
107
|
+
'debugger','with'
|
|
108
|
+
])
|
|
109
|
+
const PYTHON_KEYWORDS = new Set([
|
|
110
|
+
'import','from','as','def','class','return','if','elif','else',
|
|
111
|
+
'for','while','break','continue','try','except','finally','raise',
|
|
112
|
+
'with','yield','lambda','pass','del','global','nonlocal','assert',
|
|
113
|
+
'True','False','None','and','or','not','in','is','async','await',
|
|
114
|
+
'self','print'
|
|
115
|
+
])
|
|
116
|
+
const RUST_KEYWORDS = new Set([
|
|
117
|
+
'as','break','const','continue','crate','else','enum','extern',
|
|
118
|
+
'false','fn','for','if','impl','in','let','loop','match',
|
|
119
|
+
'mod','move','mut','pub','ref','return','self','Self',
|
|
120
|
+
'static','struct','super','trait','true','type','unsafe',
|
|
121
|
+
'use','where','while','async','await','dyn',
|
|
122
|
+
'abstract','become','box','do','final','macro',
|
|
123
|
+
'override','priv','typeof','unsized','virtual','yield',
|
|
124
|
+
'try'
|
|
125
|
+
])
|
|
126
|
+
const C_KEYWORDS = new Set([
|
|
127
|
+
'auto','break','case','char','const','continue',
|
|
128
|
+
'default','do','double','else','enum','extern',
|
|
129
|
+
'float','for','goto','if','inline','int',
|
|
130
|
+
'long','register','restrict','return','short',
|
|
131
|
+
'signed','sizeof','static','struct','switch',
|
|
132
|
+
'typedef','union','unsigned','void','volatile',
|
|
133
|
+
'while',
|
|
134
|
+
'_Alignas','_Alignof','_Atomic','_Bool',
|
|
135
|
+
'_Complex','_Generic','_Imaginary',
|
|
136
|
+
'_Noreturn','_Static_assert','_Thread_local'
|
|
137
|
+
])
|
|
138
|
+
const CSHARP_KEYWORDS = new Set([
|
|
139
|
+
'abstract','as','base','bool','break','byte',
|
|
140
|
+
'case','catch','char','checked','class',
|
|
141
|
+
'const','continue','decimal','default',
|
|
142
|
+
'delegate','do','double','else','enum',
|
|
143
|
+
'event','explicit','extern','false','finally',
|
|
144
|
+
'fixed','float','for','foreach','goto',
|
|
145
|
+
'if','implicit','in','int','interface',
|
|
146
|
+
'internal','is','lock','long','namespace',
|
|
147
|
+
'new','null','object','operator','out',
|
|
148
|
+
'override','params','private','protected',
|
|
149
|
+
'public','readonly','ref','return','sbyte',
|
|
150
|
+
'sealed','short','sizeof','stackalloc',
|
|
151
|
+
'static','string','struct','switch',
|
|
152
|
+
'this','throw','true','try','typeof',
|
|
153
|
+
'uint','ulong','unchecked','unsafe',
|
|
154
|
+
'ushort','using','virtual','void',
|
|
155
|
+
'volatile','while',
|
|
156
|
+
'async','await','record','init',
|
|
157
|
+
'required','file','global','nameof',
|
|
158
|
+
'var','dynamic','partial','yield',
|
|
159
|
+
'from','where','select','group',
|
|
160
|
+
'orderby','join','let','into',
|
|
161
|
+
'equals','by','ascending','descending'
|
|
162
|
+
])
|
|
163
|
+
const BASH_KEYWORDS = new Set([
|
|
164
|
+
'if','then','else','elif','fi',
|
|
165
|
+
'case','esac','for','while',
|
|
166
|
+
'until','do','done','in',
|
|
167
|
+
'function','select','time',
|
|
168
|
+
'coproc',
|
|
169
|
+
'echo','printf','read','cd',
|
|
170
|
+
'pwd','exit','export','unset',
|
|
171
|
+
'alias','unalias','source',
|
|
172
|
+
'exec','eval','test','shift',
|
|
173
|
+
'trap','wait','jobs','kill',
|
|
174
|
+
'bg','fg','history','type',
|
|
175
|
+
'ulimit','umask','set',
|
|
176
|
+
'true','false'
|
|
177
|
+
])
|
|
178
|
+
const CMD_KEYWORDS = new Set([
|
|
179
|
+
'echo','set','if','else',
|
|
180
|
+
'for','in','do','goto',
|
|
181
|
+
'call','exit','shift',
|
|
182
|
+
'pause','start','title',
|
|
183
|
+
'cls','rem',
|
|
184
|
+
'dir','copy','move','del',
|
|
185
|
+
'mkdir','rmdir','type',
|
|
186
|
+
'ren','tasklist','taskkill',
|
|
187
|
+
'ping','ipconfig','netstat',
|
|
188
|
+
'shutdown'
|
|
189
|
+
])
|
|
190
|
+
const POWERSHELL_KEYWORDS = new Set([
|
|
191
|
+
'function','filter','param',
|
|
192
|
+
'begin','process','end',
|
|
193
|
+
'if','else','elseif',
|
|
194
|
+
'switch','foreach','for',
|
|
195
|
+
'while','do','until',
|
|
196
|
+
'break','continue','return',
|
|
197
|
+
'throw','trap','try',
|
|
198
|
+
'catch','finally',
|
|
199
|
+
'$true','$false','$null',
|
|
200
|
+
'Write-Host','Write-Output',
|
|
201
|
+
'Get-Item','Set-Item',
|
|
202
|
+
'Get-ChildItem','Remove-Item',
|
|
203
|
+
'Copy-Item','Move-Item',
|
|
204
|
+
'Test-Path','Invoke-Command'
|
|
205
|
+
])
|
|
206
|
+
const LANGUAGE_KEYWORDS = {
|
|
207
|
+
css: CSS_KEYWORDS,
|
|
208
|
+
html: HTML_KEYWORDS,
|
|
209
|
+
javascript: JS_KEYWORDS,
|
|
210
|
+
typescript: JS_KEYWORDS,
|
|
211
|
+
js: JS_KEYWORDS,
|
|
212
|
+
ts: JS_KEYWORDS,
|
|
213
|
+
python: PYTHON_KEYWORDS,
|
|
214
|
+
py: PYTHON_KEYWORDS,
|
|
215
|
+
go: GO_KEYWORDS,
|
|
216
|
+
golang: GO_KEYWORDS,
|
|
217
|
+
cpp: CPP_KEYWORDS,
|
|
218
|
+
'c++': CPP_KEYWORDS,
|
|
219
|
+
rust: RUST_KEYWORDS,
|
|
220
|
+
rs: RUST_KEYWORDS,
|
|
221
|
+
c: C_KEYWORDS,
|
|
222
|
+
h: C_KEYWORDS,
|
|
223
|
+
csharp: CSHARP_KEYWORDS,
|
|
224
|
+
cs: CSHARP_KEYWORDS,
|
|
225
|
+
bash: BASH_KEYWORDS,
|
|
226
|
+
sh: BASH_KEYWORDS,
|
|
227
|
+
zsh: BASH_KEYWORDS,
|
|
228
|
+
cmd: CMD_KEYWORDS,
|
|
229
|
+
bat: CMD_KEYWORDS,
|
|
230
|
+
powershell: POWERSHELL_KEYWORDS,
|
|
231
|
+
ps1: POWERSHELL_KEYWORDS
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const NOOP_KEYWORDS = new Set([])
|
|
235
|
+
|
|
236
|
+
export const tokenizeCode = (code, language = 'javascript') => {
|
|
237
|
+
const keywords = LANGUAGE_KEYWORDS[language] || NOOP_KEYWORDS
|
|
238
|
+
const blocks = []
|
|
239
|
+
LEXER_REGEX.lastIndex = 0
|
|
240
|
+
let match
|
|
241
|
+
while ((match = LEXER_REGEX.exec(code)) !== null) {
|
|
242
|
+
if (match[1]) blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: match[1] })
|
|
243
|
+
else if (match[2]) blocks.push({ highlightType: CodeHighlightType.STRING, codeContent: match[2] })
|
|
244
|
+
else if (match[3]) blocks.push({ highlightType: keywords.has(match[3]) ? CodeHighlightType.KEYWORD : CodeHighlightType.METHOD, codeContent: match[3] })
|
|
245
|
+
else if (match[4]) blocks.push({ highlightType: keywords.has(match[4]) ? CodeHighlightType.KEYWORD : CodeHighlightType.DEFAULT, codeContent: match[4] })
|
|
246
|
+
else if (match[5]) blocks.push({ highlightType: CodeHighlightType.NUMBER, codeContent: match[5] })
|
|
247
|
+
else blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: match[6] })
|
|
248
|
+
}
|
|
249
|
+
return blocks
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export const toUnified = (submessages, uuid) => ({
|
|
253
|
+
response_id: uuid || randomUUID(),
|
|
254
|
+
sections: submessages.map(submessage => {
|
|
255
|
+
switch (submessage.messageType) {
|
|
256
|
+
case RichSubMessageType.CODE: {
|
|
257
|
+
const codeMetadata = submessage.codeMetadata
|
|
258
|
+
return {
|
|
259
|
+
view_model: {
|
|
260
|
+
primitive: {
|
|
261
|
+
language: codeMetadata.codeLanguage,
|
|
262
|
+
code_blocks: codeMetadata.codeBlocks.map(block => ({ content: block.codeContent, type: CodeHighlightType[block.highlightType] })),
|
|
263
|
+
__typename: 'GenAICodeUXPrimitive'
|
|
264
|
+
},
|
|
265
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
case RichSubMessageType.CONTENT_ITEMS:
|
|
270
|
+
case RichSubMessageType.INLINE_IMAGE:
|
|
271
|
+
case RichSubMessageType.LATEX:
|
|
272
|
+
return {}
|
|
273
|
+
case RichSubMessageType.TABLE: {
|
|
274
|
+
const tableMetadata = submessage.tableMetadata
|
|
275
|
+
return {
|
|
276
|
+
view_model: {
|
|
277
|
+
primitive: {
|
|
278
|
+
title: tableMetadata.title,
|
|
279
|
+
rows: tableMetadata.rows.map(row => ({ is_header: row.isHeading, cells: row.items, markdown_cells: row.items.map(item => ({ text: item })) })),
|
|
280
|
+
__typename: 'GenATableUXPrimitive'
|
|
281
|
+
},
|
|
282
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
case RichSubMessageType.TEXT:
|
|
287
|
+
return {
|
|
288
|
+
view_model: {
|
|
289
|
+
primitive: { text: submessage.messageText, inline_entities: submessage.inlineEntities || [], __typename: 'GenAIMarkdownTextUXPrimitive' },
|
|
290
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
default:
|
|
294
|
+
return submessage
|
|
295
|
+
}
|
|
296
|
+
})
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
export const prepareRichResponseMessage = content => {
|
|
300
|
+
const {
|
|
301
|
+
alignment, code, contentText, disclaimerText, footerText, headerText, imageText, inlineImage, inlineVideo,
|
|
302
|
+
items, language, latex, links, noHeading, posts, products, suggested, richResponse, table, tapLinkUrl, title
|
|
303
|
+
} = content
|
|
304
|
+
let submessages = []
|
|
305
|
+
if (Array.isArray(richResponse)) {
|
|
306
|
+
submessages = richResponse.map(submessage => {
|
|
307
|
+
if (submessage.text) return { messageType: RichSubMessageType.TEXT, messageText: submessage.text, inlineEntities: submessage.inlineEntities }
|
|
308
|
+
if (submessage.code) return { messageType: RichSubMessageType.CODE, codeMetadata: { codeLanguage: submessage.language, codeBlocks: submessage.code } }
|
|
309
|
+
if (submessage.items) {
|
|
310
|
+
return {
|
|
311
|
+
messageType: RichSubMessageType.CONTENT_ITEMS,
|
|
312
|
+
contentItemsMetadata: { itemsMetadata: submessage.items, contentType: proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL }
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (submessage.inlineImage) {
|
|
316
|
+
return {
|
|
317
|
+
messageType: RichSubMessageType.INLINE_IMAGE,
|
|
318
|
+
imageMetadata: { imageUrl: submessage.inlineImage, imageText: submessage.imageText, alignment: submessage.alignment, tapLinkUrl: submessage.tapLinkUrl }
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (submessage.inlineVideo) return { messageType: RichSubMessageType.TEXT, messageText: 'INLINE_VIDEO' }
|
|
322
|
+
if (submessage.latex) return { messageType: RichSubMessageType.LATEX, latexMetadata: { text: submessage.text, expressions: submessage.latex } }
|
|
323
|
+
if (submessage.posts) return { messageType: RichSubMessageType.TEXT, messageText: 'POSTS' }
|
|
324
|
+
if (submessage.products) return { messageType: RichSubMessageType.TEXT, messageText: 'PRODUCTS' }
|
|
325
|
+
if (submessage.suggested) return { messageType: RichSubMessageType.TEXT, messageText: 'SUGGESTED_PROMPT' }
|
|
326
|
+
if (submessage.table) return { messageType: RichSubMessageType.TABLE, tableMetadata: { title: submessage.title, rows: submessage.table } }
|
|
327
|
+
return submessage
|
|
328
|
+
})
|
|
329
|
+
} else {
|
|
330
|
+
if (headerText) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: headerText })
|
|
331
|
+
if (contentText) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: contentText })
|
|
332
|
+
if (code) {
|
|
333
|
+
const lang = language || 'javascript'
|
|
334
|
+
submessages.push({ messageType: RichSubMessageType.CODE, codeMetadata: { codeLanguage: lang, codeBlocks: tokenizeCode(code, lang) } })
|
|
335
|
+
}
|
|
336
|
+
if (items) {
|
|
337
|
+
submessages.push({
|
|
338
|
+
messageType: RichSubMessageType.CONTENT_ITEMS,
|
|
339
|
+
contentItemsMetadata: { itemsMetadata: items, contentType: proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL }
|
|
340
|
+
})
|
|
341
|
+
}
|
|
342
|
+
if (inlineImage) submessages.push({ messageType: RichSubMessageType.INLINE_IMAGE, imageMetadata: { imageUrl: inlineImage, imageText, alignment, tapLinkUrl } })
|
|
343
|
+
if (inlineVideo) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: 'INLINE_VIDEO' })
|
|
344
|
+
if (latex) submessages.push({ messageType: RichSubMessageType.LATEX, latexMetadata: { text: content.text, expressions: latex } })
|
|
345
|
+
if (links) {
|
|
346
|
+
links.forEach((linkField, index) => {
|
|
347
|
+
const prefix = 'SS_' + index
|
|
348
|
+
const url = linkField.url
|
|
349
|
+
const sources = linkField.sources?.map(sourceField => ({
|
|
350
|
+
source_type: 'THIRD_PARTY',
|
|
351
|
+
source_display_name: sourceField.displayName,
|
|
352
|
+
source_subtitle: sourceField.subtitle,
|
|
353
|
+
source_url: sourceField.url || url
|
|
354
|
+
}))
|
|
355
|
+
submessages.push({
|
|
356
|
+
messageType: RichSubMessageType.TEXT,
|
|
357
|
+
messageText: linkField.text + ` {{${prefix}}}¹{{/${prefix}}} `,
|
|
358
|
+
inlineEntities: [
|
|
359
|
+
{
|
|
360
|
+
key: prefix,
|
|
361
|
+
metadata: {
|
|
362
|
+
reference_id: index + 1,
|
|
363
|
+
reference_url: url,
|
|
364
|
+
reference_title: linkField.title,
|
|
365
|
+
reference_display_name: linkField.displayName,
|
|
366
|
+
sources: sources || [],
|
|
367
|
+
__typename: 'GenAISearchCitationItem'
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
]
|
|
371
|
+
})
|
|
372
|
+
})
|
|
373
|
+
}
|
|
374
|
+
if (posts) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: 'POSTS' })
|
|
375
|
+
if (products) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: 'PRODUCTS' })
|
|
376
|
+
if (suggested) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: 'SUGGESTED_PROMPT' })
|
|
377
|
+
if (table) {
|
|
378
|
+
submessages.push({
|
|
379
|
+
messageType: RichSubMessageType.TABLE,
|
|
380
|
+
tableMetadata: { title, rows: table.map((items_, index) => ({ isHeading: !noHeading && index === 0, items: items_ })) }
|
|
381
|
+
})
|
|
382
|
+
}
|
|
383
|
+
if (footerText) submessages.push({ messageType: RichSubMessageType.TEXT, messageText: footerText })
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const uuid = randomUUID()
|
|
387
|
+
const unified = toUnified(submessages, uuid)
|
|
388
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
389
|
+
submessages,
|
|
390
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
391
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
392
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 }
|
|
393
|
+
})
|
|
394
|
+
const message = wrapToBotForwardedMessage(richResponseMessage)
|
|
395
|
+
const botMetadata = message.messageContextInfo.botMetadata
|
|
396
|
+
if (disclaimerText) botMetadata.messageDisclaimerText = disclaimerText
|
|
397
|
+
botMetadata.botResponseId = uuid
|
|
398
|
+
return message
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export const botMetadataSignature = () => {
|
|
402
|
+
const signature = new Uint8Array(64)
|
|
403
|
+
getRandomValues(signature)
|
|
404
|
+
return signature
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export const botMetadataCertificate = (length = 685) => {
|
|
408
|
+
const certificate = new Uint8Array(length)
|
|
409
|
+
certificate[0] = 48
|
|
410
|
+
certificate[1] = 130
|
|
411
|
+
getRandomValues(certificate.subarray(2))
|
|
412
|
+
return certificate
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export const wrapToBotForwardedMessage = richResponseMessage => ({
|
|
416
|
+
messageContextInfo: {
|
|
417
|
+
botMetadata: {
|
|
418
|
+
verificationMetadata: {
|
|
419
|
+
proofs: [{ certificateChain: [botMetadataCertificate(), botMetadataCertificate(892)], version: 1, useCase: 1, signature: botMetadataSignature() }]
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
},
|
|
423
|
+
botForwardedMessage: { message: { richResponseMessage } }
|
|
424
|
+
})
|
|
425
|
+
|
|
426
|
+
/* ------------------------------------------------------------------ */
|
|
427
|
+
/* Message content composition */
|
|
428
|
+
/* ------------------------------------------------------------------ */
|
|
429
|
+
|
|
430
|
+
/** Uses a regex to test whether the string contains a URL, and returns the URL if it does. */
|
|
431
|
+
export const extractUrlFromText = text => text.match(URL_REGEX)?.[0]
|
|
432
|
+
|
|
433
|
+
export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
|
|
434
|
+
const url = extractUrlFromText(text)
|
|
435
|
+
if (!!getUrlInfo && url) {
|
|
436
|
+
try {
|
|
437
|
+
return await getUrlInfo(url)
|
|
438
|
+
} catch (error) {
|
|
439
|
+
logger?.warn({ trace: error.stack }, 'url generation failed')
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const assertColor = async color => {
|
|
445
|
+
if (typeof color === 'number') return color > 0 ? color : 0xffffffff + Number(color) + 1
|
|
446
|
+
let hex = color.trim().replace('#', '')
|
|
447
|
+
if (hex.length <= 6) hex = 'FF' + hex.padStart(6, '0')
|
|
448
|
+
return parseInt(hex, 16)
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export const prepareWAMessageMedia = async (message, options) => {
|
|
452
|
+
const logger = options.logger
|
|
453
|
+
let mediaType
|
|
454
|
+
for (const key of MEDIA_KEYS) if (key in message) mediaType = key
|
|
455
|
+
if (!mediaType) throw new Boom('Invalid media type', { statusCode: 400 })
|
|
456
|
+
|
|
457
|
+
const uploadData = { ...message, media: message[mediaType] }
|
|
458
|
+
delete uploadData[mediaType]
|
|
459
|
+
|
|
460
|
+
const cacheableKey =
|
|
461
|
+
typeof uploadData.media === 'object' &&
|
|
462
|
+
'url' in uploadData.media &&
|
|
463
|
+
!!uploadData.media.url &&
|
|
464
|
+
!!options.mediaCache &&
|
|
465
|
+
mediaType + ':' + uploadData.media.url.toString()
|
|
466
|
+
|
|
467
|
+
if (mediaType === 'document' && !uploadData.fileName) uploadData.fileName = 'file'
|
|
468
|
+
if (!uploadData.mimetype) uploadData.mimetype = MIMETYPE_MAP[mediaType]
|
|
469
|
+
|
|
470
|
+
if (cacheableKey) {
|
|
471
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey)
|
|
472
|
+
if (mediaBuff) {
|
|
473
|
+
logger?.debug({ cacheableKey }, 'got media cache hit')
|
|
474
|
+
const obj = proto.Message.decode(mediaBuff)
|
|
475
|
+
const key = `${mediaType}Message`
|
|
476
|
+
Object.assign(obj[key], { ...uploadData, media: undefined })
|
|
477
|
+
return obj
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const isNewsletter = !!options.jid && isJidNewsletter(options.jid)
|
|
482
|
+
if (isNewsletter) {
|
|
483
|
+
logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter')
|
|
484
|
+
const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger)
|
|
485
|
+
const fileSha256B64 = fileSha256.toString('base64')
|
|
486
|
+
const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
|
|
487
|
+
fileEncSha256B64: fileSha256B64,
|
|
488
|
+
mediaType,
|
|
489
|
+
timeoutMs: options.mediaUploadTimeoutMs,
|
|
490
|
+
newsletter: isNewsletter
|
|
491
|
+
})
|
|
492
|
+
await fs.unlink(filePath)
|
|
493
|
+
const obj = WAProto.Message.fromObject({
|
|
494
|
+
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
495
|
+
url: mediaUrl,
|
|
496
|
+
directPath,
|
|
497
|
+
fileSha256,
|
|
498
|
+
fileLength,
|
|
499
|
+
thumbnailDirectPath,
|
|
500
|
+
thumbnailSha256,
|
|
501
|
+
...uploadData,
|
|
502
|
+
media: undefined
|
|
503
|
+
})
|
|
504
|
+
})
|
|
505
|
+
if (uploadData.ptv) {
|
|
506
|
+
obj.ptvMessage = obj.videoMessage
|
|
507
|
+
delete obj.videoMessage
|
|
508
|
+
}
|
|
509
|
+
if (obj.stickerMessage) obj.stickerMessage.stickerSentTs = Date.now()
|
|
510
|
+
if (cacheableKey) {
|
|
511
|
+
logger?.debug({ cacheableKey }, 'set cache')
|
|
512
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish())
|
|
513
|
+
}
|
|
514
|
+
return obj
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
|
518
|
+
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined'
|
|
519
|
+
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined'
|
|
520
|
+
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
|
521
|
+
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
|
522
|
+
|
|
523
|
+
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(
|
|
524
|
+
uploadData.media,
|
|
525
|
+
options.mediaTypeOverride || mediaType,
|
|
526
|
+
{ logger, saveOriginalFileIfRequired: requiresOriginalForSomeProcessing, opts: options.options }
|
|
527
|
+
)
|
|
528
|
+
const fileEncSha256B64 = fileEncSha256.toString('base64')
|
|
529
|
+
const [{ mediaUrl, directPath }] = await Promise.all([
|
|
530
|
+
(async () => {
|
|
531
|
+
const result = await options.upload(encFilePath, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs })
|
|
532
|
+
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
|
533
|
+
return result
|
|
534
|
+
})(),
|
|
535
|
+
(async () => {
|
|
536
|
+
try {
|
|
537
|
+
if (requiresThumbnailComputation) {
|
|
538
|
+
const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options)
|
|
539
|
+
uploadData.jpegThumbnail = thumbnail
|
|
540
|
+
if (!uploadData.width && originalImageDimensions) {
|
|
541
|
+
uploadData.width = originalImageDimensions.width
|
|
542
|
+
uploadData.height = originalImageDimensions.height
|
|
543
|
+
logger?.debug('set dimensions')
|
|
544
|
+
}
|
|
545
|
+
logger?.debug('generated thumbnail')
|
|
546
|
+
}
|
|
547
|
+
if (requiresDurationComputation) {
|
|
548
|
+
uploadData.seconds = await getAudioDuration(originalFilePath)
|
|
549
|
+
logger?.debug('computed audio duration')
|
|
550
|
+
}
|
|
551
|
+
if (requiresWaveformProcessing) {
|
|
552
|
+
uploadData.waveform = await getAudioWaveform(originalFilePath, logger)
|
|
553
|
+
logger?.debug('processed waveform')
|
|
554
|
+
}
|
|
555
|
+
if (requiresAudioBackground) {
|
|
556
|
+
uploadData.backgroundArgb = await assertColor(options.backgroundColor)
|
|
557
|
+
logger?.debug('computed backgroundColor audio status')
|
|
558
|
+
}
|
|
559
|
+
} catch (error) {
|
|
560
|
+
logger?.warn({ trace: error.stack }, 'failed to obtain extra info')
|
|
561
|
+
}
|
|
562
|
+
})()
|
|
563
|
+
]).finally(async () => {
|
|
564
|
+
try {
|
|
565
|
+
await fs.unlink(encFilePath)
|
|
566
|
+
if (originalFilePath) await fs.unlink(originalFilePath)
|
|
567
|
+
logger?.debug('removed tmp files')
|
|
568
|
+
} catch {
|
|
569
|
+
logger?.warn('failed to remove tmp file')
|
|
570
|
+
}
|
|
571
|
+
})
|
|
572
|
+
|
|
573
|
+
const obj = WAProto.Message.fromObject({
|
|
574
|
+
[`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
|
|
575
|
+
url: mediaUrl,
|
|
576
|
+
directPath,
|
|
577
|
+
mediaKey,
|
|
578
|
+
fileEncSha256,
|
|
579
|
+
fileSha256,
|
|
580
|
+
fileLength,
|
|
581
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
582
|
+
...uploadData,
|
|
583
|
+
media: undefined
|
|
584
|
+
})
|
|
585
|
+
})
|
|
586
|
+
if (uploadData.ptv) {
|
|
587
|
+
obj.ptvMessage = obj.videoMessage
|
|
588
|
+
delete obj.videoMessage
|
|
589
|
+
}
|
|
590
|
+
if (cacheableKey) {
|
|
591
|
+
logger?.debug({ cacheableKey }, 'set cache')
|
|
592
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish())
|
|
593
|
+
}
|
|
594
|
+
return obj
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const prepareProductMessage = async (message, options) => {
|
|
598
|
+
if (!message.businessOwnerJid) throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 })
|
|
599
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options)
|
|
600
|
+
const { image, ...content } = message
|
|
601
|
+
content.product = { currencyCode: 'IDR', priceAmount1000: 1000, title: LIBRARY_NAME, ...message.product, productImage: imageMessage }
|
|
602
|
+
return content
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1
|
|
607
|
+
* (https://github.com/jlucaso1), based on https://github.com/WhiskeySockets/Baileys/pull/1561
|
|
608
|
+
*/
|
|
609
|
+
const prepareStickerPackMessage = async (message, options) => {
|
|
610
|
+
const { cover, stickers = [], name = '📦 Sticker Pack', publisher = '', description = '' } = message
|
|
611
|
+
if (stickers.length > 60) throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 })
|
|
612
|
+
if (stickers.length === 0) throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 })
|
|
613
|
+
if (!cover) throw new Boom('Sticker pack must contain a cover', { statusCode: 400 })
|
|
614
|
+
|
|
615
|
+
const logger = options.logger
|
|
616
|
+
let cacheableKey = false
|
|
617
|
+
if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
|
|
618
|
+
const urls = []
|
|
619
|
+
for (const s of stickers) {
|
|
620
|
+
if (typeof s.data === 'object' && s.data?.url) urls.push(s.data.url)
|
|
621
|
+
}
|
|
622
|
+
if (urls.length > 0) cacheableKey = 'sticker:' + urls.join('@')
|
|
623
|
+
}
|
|
624
|
+
if (cacheableKey) {
|
|
625
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey)
|
|
626
|
+
if (mediaBuff) {
|
|
627
|
+
logger?.debug({ cacheableKey }, 'got media cache hit')
|
|
628
|
+
return proto.Message.StickerPackMessage.decode(mediaBuff)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const lib = await getImageProcessingLibrary()
|
|
633
|
+
const hasSharp = 'sharp' in lib && !!lib.sharp?.default
|
|
634
|
+
const hasImage = 'image' in lib && !!lib.image?.Transformer
|
|
635
|
+
const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp
|
|
636
|
+
if (!hasSharp && !hasImage) throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.')
|
|
637
|
+
|
|
638
|
+
const stickerPackIdValue = generateMessageIDV2()
|
|
639
|
+
const stickerData = {}
|
|
640
|
+
const stickerMetadata = new Array(stickers.length)
|
|
641
|
+
for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
|
|
642
|
+
const promises = []
|
|
643
|
+
const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length)
|
|
644
|
+
for (let j = i; j < chunkEnd; j++) {
|
|
645
|
+
promises.push(
|
|
646
|
+
(async index => {
|
|
647
|
+
const sticker = stickers[index]
|
|
648
|
+
const { stream } = await getStream(sticker.data)
|
|
649
|
+
const buffer = await toBuffer(stream)
|
|
650
|
+
let webpBuffer
|
|
651
|
+
let isAnimated = false
|
|
652
|
+
if (isWebPBuffer(buffer)) {
|
|
653
|
+
webpBuffer = buffer
|
|
654
|
+
isAnimated = isAnimatedWebP(buffer)
|
|
655
|
+
} else if (hasSharp) {
|
|
656
|
+
webpBuffer = await lib.sharp.default(buffer).resize(512, 512, { fit: 'inside' }).webp({ quality: 80 }).toBuffer()
|
|
657
|
+
} else {
|
|
658
|
+
webpBuffer = await new lib.image.Transformer(buffer).resize(512, 512).webp(80)
|
|
659
|
+
}
|
|
660
|
+
if (webpBuffer.length > 1024 * 1024) throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 })
|
|
661
|
+
const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-')
|
|
662
|
+
const fileName = `${hash}.webp`
|
|
663
|
+
stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }]
|
|
664
|
+
stickerMetadata[index] = {
|
|
665
|
+
fileName,
|
|
666
|
+
mimetype: 'image/webp',
|
|
667
|
+
isAnimated,
|
|
668
|
+
emojis: sticker.emojis || ['✨'],
|
|
669
|
+
accessibilityLabel: sticker.accessibilityLabel || ''
|
|
670
|
+
}
|
|
671
|
+
})(j)
|
|
672
|
+
)
|
|
673
|
+
}
|
|
674
|
+
await Promise.all(promises)
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const trayIconFileName = `${stickerPackIdValue}.webp`
|
|
678
|
+
const { stream: coverStream } = await getStream(cover)
|
|
679
|
+
const coverBuffer = await toBuffer(coverStream)
|
|
680
|
+
let coverWebpBuffer
|
|
681
|
+
if (isWebPBuffer(coverBuffer)) coverWebpBuffer = coverBuffer
|
|
682
|
+
else if (hasSharp) coverWebpBuffer = await lib.sharp.default(coverBuffer).resize(512, 512, { fit: 'inside' }).webp({ quality: 80 }).toBuffer()
|
|
683
|
+
else coverWebpBuffer = await new lib.image.Transformer(coverBuffer).resize(512, 512).webp(80)
|
|
684
|
+
stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }]
|
|
685
|
+
|
|
686
|
+
const zipBuffer = await new Promise((resolve, reject) => {
|
|
687
|
+
zip(stickerData, (error, data) => (error ? reject(error) : resolve(Buffer.from(data))))
|
|
688
|
+
})
|
|
689
|
+
const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', { logger, opts: options.options })
|
|
690
|
+
let stickerPackUploadResult
|
|
691
|
+
try {
|
|
692
|
+
stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
|
|
693
|
+
fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
|
|
694
|
+
mediaType: 'sticker-pack',
|
|
695
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
696
|
+
})
|
|
697
|
+
} finally {
|
|
698
|
+
fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'))
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const obj = {
|
|
702
|
+
name,
|
|
703
|
+
publisher,
|
|
704
|
+
stickerPackId: stickerPackIdValue,
|
|
705
|
+
packDescription: description,
|
|
706
|
+
stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
|
|
707
|
+
stickerPackSize: zipBuffer.length,
|
|
708
|
+
stickers: stickerMetadata,
|
|
709
|
+
fileSha256: stickerPackUpload.fileSha256,
|
|
710
|
+
fileEncSha256: stickerPackUpload.fileEncSha256,
|
|
711
|
+
mediaKey: stickerPackUpload.mediaKey,
|
|
712
|
+
directPath: stickerPackUploadResult.directPath,
|
|
713
|
+
fileLength: stickerPackUpload.fileLength,
|
|
714
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
715
|
+
trayIconFileName
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
try {
|
|
719
|
+
let thumbnailBuffer
|
|
720
|
+
if (hasSharp) thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer()
|
|
721
|
+
else if (hasImage) thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg()
|
|
722
|
+
else if (hasJimp) {
|
|
723
|
+
const jimpImage = await lib.jimp.Jimp.read(coverBuffer)
|
|
724
|
+
thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg')
|
|
725
|
+
} else {
|
|
726
|
+
throw new Error('No image processing library available for thumbnail generation')
|
|
727
|
+
}
|
|
728
|
+
if (!thumbnailBuffer || thumbnailBuffer.length === 0) throw new Error('Failed to generate thumbnail buffer')
|
|
729
|
+
|
|
730
|
+
const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', { logger, opts: options.options, mediaKey: stickerPackUpload.mediaKey })
|
|
731
|
+
let thumbUploadResult
|
|
732
|
+
try {
|
|
733
|
+
thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
|
|
734
|
+
fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
|
|
735
|
+
mediaType: 'thumbnail-sticker-pack',
|
|
736
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
737
|
+
})
|
|
738
|
+
} finally {
|
|
739
|
+
fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'))
|
|
740
|
+
}
|
|
741
|
+
Object.assign(obj, {
|
|
742
|
+
thumbnailDirectPath: thumbUploadResult.directPath,
|
|
743
|
+
thumbnailSha256: thumbUpload.fileSha256,
|
|
744
|
+
thumbnailEncSha256: thumbUpload.fileEncSha256,
|
|
745
|
+
thumbnailHeight: 252,
|
|
746
|
+
thumbnailWidth: 252,
|
|
747
|
+
imageDataHash: sha256(thumbnailBuffer).toString('base64')
|
|
748
|
+
})
|
|
749
|
+
} catch (error) {
|
|
750
|
+
logger?.warn(`Thumbnail generation failed: ${error}`)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (cacheableKey) {
|
|
754
|
+
logger?.debug({ cacheableKey }, 'set cache (background)')
|
|
755
|
+
options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish())
|
|
756
|
+
}
|
|
757
|
+
return WAProto.Message.StickerPackMessage.fromObject(obj)
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const prepareNativeFlowButtons = message => {
|
|
761
|
+
const buttons = message.nativeFlow
|
|
762
|
+
const isButtonsFieldArray = Array.isArray(buttons)
|
|
763
|
+
const correctedField = isButtonsFieldArray ? buttons : buttons.buttons
|
|
764
|
+
const messageParamsJson = {}
|
|
765
|
+
if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
|
|
766
|
+
Object.assign(messageParamsJson, {
|
|
767
|
+
limited_time_offer: { text: message.offerText || LIBRARY_NAME, ...(message.offerUrl ? { url: message.offerUrl } : {}), copy_code: message.offerCode, expiration_time: message.offerExpiration }
|
|
768
|
+
})
|
|
769
|
+
}
|
|
770
|
+
if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
|
|
771
|
+
Object.assign(messageParamsJson, {
|
|
772
|
+
bottom_sheet: {
|
|
773
|
+
in_thread_buttons_limit: 1,
|
|
774
|
+
divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
|
|
775
|
+
list_title: message.optionTitle || '📄 Select Options',
|
|
776
|
+
button_title: message.optionText
|
|
777
|
+
}
|
|
778
|
+
})
|
|
779
|
+
}
|
|
780
|
+
return {
|
|
781
|
+
buttons: correctedField.map(button => {
|
|
782
|
+
const buttonText = button.text || button.buttonText
|
|
783
|
+
const buttonIcon = button.icon?.toUpperCase()
|
|
784
|
+
if (hasOptionalProperty(button, 'id') && !!button.id) {
|
|
785
|
+
return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: buttonText || '👉🏻 Click', id: button.id, icon: buttonIcon }) }
|
|
786
|
+
}
|
|
787
|
+
if (hasOptionalProperty(button, 'copy') && !!button.copy) {
|
|
788
|
+
return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: buttonText || '📋 Copy', copy_code: button.copy, icon: buttonIcon }) }
|
|
789
|
+
}
|
|
790
|
+
if (hasOptionalProperty(button, 'url') && !!button.url) {
|
|
791
|
+
return {
|
|
792
|
+
name: 'cta_url',
|
|
793
|
+
buttonParamsJson: JSON.stringify({ display_text: buttonText || '🌐 Visit', url: button.url, merchant_url: button.url, webview_interaction: button.useWebview, icon: buttonIcon })
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
if (hasOptionalProperty(button, 'call') && !!button.call) {
|
|
797
|
+
return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: buttonText || '📞 Call', phone_number: button.call, icon: buttonIcon }) }
|
|
798
|
+
}
|
|
799
|
+
if (hasOptionalProperty(button, 'sections') && !!button.sections) {
|
|
800
|
+
return { name: 'single_select', buttonParamsJson: JSON.stringify({ title: buttonText || '📋 Select', sections: button.sections, icon: buttonIcon }) }
|
|
801
|
+
}
|
|
802
|
+
return button
|
|
803
|
+
}),
|
|
804
|
+
messageParamsJson: JSON.stringify(messageParamsJson)
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
export const prepareDisappearingMessageSettingContent = ephemeralExpiration => {
|
|
809
|
+
ephemeralExpiration = ephemeralExpiration || 0
|
|
810
|
+
return WAProto.Message.fromObject({
|
|
811
|
+
ephemeralMessage: { message: { protocolMessage: { type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING, ephemeralExpiration } } }
|
|
812
|
+
})
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Generate forwarded message content like WA does.
|
|
817
|
+
* @param message the message to forward
|
|
818
|
+
* @param forceForward will show the message as forwarded even if it is from you
|
|
819
|
+
*/
|
|
820
|
+
export const generateForwardMessageContent = (message, forceForward) => {
|
|
821
|
+
let content = message.message
|
|
822
|
+
if (!content) throw new Boom('no content in message', { statusCode: 400 })
|
|
823
|
+
content = normalizeMessageContent(content)
|
|
824
|
+
content = proto.Message.decode(proto.Message.encode(content).finish())
|
|
825
|
+
let key = Object.keys(content)[0]
|
|
826
|
+
let score = content?.[key]?.contextInfo?.forwardingScore || 0
|
|
827
|
+
score += message.key.fromMe && !forceForward ? 0 : 1
|
|
828
|
+
if (key === 'conversation') {
|
|
829
|
+
content.extendedTextMessage = { text: content[key] }
|
|
830
|
+
delete content.conversation
|
|
831
|
+
key = 'extendedTextMessage'
|
|
832
|
+
}
|
|
833
|
+
const key_ = content?.[key]
|
|
834
|
+
key_.contextInfo = score > 0 ? { forwardingScore: score, isForwarded: true } : {}
|
|
835
|
+
return content
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
export const hasNonNullishProperty = (message, key) => message != null && typeof message === 'object' && key in message && message[key] != null
|
|
839
|
+
export const hasOptionalProperty = (obj, key) => obj != null && typeof obj === 'object' && key in obj && obj[key] != null
|
|
840
|
+
export const hasValidAlbumMedia = message => !!(message.imageMessage || message.videoMessage)
|
|
841
|
+
export const hasValidInteractiveHeader = message =>
|
|
842
|
+
!!(message.imageMessage || message.videoMessage || message.documentMessage || message.productMessage || message.locationMessage)
|
|
843
|
+
export const hasValidCarouselHeader = message => !!(message.imageMessage || message.videoMessage || message.productMessage)
|
|
844
|
+
|
|
845
|
+
export const generateWAMessageContent = async (message, options) => {
|
|
846
|
+
let m = {}
|
|
847
|
+
if (hasNonNullishProperty(message, 'raw')) {
|
|
848
|
+
delete message.raw
|
|
849
|
+
return message
|
|
850
|
+
} else if (
|
|
851
|
+
hasNonNullishProperty(message, 'code') ||
|
|
852
|
+
hasNonNullishProperty(message, 'links') ||
|
|
853
|
+
hasNonNullishProperty(message, 'table') ||
|
|
854
|
+
hasNonNullishProperty(message, 'richResponse')
|
|
855
|
+
) {
|
|
856
|
+
m = prepareRichResponseMessage(message)
|
|
857
|
+
} else if (hasNonNullishProperty(message, 'text')) {
|
|
858
|
+
const extContent = { text: message.text }
|
|
859
|
+
let urlInfo = message.linkPreview
|
|
860
|
+
if (typeof urlInfo === 'undefined') urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger)
|
|
861
|
+
if (urlInfo) {
|
|
862
|
+
extContent.matchedText = urlInfo['matched-text']
|
|
863
|
+
extContent.jpegThumbnail = urlInfo.jpegThumbnail
|
|
864
|
+
extContent.description = urlInfo.description
|
|
865
|
+
extContent.title = urlInfo.title
|
|
866
|
+
extContent.previewType = urlInfo.previewType ?? 0
|
|
867
|
+
extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata
|
|
868
|
+
const img = urlInfo.highQualityThumbnail
|
|
869
|
+
if (img) {
|
|
870
|
+
extContent.thumbnailDirectPath = img.directPath
|
|
871
|
+
extContent.mediaKey = img.mediaKey
|
|
872
|
+
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp
|
|
873
|
+
extContent.thumbnailWidth = img.width
|
|
874
|
+
extContent.thumbnailHeight = img.height
|
|
875
|
+
extContent.thumbnailSha256 = img.fileSha256
|
|
876
|
+
extContent.thumbnailEncSha256 = img.fileEncSha256
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
const faviconData = message.favicon
|
|
880
|
+
if (faviconData && typeof options.upload === 'function') {
|
|
881
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: faviconData }, options)
|
|
882
|
+
extContent.faviconMMSMetadata = {
|
|
883
|
+
thumbnailDirectPath: imageMessage.directPath,
|
|
884
|
+
mediaKey: imageMessage.mediaKey,
|
|
885
|
+
mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
|
|
886
|
+
thumbnailWidth: 32,
|
|
887
|
+
thumbnailHeight: 32,
|
|
888
|
+
thumbnailSha256: imageMessage.fileSha256,
|
|
889
|
+
thumbnailEncSha256: imageMessage.fileEncSha256
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
if (options.backgroundColor) extContent.backgroundArgb = await assertColor(options.backgroundColor)
|
|
893
|
+
if (options.font) extContent.font = options.font
|
|
894
|
+
m.extendedTextMessage = extContent
|
|
895
|
+
} else if (hasNonNullishProperty(message, 'contacts')) {
|
|
896
|
+
const contactLen = message.contacts.contacts.length
|
|
897
|
+
if (!contactLen) throw new Boom('require atleast 1 contact', { statusCode: 400 })
|
|
898
|
+
if (contactLen === 1) m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0])
|
|
899
|
+
else m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts)
|
|
900
|
+
} else if (hasNonNullishProperty(message, 'location')) {
|
|
901
|
+
m.locationMessage = WAProto.Message.LocationMessage.create(message.location)
|
|
902
|
+
} else if (hasNonNullishProperty(message, 'react')) {
|
|
903
|
+
if (!message.react.senderTimestampMs) message.react.senderTimestampMs = Date.now()
|
|
904
|
+
m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react)
|
|
905
|
+
} else if (hasNonNullishProperty(message, 'delete')) {
|
|
906
|
+
m.protocolMessage = { key: message.delete, type: WAProto.Message.ProtocolMessage.Type.REVOKE }
|
|
907
|
+
} else if (hasNonNullishProperty(message, 'forward')) {
|
|
908
|
+
m = generateForwardMessageContent(message.forward, message.force)
|
|
909
|
+
} else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
|
|
910
|
+
const exp =
|
|
911
|
+
typeof message.disappearingMessagesInChat === 'boolean'
|
|
912
|
+
? message.disappearingMessagesInChat
|
|
913
|
+
? WA_DEFAULT_EPHEMERAL
|
|
914
|
+
: 0
|
|
915
|
+
: message.disappearingMessagesInChat
|
|
916
|
+
m = prepareDisappearingMessageSettingContent(exp)
|
|
917
|
+
} else if (hasNonNullishProperty(message, 'groupInvite')) {
|
|
918
|
+
m.groupInviteMessage = {}
|
|
919
|
+
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode
|
|
920
|
+
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration
|
|
921
|
+
m.groupInviteMessage.caption = message.groupInvite.text
|
|
922
|
+
m.groupInviteMessage.groupJid = message.groupInvite.jid
|
|
923
|
+
m.groupInviteMessage.groupName = message.groupInvite.subject
|
|
924
|
+
if (options.getProfilePicUrl) {
|
|
925
|
+
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview')
|
|
926
|
+
if (pfpUrl) {
|
|
927
|
+
const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher })
|
|
928
|
+
if (resp.ok) m.groupInviteMessage.jpegThumbnail = Buffer.from(await resp.arrayBuffer())
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
} else if (hasNonNullishProperty(message, 'stickers')) {
|
|
932
|
+
m.stickerPackMessage = await prepareStickerPackMessage(message, options)
|
|
933
|
+
} else if (hasNonNullishProperty(message, 'pin')) {
|
|
934
|
+
m.pinInChatMessage = {}
|
|
935
|
+
m.messageContextInfo = {}
|
|
936
|
+
m.pinInChatMessage.key = message.pin
|
|
937
|
+
m.pinInChatMessage.type = message.type
|
|
938
|
+
m.pinInChatMessage.senderTimestampMs = Date.now()
|
|
939
|
+
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0
|
|
940
|
+
} else if (hasNonNullishProperty(message, 'keep')) {
|
|
941
|
+
m.keepInChatMessage = {}
|
|
942
|
+
m.keepInChatMessage.key = message.keep
|
|
943
|
+
m.keepInChatMessage.keepType = message.type
|
|
944
|
+
m.keepInChatMessage.timestampMs = Date.now()
|
|
945
|
+
} else if (hasNonNullishProperty(message, 'flowReply')) {
|
|
946
|
+
m.interactiveResponseMessage = {
|
|
947
|
+
body: { format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT, text: message.flowReply.text },
|
|
948
|
+
nativeFlowResponseMessage: { name: message.flowReply.name, paramsJson: message.flowReply.paramsJson || '{}', version: message.flowReply.version || 1 }
|
|
949
|
+
}
|
|
950
|
+
} else if (hasNonNullishProperty(message, 'buttonReply')) {
|
|
951
|
+
if (message.type === 'template') {
|
|
952
|
+
m.templateButtonReplyMessage = {
|
|
953
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
954
|
+
selectedId: message.buttonReply.id,
|
|
955
|
+
selectedIndex: message.buttonReply.index
|
|
956
|
+
}
|
|
957
|
+
} else if (message.type === 'plain') {
|
|
958
|
+
m.buttonsResponseMessage = {
|
|
959
|
+
selectedButtonId: message.buttonReply.id,
|
|
960
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
961
|
+
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
} else if (hasNonNullishProperty(message, 'listReply')) {
|
|
965
|
+
m.listResponseMessage = {
|
|
966
|
+
description: message.listReply.description,
|
|
967
|
+
listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
|
|
968
|
+
singleSelectReply: { selectedRowId: message.listReply.id },
|
|
969
|
+
title: message.listReply.title
|
|
970
|
+
}
|
|
971
|
+
} else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
|
|
972
|
+
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options)
|
|
973
|
+
m.ptvMessage = videoMessage
|
|
974
|
+
} else if (hasNonNullishProperty(message, 'product')) {
|
|
975
|
+
m.productMessage = await prepareProductMessage(message, options)
|
|
976
|
+
} else if (hasNonNullishProperty(message, 'event')) {
|
|
977
|
+
m.eventMessage = {}
|
|
978
|
+
const startTime = Math.floor(message.event.startDate.getTime() / 1000)
|
|
979
|
+
if (message.event.call && options.getCallLink) {
|
|
980
|
+
const token = await options.getCallLink(message.event.call, { startTime })
|
|
981
|
+
m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token
|
|
982
|
+
}
|
|
983
|
+
m.messageContextInfo = { messageSecret: message.event.messageSecret || randomBytes(32) }
|
|
984
|
+
m.eventMessage.name = message.event.name
|
|
985
|
+
m.eventMessage.description = message.event.description
|
|
986
|
+
m.eventMessage.startTime = startTime
|
|
987
|
+
m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined
|
|
988
|
+
m.eventMessage.isCanceled = message.event.isCancelled ?? false
|
|
989
|
+
m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed
|
|
990
|
+
m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false
|
|
991
|
+
m.eventMessage.location = message.event.location
|
|
992
|
+
} else if (hasNonNullishProperty(message, 'poll')) {
|
|
993
|
+
message.poll.selectableCount ||= 0
|
|
994
|
+
message.poll.toAnnouncementGroup ||= false
|
|
995
|
+
if (!Array.isArray(message.poll.values)) throw new Boom('Invalid poll values', { statusCode: 400 })
|
|
996
|
+
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
|
997
|
+
throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, { statusCode: 400 })
|
|
998
|
+
}
|
|
999
|
+
const pollCreationMessage = {
|
|
1000
|
+
name: message.poll.name,
|
|
1001
|
+
selectableOptionsCount: message.poll.selectableCount,
|
|
1002
|
+
options: message.poll.values.map(optionName => ({ optionName })),
|
|
1003
|
+
endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
|
|
1004
|
+
hideParticipantName: message.poll.hideVoter ?? false,
|
|
1005
|
+
allowAddOption: message.poll.canAddOption ?? false
|
|
1006
|
+
}
|
|
1007
|
+
if (message.poll.toAnnouncementGroup) {
|
|
1008
|
+
m.pollCreationMessageV2 = pollCreationMessage // v2: community announcement groups (single + multiple select)
|
|
1009
|
+
} else if (message.poll.pollType === 1) {
|
|
1010
|
+
if (!message.poll.correctAnswer) throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 })
|
|
1011
|
+
m.pollCreationMessageV5 = {
|
|
1012
|
+
...pollCreationMessage, // quiz — newsletter only
|
|
1013
|
+
correctAnswer: { optionName: message.poll.correctAnswer.toString() },
|
|
1014
|
+
pollType: 1,
|
|
1015
|
+
selectableOptionsCount: 1
|
|
1016
|
+
}
|
|
1017
|
+
} else if (message.poll.hideVoter) {
|
|
1018
|
+
m.pollCreationMessageV6 = pollCreationMessage // v6: hidden-voter-names poll variant
|
|
1019
|
+
} else if (message.poll.selectableCount === 1) {
|
|
1020
|
+
m.pollCreationMessageV3 = pollCreationMessage // v3: single select polls
|
|
1021
|
+
} else {
|
|
1022
|
+
m.pollCreationMessage = pollCreationMessage // multiple choice polls
|
|
1023
|
+
}
|
|
1024
|
+
m.messageContextInfo = { messageSecret: message.poll.messageSecret || randomBytes(32) }
|
|
1025
|
+
} else if (hasNonNullishProperty(message, 'pollResult')) {
|
|
1026
|
+
const pollResultSnapshotMessage = {
|
|
1027
|
+
name: message.pollResult.name,
|
|
1028
|
+
pollVotes: message.pollResult.votes.map(vote => ({ optionName: vote.name, optionVoteCount: parseInt(vote.voteCount) }))
|
|
1029
|
+
}
|
|
1030
|
+
if (message.pollResult.pollType === 1) {
|
|
1031
|
+
pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ
|
|
1032
|
+
m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage
|
|
1033
|
+
} else {
|
|
1034
|
+
pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL
|
|
1035
|
+
m.pollResultSnapshotMessage = pollResultSnapshotMessage
|
|
1036
|
+
}
|
|
1037
|
+
} else if (hasNonNullishProperty(message, 'pollUpdate')) {
|
|
1038
|
+
if (!message.pollUpdate.key) throw new Boom('Message key is required', { statusCode: 400 })
|
|
1039
|
+
if (!message.pollUpdate.vote) throw new Boom('Encrypted vote payload is required', { statusCode: 400 })
|
|
1040
|
+
m.pollUpdateMessage = { metadata: message.pollUpdate.metadata, pollCreationMessageKey: message.pollUpdate.key, senderTimestampMs: Date.now(), vote: message.pollUpdate.vote }
|
|
1041
|
+
} else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
|
|
1042
|
+
m.paymentInviteMessage = { expiryTimestamp: Date.now(), serviceType: message.paymentInviteServiceType }
|
|
1043
|
+
} else if (hasNonNullishProperty(message, 'orderText')) {
|
|
1044
|
+
if (!Buffer.isBuffer(message.thumbnail)) throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 })
|
|
1045
|
+
m.orderMessage = {
|
|
1046
|
+
itemCount: 1,
|
|
1047
|
+
messageVersion: 1,
|
|
1048
|
+
orderTitle: LIBRARY_NAME,
|
|
1049
|
+
status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
|
|
1050
|
+
surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
|
|
1051
|
+
token: generateMessageIDV2(),
|
|
1052
|
+
totalAmount1000: 1000,
|
|
1053
|
+
totalCurrencyCode: 'IDR',
|
|
1054
|
+
...message,
|
|
1055
|
+
message: message.orderText
|
|
1056
|
+
}
|
|
1057
|
+
delete m.orderMessage.orderText
|
|
1058
|
+
} else if (hasNonNullishProperty(message, 'album')) {
|
|
1059
|
+
if (!Array.isArray(message.album)) throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 })
|
|
1060
|
+
let videoCount = 0
|
|
1061
|
+
let imageCount = 0
|
|
1062
|
+
for (const item of message.album) {
|
|
1063
|
+
if (item.video) videoCount++
|
|
1064
|
+
if (item.image) imageCount++
|
|
1065
|
+
}
|
|
1066
|
+
if (videoCount + imageCount < 2) throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 })
|
|
1067
|
+
m.albumMessage = { expectedImageCount: imageCount, expectedVideoCount: videoCount }
|
|
1068
|
+
} else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
|
|
1069
|
+
m.protocolMessage = { type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER }
|
|
1070
|
+
} else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
|
|
1071
|
+
m.requestPhoneNumberMessage = {}
|
|
1072
|
+
} else if (hasNonNullishProperty(message, 'limitSharing')) {
|
|
1073
|
+
m.protocolMessage = {
|
|
1074
|
+
type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
|
|
1075
|
+
limitSharing: { sharingLimited: message.limitSharing === true, trigger: 1, limitSharingSettingTimestamp: Date.now(), initiatedByMe: true }
|
|
1076
|
+
}
|
|
1077
|
+
} else {
|
|
1078
|
+
m = await prepareWAMessageMedia(message, options)
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
if (hasNonNullishProperty(message, 'buttons')) {
|
|
1082
|
+
const buttonsMessage = {
|
|
1083
|
+
buttons: message.buttons.map(button => {
|
|
1084
|
+
const buttonText = button.text || button.buttonText
|
|
1085
|
+
if (hasOptionalProperty(button, 'sections')) {
|
|
1086
|
+
return { nativeFlowInfo: { name: 'single_select', paramsJson: JSON.stringify({ title: buttonText, sections: button.sections }) }, type: ButtonType.NATIVE_FLOW }
|
|
1087
|
+
}
|
|
1088
|
+
if (hasOptionalProperty(button, 'name')) {
|
|
1089
|
+
return { nativeFlowInfo: { name: button.name, paramsJson: button.paramsJson }, type: ButtonType.NATIVE_FLOW }
|
|
1090
|
+
}
|
|
1091
|
+
return { buttonId: button.id || button.buttonId, buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText, type: button.type || ButtonType.RESPONSE }
|
|
1092
|
+
})
|
|
1093
|
+
}
|
|
1094
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1095
|
+
buttonsMessage.contentText = message.text
|
|
1096
|
+
buttonsMessage.headerType = ButtonHeaderType.EMPTY
|
|
1097
|
+
} else {
|
|
1098
|
+
if (hasOptionalProperty(message, 'caption')) buttonsMessage.contentText = message.caption
|
|
1099
|
+
const type = Object.keys(m)[0].replace('Message', '').toUpperCase()
|
|
1100
|
+
buttonsMessage.headerType = ButtonHeaderType[type]
|
|
1101
|
+
Object.assign(buttonsMessage, m)
|
|
1102
|
+
}
|
|
1103
|
+
if (hasOptionalProperty(message, 'footer')) buttonsMessage.footerText = message.footer
|
|
1104
|
+
m = { buttonsMessage }
|
|
1105
|
+
} else if (hasNonNullishProperty(message, 'sections')) {
|
|
1106
|
+
m = { listMessage: { sections: message.sections, buttonText: message.buttonText, title: message.title, footerText: message.footer, description: message.text, listType: ListType.SINGLE_SELECT } }
|
|
1107
|
+
} else if (hasNonNullishProperty(message, 'templateButtons')) {
|
|
1108
|
+
const hydratedTemplate = {
|
|
1109
|
+
hydratedButtons: message.templateButtons.map((button, i) => {
|
|
1110
|
+
const buttonText = button.text || button.buttonText
|
|
1111
|
+
if (hasOptionalProperty(button, 'id')) return { index: i, quickReplyButton: { displayText: buttonText || '👉🏻 Click', id: button.id } }
|
|
1112
|
+
if (hasOptionalProperty(button, 'url')) return { index: i, urlButton: { displayText: buttonText || '🌐 Visit', url: button.url } }
|
|
1113
|
+
if (hasOptionalProperty(button, 'call')) return { index: i, callButton: { displayText: buttonText || '📞 Call', phoneNumber: button.call } }
|
|
1114
|
+
button.index = button.index || i
|
|
1115
|
+
return button
|
|
1116
|
+
})
|
|
1117
|
+
}
|
|
1118
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1119
|
+
hydratedTemplate.hydratedContentText = message.text
|
|
1120
|
+
} else {
|
|
1121
|
+
if (hasOptionalProperty(message, 'caption')) {
|
|
1122
|
+
hydratedTemplate.hydratedTitleText = message.title
|
|
1123
|
+
hydratedTemplate.hydratedContentText = message.caption
|
|
1124
|
+
}
|
|
1125
|
+
Object.assign(hydratedTemplate, m)
|
|
1126
|
+
}
|
|
1127
|
+
if (hasOptionalProperty(message, 'footer')) hydratedTemplate.hydratedFooterText = message.footer
|
|
1128
|
+
hydratedTemplate.templateId = message.id || 'template-' + Date.now()
|
|
1129
|
+
m = { templateMessage: { hydratedFourRowTemplate: hydratedTemplate, hydratedTemplate } }
|
|
1130
|
+
} else if (hasNonNullishProperty(message, 'nativeFlow')) {
|
|
1131
|
+
const interactiveMessage = { nativeFlowMessage: prepareNativeFlowButtons(message) }
|
|
1132
|
+
if (hasOptionalProperty(message, 'bizJid')) {
|
|
1133
|
+
interactiveMessage.collectionMessage = { bizJid: message.bizJid, id: message.id, messageVersion: 1 }
|
|
1134
|
+
} else if (hasOptionalProperty(message, 'shopSurface')) {
|
|
1135
|
+
interactiveMessage.shopStorefrontMessage = { surface: message.shopSurface, id: message.id, messageVersion: 1 }
|
|
1136
|
+
}
|
|
1137
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1138
|
+
interactiveMessage.body = { text: message.text }
|
|
1139
|
+
} else {
|
|
1140
|
+
if (hasOptionalProperty(message, 'caption')) {
|
|
1141
|
+
const isValidHeader = hasValidInteractiveHeader(m)
|
|
1142
|
+
if (!isValidHeader) throw new Boom('Invalid media type for interactive message header', { statusCode: 400 })
|
|
1143
|
+
interactiveMessage.header = { title: message.title || '', subtitle: message.subtitle || '', hasMediaAttachment: isValidHeader }
|
|
1144
|
+
interactiveMessage.body = { text: message.caption }
|
|
1145
|
+
}
|
|
1146
|
+
if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) interactiveMessage.jpegThumbnail = message.thumbnail
|
|
1147
|
+
Object.assign(interactiveMessage.header, m)
|
|
1148
|
+
}
|
|
1149
|
+
if (hasOptionalProperty(message, 'audioFooter')) {
|
|
1150
|
+
const { audioMessage } = await prepareWAMessageMedia({ audio: message.audioFooter }, options)
|
|
1151
|
+
interactiveMessage.footer = { audioMessage, hasMediaAttachment: true }
|
|
1152
|
+
} else if (hasOptionalProperty(message, 'footer')) {
|
|
1153
|
+
interactiveMessage.footer = { text: message.footer }
|
|
1154
|
+
}
|
|
1155
|
+
m = { interactiveMessage }
|
|
1156
|
+
} else if (hasNonNullishProperty(message, 'cards')) {
|
|
1157
|
+
const interactiveMessage = {
|
|
1158
|
+
carouselMessage: {
|
|
1159
|
+
cards: await Promise.all(
|
|
1160
|
+
message.cards.map(async card => {
|
|
1161
|
+
let carouselHeader = {}
|
|
1162
|
+
if (hasNonNullishProperty(card, 'product')) carouselHeader.productMessage = await prepareProductMessage(card, options)
|
|
1163
|
+
else carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}))
|
|
1164
|
+
const isValidHeader = hasValidCarouselHeader(carouselHeader)
|
|
1165
|
+
if (!isValidHeader) throw new Boom('Invalid media type for carousel card', { statusCode: 400 })
|
|
1166
|
+
const carouselCard = { nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : []) }
|
|
1167
|
+
if (hasOptionalProperty(card, 'text')) {
|
|
1168
|
+
carouselCard.body = { text: card.text }
|
|
1169
|
+
} else {
|
|
1170
|
+
if (hasOptionalProperty(card, 'caption')) {
|
|
1171
|
+
carouselCard.header = { title: card.title || '', subtitle: card.subtitle || '', hasMediaAttachment: isValidHeader }
|
|
1172
|
+
carouselCard.body = { text: card.caption }
|
|
1173
|
+
}
|
|
1174
|
+
if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) carouselCard.jpegThumbnail = card.thumbnail
|
|
1175
|
+
Object.assign(carouselCard.header, carouselHeader)
|
|
1176
|
+
}
|
|
1177
|
+
if (hasOptionalProperty(card, 'audioFooter')) {
|
|
1178
|
+
const { audioMessage } = await prepareWAMessageMedia({ audio: card.audioFooter }, options)
|
|
1179
|
+
carouselCard.footer = { audioMessage, hasMediaAttachment: true }
|
|
1180
|
+
} else if (hasOptionalProperty(card, 'footer')) {
|
|
1181
|
+
carouselCard.footer = { text: card.footer }
|
|
1182
|
+
}
|
|
1183
|
+
return carouselCard
|
|
1184
|
+
})
|
|
1185
|
+
),
|
|
1186
|
+
carouselCardType: CarouselCardType.UNKNOWN,
|
|
1187
|
+
messageVersion: 1
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
if (hasOptionalProperty(message, 'text')) interactiveMessage.body = { text: message.text }
|
|
1191
|
+
if (hasOptionalProperty(message, 'footer')) interactiveMessage.footer = { text: message.footer }
|
|
1192
|
+
m = { interactiveMessage }
|
|
1193
|
+
} else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
|
|
1194
|
+
const requestPaymentMessage = {
|
|
1195
|
+
amount: { currencyCode: 'IDR', offset: 1000, value: 1000 },
|
|
1196
|
+
amount1000: 1000,
|
|
1197
|
+
currencyCodeIso4217: 'IDR',
|
|
1198
|
+
expiryTimestamp: Date.now(),
|
|
1199
|
+
noteMessage: m,
|
|
1200
|
+
requestFrom: message.requestPaymentFrom,
|
|
1201
|
+
...message
|
|
1202
|
+
}
|
|
1203
|
+
delete requestPaymentMessage.requestPaymentFrom
|
|
1204
|
+
if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
|
|
1205
|
+
Object.assign(requestPaymentMessage.noteMessage, m)
|
|
1206
|
+
} else {
|
|
1207
|
+
throw new Boom('Invalid message type for request payment note message', { statusCode: 400 })
|
|
1208
|
+
}
|
|
1209
|
+
m = { requestPaymentMessage }
|
|
1210
|
+
} else if (hasNonNullishProperty(message, 'invoiceNote')) {
|
|
1211
|
+
const attachment = m.imageMessage || m.documentMessage
|
|
1212
|
+
const type = Object.keys(m)[0].replace('Message', '').toUpperCase()
|
|
1213
|
+
const invoiceMessage = { attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'], note: message.invoiceNote }
|
|
1214
|
+
if (attachment) {
|
|
1215
|
+
const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment
|
|
1216
|
+
Object.assign(invoiceMessage, {
|
|
1217
|
+
attachmentDirectPath: directPath,
|
|
1218
|
+
attachmentFileEncSha256: fileEncSha256,
|
|
1219
|
+
attachmentFileSha256: fileSha256,
|
|
1220
|
+
attachmentJpegThumbnail: jpegThumbnail,
|
|
1221
|
+
attachmentMediaKey: mediaKey,
|
|
1222
|
+
attachmentMediaKeyTimestamp: mediaKeyTimestamp,
|
|
1223
|
+
attachmentMimetype: mimetype,
|
|
1224
|
+
token: generateMessageIDV2()
|
|
1225
|
+
})
|
|
1226
|
+
} else {
|
|
1227
|
+
throw new Boom('Invalid media type for invoice message', { statusCode: 400 })
|
|
1228
|
+
}
|
|
1229
|
+
m = { invoiceMessage }
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
|
|
1233
|
+
const messageType = Object.keys(m)[0]
|
|
1234
|
+
const key = m[messageType]
|
|
1235
|
+
const content = message.externalAdReply
|
|
1236
|
+
if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) throw new Boom('Thumbnail must in buffer type', { statusCode: 400 })
|
|
1237
|
+
if (content.url != null && typeof content.url !== 'string') throw new Boom('externalAdReply.url must be a string', { statusCode: 400 })
|
|
1238
|
+
const externalAdReply = {
|
|
1239
|
+
...content,
|
|
1240
|
+
body: content.body,
|
|
1241
|
+
mediaType: content.mediaType || 1,
|
|
1242
|
+
mediaUrl: content.url,
|
|
1243
|
+
renderLargerThumbnail: content.largeThumbnail,
|
|
1244
|
+
sourceUrl: content.url,
|
|
1245
|
+
thumbnail: content.thumbnail,
|
|
1246
|
+
thumbnailUrl: content.url ? content.url + '?update=' + Date.now() : undefined,
|
|
1247
|
+
title: content.title || LIBRARY_NAME
|
|
1248
|
+
}
|
|
1249
|
+
delete externalAdReply.subTitle
|
|
1250
|
+
delete externalAdReply.largeThumbnail
|
|
1251
|
+
delete externalAdReply.url
|
|
1252
|
+
if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply }
|
|
1253
|
+
else if (key) key.contextInfo = { externalAdReply }
|
|
1254
|
+
}
|
|
1255
|
+
if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) || (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
|
|
1256
|
+
const messageType = Object.keys(m)[0]
|
|
1257
|
+
const key = m[messageType]
|
|
1258
|
+
if (key && 'contextInfo' in key) {
|
|
1259
|
+
key.contextInfo = key.contextInfo || {}
|
|
1260
|
+
if (message.mentions?.length) key.contextInfo.mentionedJid = message.mentions
|
|
1261
|
+
if (message.mentionAll) key.contextInfo.nonJidMentions = 1
|
|
1262
|
+
} else if (key) {
|
|
1263
|
+
key.contextInfo = { mentionedJid: message.mentions, nonJidMentions: message.mentionAll ? 1 : 0 }
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
|
|
1267
|
+
const messageType = Object.keys(m)[0]
|
|
1268
|
+
const key = m[messageType]
|
|
1269
|
+
if ('contextInfo' in key && !!key.contextInfo) key.contextInfo = { ...key.contextInfo, ...message.contextInfo }
|
|
1270
|
+
else if (key) key.contextInfo = message.contextInfo
|
|
1271
|
+
}
|
|
1272
|
+
if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
|
|
1273
|
+
const messageType = Object.keys(m)[0]
|
|
1274
|
+
const key = m[messageType]
|
|
1275
|
+
if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.isGroupStatus = message.groupStatus
|
|
1276
|
+
else if (key) key.contextInfo = { isGroupStatus: message.groupStatus }
|
|
1277
|
+
m = { groupStatusMessageV2: { message: m } }
|
|
1278
|
+
delete message.groupStatus
|
|
1279
|
+
}
|
|
1280
|
+
if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
|
|
1281
|
+
const messageType = Object.keys(m)[0]
|
|
1282
|
+
const key = m[messageType]
|
|
1283
|
+
if ('contextInfo' in key && !!key.contextInfo) key.contextInfo.isSpoiler = message.spoiler
|
|
1284
|
+
else if (key) key.contextInfo = { isSpoiler: message.spoiler }
|
|
1285
|
+
m = { spoilerMessage: { message: m } }
|
|
1286
|
+
delete message.spoiler
|
|
1287
|
+
} else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
|
|
1288
|
+
if (!m.interactiveMessage) throw new Boom('Invalid message type for template', { statusCode: 400 })
|
|
1289
|
+
m = { templateMessage: { interactiveMessageTemplate: m.interactiveMessage, templateId: message.id || 'template-' + Date.now() } }
|
|
1290
|
+
delete message.interactiveAsTemplate
|
|
1291
|
+
}
|
|
1292
|
+
if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
|
|
1293
|
+
m = { ephemeralMessage: { message: m } }
|
|
1294
|
+
delete message.ephemeral
|
|
1295
|
+
}
|
|
1296
|
+
if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
|
|
1297
|
+
m = { lottieStickerMessage: { message: m } }
|
|
1298
|
+
} else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
|
1299
|
+
m = { viewOnceMessage: { message: m } }
|
|
1300
|
+
} else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
|
|
1301
|
+
m = { viewOnceMessageV2: { message: m } }
|
|
1302
|
+
delete message.viewOnceV2
|
|
1303
|
+
} else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
|
|
1304
|
+
m = { viewOnceMessageV2Extension: { message: m } }
|
|
1305
|
+
delete message.viewOnceV2Extension
|
|
1306
|
+
}
|
|
1307
|
+
if (hasOptionalProperty(message, 'edit')) {
|
|
1308
|
+
m = { protocolMessage: { key: message.edit, editedMessage: m, timestampMs: Date.now(), type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT } }
|
|
1309
|
+
}
|
|
1310
|
+
if (shouldIncludeReportingToken(m)) {
|
|
1311
|
+
m.messageContextInfo = m.messageContextInfo || {}
|
|
1312
|
+
if (!m.messageContextInfo.messageSecret) m.messageContextInfo.messageSecret = randomBytes(32)
|
|
1313
|
+
}
|
|
1314
|
+
return WAProto.Message.create(m)
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
export const generateWAMessageFromContent = (jid, message, options) => {
|
|
1318
|
+
if (!options.timestamp) options.timestamp = new Date()
|
|
1319
|
+
const innerMessage = normalizeMessageContent(message)
|
|
1320
|
+
const messageContextInfo = message.messageContextInfo
|
|
1321
|
+
const key = getContentType(innerMessage)
|
|
1322
|
+
const timestamp = unixTimestampSeconds(options.timestamp)
|
|
1323
|
+
const isNewsletter = isJidNewsletter(jid)
|
|
1324
|
+
const { quoted, userJid } = options
|
|
1325
|
+
|
|
1326
|
+
if (quoted) {
|
|
1327
|
+
const participant = quoted.key.fromMe ? userJid : quoted.participant || quoted.key.participant || quoted.key.remoteJid
|
|
1328
|
+
let quotedMsg = normalizeMessageContent(quoted.message)
|
|
1329
|
+
const msgType = getContentType(quotedMsg)
|
|
1330
|
+
quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] }) // strip redundant properties
|
|
1331
|
+
const quotedContent = quotedMsg[msgType]
|
|
1332
|
+
if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) delete quotedContent.contextInfo
|
|
1333
|
+
const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {}
|
|
1334
|
+
contextInfo.participant = jidNormalizedUser(participant)
|
|
1335
|
+
contextInfo.stanzaId = quoted.key.id
|
|
1336
|
+
contextInfo.quotedMessage = quotedMsg
|
|
1337
|
+
// if a participant is quoted, then it must be a group, so remoteJid of that group must also be set
|
|
1338
|
+
if (!isNewsletter && jid !== quoted.key.remoteJid) contextInfo.remoteJid = quoted.key.remoteJid
|
|
1339
|
+
if (contextInfo && innerMessage[key]) innerMessage[key].contextInfo = contextInfo
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
if (!!options?.ephemeralExpiration && key !== 'protocolMessage' && key !== 'ephemeralMessage' && !isNewsletter) {
|
|
1343
|
+
innerMessage[key].contextInfo = { ...(innerMessage[key].contextInfo || {}), expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL }
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
message = WAProto.Message.create(message)
|
|
1347
|
+
const messageJSON = {
|
|
1348
|
+
key: { remoteJid: jid, fromMe: true, id: options?.messageId || generateMessageIDV2() },
|
|
1349
|
+
message,
|
|
1350
|
+
messageTimestamp: timestamp,
|
|
1351
|
+
messageStubParameters: [],
|
|
1352
|
+
participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined,
|
|
1353
|
+
status: WAMessageStatus.PENDING
|
|
1354
|
+
}
|
|
1355
|
+
return WAProto.WebMessageInfo.fromObject(messageJSON)
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
export const generateWAMessage = async (jid, content, options) => {
|
|
1359
|
+
// ensure msg ID is with every log
|
|
1360
|
+
options.logger = options?.logger?.child({ msgId: options.messageId })
|
|
1361
|
+
// Pass jid in the options to generateWAMessageContent (copy: do not mutate the caller's options)
|
|
1362
|
+
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options)
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/** Get the key to access the true type of content */
|
|
1366
|
+
export const getContentType = content => {
|
|
1367
|
+
if (content) {
|
|
1368
|
+
const keys = Object.keys(content)
|
|
1369
|
+
return keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
const getFutureProofMessage = message =>
|
|
1374
|
+
message?.associatedChildMessage ||
|
|
1375
|
+
message?.botForwardedMessage ||
|
|
1376
|
+
message?.botInvokeMessage ||
|
|
1377
|
+
message?.botTaskMessage ||
|
|
1378
|
+
message?.documentWithCaptionMessage ||
|
|
1379
|
+
message?.editedMessage ||
|
|
1380
|
+
message?.ephemeralMessage ||
|
|
1381
|
+
message?.eventCoverImage ||
|
|
1382
|
+
message?.groupMentionedMessage ||
|
|
1383
|
+
message?.groupStatusMentionMessage ||
|
|
1384
|
+
message?.groupStatusMessage ||
|
|
1385
|
+
message?.groupStatusMessageV2 ||
|
|
1386
|
+
message?.limitSharingMessage ||
|
|
1387
|
+
message?.lottieStickerMessage ||
|
|
1388
|
+
message?.newsletterAdminProfileMessage ||
|
|
1389
|
+
message?.newsletterAdminProfileMessageV2 ||
|
|
1390
|
+
message?.newsletterAdminProfileStatusMessage ||
|
|
1391
|
+
message?.pollCreationMessageV4 ||
|
|
1392
|
+
message?.pollCreationOptionImageMessage ||
|
|
1393
|
+
message?.questionMessage ||
|
|
1394
|
+
message?.questionReplyMessage ||
|
|
1395
|
+
message?.spoilerMessage ||
|
|
1396
|
+
message?.statusAddYours ||
|
|
1397
|
+
message?.statusMentionMessage ||
|
|
1398
|
+
message?.viewOnceMessage ||
|
|
1399
|
+
message?.viewOnceMessageV2 ||
|
|
1400
|
+
message?.viewOnceMessageV2Extension
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* Normalizes ephemeral, view once messages to regular message content.
|
|
1404
|
+
* Eg. image messages in ephemeral messages, in view once messages etc.
|
|
1405
|
+
*/
|
|
1406
|
+
export const normalizeMessageContent = content => {
|
|
1407
|
+
if (!content) return undefined
|
|
1408
|
+
for (let i = 0; i < 5; i++) {
|
|
1409
|
+
const inner = getFutureProofMessage(content)
|
|
1410
|
+
if (!inner) break
|
|
1411
|
+
content = inner.message
|
|
1412
|
+
}
|
|
1413
|
+
return content
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/** Extract the true message content from a message. Eg. extracts the inner message from a disappearing/view-once message. */
|
|
1417
|
+
export const extractMessageContent = content => {
|
|
1418
|
+
const extractFromTemplateMessage = msg => {
|
|
1419
|
+
if (msg.imageMessage) return { imageMessage: msg.imageMessage }
|
|
1420
|
+
if (msg.documentMessage) return { documentMessage: msg.documentMessage }
|
|
1421
|
+
if (msg.videoMessage) return { videoMessage: msg.videoMessage }
|
|
1422
|
+
if (msg.locationMessage) return { locationMessage: msg.locationMessage }
|
|
1423
|
+
return { conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : '' }
|
|
1424
|
+
}
|
|
1425
|
+
content = normalizeMessageContent(content)
|
|
1426
|
+
if (content?.buttonsMessage) return extractFromTemplateMessage(content.buttonsMessage)
|
|
1427
|
+
if (content?.templateMessage?.hydratedFourRowTemplate) return extractFromTemplateMessage(content.templateMessage.hydratedFourRowTemplate)
|
|
1428
|
+
if (content?.templateMessage?.hydratedTemplate) return extractFromTemplateMessage(content.templateMessage.hydratedTemplate)
|
|
1429
|
+
if (content?.templateMessage?.fourRowTemplate) return extractFromTemplateMessage(content.templateMessage.fourRowTemplate)
|
|
1430
|
+
return content
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
/** Returns the device predicted by message ID */
|
|
1434
|
+
export const getDevice = id =>
|
|
1435
|
+
/^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^(3F|.{18}$)/.test(id) ? 'desktop' : 'unknown'
|
|
1436
|
+
|
|
1437
|
+
/** Upserts a receipt in the message */
|
|
1438
|
+
export const updateMessageWithReceipt = (msg, receipt) => {
|
|
1439
|
+
msg.userReceipt = msg.userReceipt || []
|
|
1440
|
+
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
|
|
1441
|
+
if (recp) Object.assign(recp, receipt)
|
|
1442
|
+
else msg.userReceipt.push(receipt)
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
/** Update the message with a new reaction */
|
|
1446
|
+
export const updateMessageWithReaction = (msg, reaction) => {
|
|
1447
|
+
const authorID = getKeyAuthor(reaction.key)
|
|
1448
|
+
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
|
|
1449
|
+
reaction.text = reaction.text || ''
|
|
1450
|
+
reactions.push(reaction)
|
|
1451
|
+
msg.reactions = reactions
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/** Update the message with a new poll update */
|
|
1455
|
+
export const updateMessageWithPollUpdate = (msg, update) => {
|
|
1456
|
+
const authorID = getKeyAuthor(update.pollUpdateMessageKey)
|
|
1457
|
+
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
|
|
1458
|
+
if (update.vote?.selectedOptions?.length) reactions.push(update)
|
|
1459
|
+
msg.pollUpdates = reactions
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/** Update the message with a new event response */
|
|
1463
|
+
export const updateMessageWithEventResponse = (msg, update) => {
|
|
1464
|
+
const authorID = getKeyAuthor(update.eventResponseMessageKey)
|
|
1465
|
+
const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID)
|
|
1466
|
+
responses.push(update)
|
|
1467
|
+
msg.eventResponses = responses
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/** Aggregates all poll updates in a poll. Returns a list of options & their voters. */
|
|
1471
|
+
export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
|
|
1472
|
+
const opts =
|
|
1473
|
+
message?.pollCreationMessage?.options ||
|
|
1474
|
+
message?.pollCreationMessageV2?.options ||
|
|
1475
|
+
message?.pollCreationMessageV3?.options ||
|
|
1476
|
+
message?.pollCreationMessageV5?.options ||
|
|
1477
|
+
message?.pollCreationMessageV6?.options ||
|
|
1478
|
+
[]
|
|
1479
|
+
const voteHashMap = opts.reduce((acc, opt) => {
|
|
1480
|
+
const hash = sha256(Buffer.from(opt.optionName || '')).toString()
|
|
1481
|
+
acc[hash] = { name: opt.optionName || '', voters: [] }
|
|
1482
|
+
return acc
|
|
1483
|
+
}, {})
|
|
1484
|
+
for (const update of pollUpdates || []) {
|
|
1485
|
+
const { vote } = update
|
|
1486
|
+
if (!vote) continue
|
|
1487
|
+
for (const option of vote.selectedOptions || []) {
|
|
1488
|
+
const hash = option.toString()
|
|
1489
|
+
let data = voteHashMap[hash]
|
|
1490
|
+
if (!data) {
|
|
1491
|
+
voteHashMap[hash] = { name: 'Unknown', voters: [] }
|
|
1492
|
+
data = voteHashMap[hash]
|
|
1493
|
+
}
|
|
1494
|
+
voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId))
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
return Object.values(voteHashMap)
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** Aggregates all event responses in an event message. Returns a list of response types & their responders. */
|
|
1501
|
+
export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
|
|
1502
|
+
const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE']
|
|
1503
|
+
const responseMap = {}
|
|
1504
|
+
for (const type of responseTypes) responseMap[type] = { response: type, responders: [] }
|
|
1505
|
+
for (const update of eventResponses || []) {
|
|
1506
|
+
const responseType = update.eventResponse || 'UNKNOWN'
|
|
1507
|
+
if (responseType !== 'UNKNOWN' && responseMap[responseType]) responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId))
|
|
1508
|
+
}
|
|
1509
|
+
return Object.values(responseMap)
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk. */
|
|
1513
|
+
export const aggregateMessageKeysNotFromMe = keys => {
|
|
1514
|
+
const keyMap = {}
|
|
1515
|
+
for (const { remoteJid, id, participant, fromMe } of keys) {
|
|
1516
|
+
if (!fromMe) {
|
|
1517
|
+
const uqKey = `${remoteJid}:${participant || ''}`
|
|
1518
|
+
if (!keyMap[uqKey]) keyMap[uqKey] = { jid: remoteJid, participant, messageIds: [] }
|
|
1519
|
+
keyMap[uqKey].messageIds.push(id)
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
return Object.values(keyMap)
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
const REUPLOAD_REQUIRED_STATUS = [410, 404]
|
|
1526
|
+
|
|
1527
|
+
/** Downloads the given message. Throws an error if it's not a media message. */
|
|
1528
|
+
export const downloadMediaMessage = async (message, type, options, ctx) => {
|
|
1529
|
+
async function downloadMsg() {
|
|
1530
|
+
const mContent = extractMessageContent(message.message)
|
|
1531
|
+
if (!mContent) throw new Boom('No message present', { statusCode: 400, data: message })
|
|
1532
|
+
const contentType = getContentType(mContent)
|
|
1533
|
+
let mediaType = contentType?.replace('Message', '')
|
|
1534
|
+
const media = mContent[contentType]
|
|
1535
|
+
if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
|
1536
|
+
throw new Boom(`"${contentType}" message is not a media message`)
|
|
1537
|
+
}
|
|
1538
|
+
let download
|
|
1539
|
+
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
|
1540
|
+
download = { directPath: media.thumbnailDirectPath, mediaKey: media.mediaKey }
|
|
1541
|
+
mediaType = 'thumbnail-link'
|
|
1542
|
+
} else {
|
|
1543
|
+
download = media
|
|
1544
|
+
}
|
|
1545
|
+
const stream = await downloadContentFromMessage(download, mediaType, options)
|
|
1546
|
+
if (type === 'buffer') {
|
|
1547
|
+
const bufferArray = []
|
|
1548
|
+
for await (const chunk of stream) bufferArray.push(chunk)
|
|
1549
|
+
return Buffer.concat(bufferArray)
|
|
1550
|
+
}
|
|
1551
|
+
return stream
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
return downloadMsg().catch(async error => {
|
|
1555
|
+
if (ctx && typeof error?.status === 'number' && REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
|
|
1556
|
+
ctx.logger.info({ key: message.key }, 'sending reupload media request...')
|
|
1557
|
+
message = await ctx.reuploadRequest(message)
|
|
1558
|
+
return downloadMsg()
|
|
1559
|
+
}
|
|
1560
|
+
throw error
|
|
1561
|
+
})
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
/** Checks whether the given message is a media message; if it is returns the inner content */
|
|
1565
|
+
export const assertMediaContent = content => {
|
|
1566
|
+
content = extractMessageContent(content)
|
|
1567
|
+
const mediaContent = content?.documentMessage || content?.imageMessage || content?.videoMessage || content?.audioMessage || content?.stickerMessage
|
|
1568
|
+
if (!mediaContent) throw new Boom('given message is not a media message', { statusCode: 400, data: content })
|
|
1569
|
+
return mediaContent
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/** Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag, or ANIM/ANMF chunks */
|
|
1573
|
+
const isAnimatedWebP = buffer => {
|
|
1574
|
+
if (!isWebPBuffer(buffer)) return false
|
|
1575
|
+
let offset = 12
|
|
1576
|
+
while (offset < buffer.length - 8) {
|
|
1577
|
+
const chunkFourCC = buffer.toString('ascii', offset, offset + 4)
|
|
1578
|
+
const chunkSize = buffer.readUInt32LE(offset + 4)
|
|
1579
|
+
if (chunkFourCC === 'VP8X') {
|
|
1580
|
+
const flagsOffset = offset + 8
|
|
1581
|
+
if (flagsOffset < buffer.length && buffer[flagsOffset] & 0x02) return true
|
|
1582
|
+
} else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
|
|
1583
|
+
return true
|
|
1584
|
+
}
|
|
1585
|
+
offset += 8 + chunkSize + (chunkSize % 2)
|
|
1586
|
+
}
|
|
1587
|
+
return false
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
/** Checks if a buffer is a WebP file */
|
|
1591
|
+
const isWebPBuffer = buffer =>
|
|
1592
|
+
buffer.length >= 12 &&
|
|
1593
|
+
buffer[0] === 0x52 &&
|
|
1594
|
+
buffer[1] === 0x49 &&
|
|
1595
|
+
buffer[2] === 0x46 &&
|
|
1596
|
+
buffer[3] === 0x46 &&
|
|
1597
|
+
buffer[8] === 0x57 &&
|
|
1598
|
+
buffer[9] === 0x45 &&
|
|
1599
|
+
buffer[10] === 0x42 &&
|
|
1600
|
+
buffer[11] === 0x50
|
|
1601
|
+
|
|
1602
|
+
/**
|
|
1603
|
+
* Determines whether a message should include a Biz Binary Node.
|
|
1604
|
+
* A Biz Binary Node is added only for interactive messages such as buttons or other supported interactive types.
|
|
1605
|
+
*/
|
|
1606
|
+
export const shouldIncludeBizBinaryNode = message =>
|
|
1607
|
+
!!(message.buttonsMessage || message.listMessage || message.templateMessage || (message.interactiveMessage && message.interactiveMessage.nativeFlowMessage))
|
|
1608
|
+
|
|
1609
|
+
export { AssociationType }
|