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