@zervonexx/baileys 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -22
- package/README.md +4112 -4112
- package/WAProto/WAProtoCompile.js +322 -322
- package/WAProto/fetcher.js +67 -67
- package/WAProto/index.js +95 -95
- package/WAProto/parser.js +333 -333
- package/lib/Builders/AIRich.js +673 -673
- package/lib/Builders/auto.js +49 -49
- package/lib/Builders/base.js +144 -144
- package/lib/Builders/builders.js +588 -588
- package/lib/Builders/index.js +3 -3
- package/lib/Defaults/index.js +248 -248
- package/lib/Signal/index.js +2 -2
- package/lib/Signal/libsignal.js +526 -526
- package/lib/Signal/lid-mapping.js +282 -282
- package/lib/Socket/Client/index.js +1 -1
- package/lib/Socket/Client/types.js +9 -9
- package/lib/Socket/Client/websocket.js +83 -83
- package/lib/Socket/business.js +151 -151
- package/lib/Socket/chats.js +854 -854
- package/lib/Socket/communities.js +146 -146
- package/lib/Socket/groups.js +293 -293
- package/lib/Socket/index.js +14 -14
- package/lib/Socket/messages-recv.js +993 -993
- package/lib/Socket/messages-send.js +722 -722
- package/lib/Socket/mex.js +33 -33
- package/lib/Socket/newsletter.js +783 -783
- package/lib/Socket/registration.js +154 -154
- package/lib/Socket/socket.js +797 -797
- package/lib/Socket/spam-report.js +143 -143
- package/lib/Socket/username.js +81 -81
- package/lib/Socket/zervonex-handler.js +57 -57
- package/lib/Store/index.js +6 -6
- package/lib/Store/make-cache-manager-store.js +80 -80
- package/lib/Store/make-in-memory-store.js +426 -426
- package/lib/Store/make-ordered-dictionary.js +81 -81
- package/lib/Store/object-repository.js +30 -30
- package/lib/Store/reporting-info-store.js +37 -37
- package/lib/Types/Auth.js +1 -1
- package/lib/Types/Bussines.js +1 -1
- package/lib/Types/Call.js +1 -1
- package/lib/Types/Chat.js +7 -7
- package/lib/Types/Contact.js +1 -1
- package/lib/Types/Events.js +1 -1
- package/lib/Types/GroupMetadata.js +1 -1
- package/lib/Types/Label.js +24 -24
- package/lib/Types/LabelAssociation.js +6 -6
- package/lib/Types/Message.js +14 -14
- package/lib/Types/Newsletter.js +99 -99
- package/lib/Types/Product.js +1 -1
- package/lib/Types/Signal.js +1 -1
- package/lib/Types/Socket.js +14 -14
- package/lib/Types/State.js +26 -26
- package/lib/Types/USync.js +1 -1
- package/lib/Types/index.js +30 -30
- package/lib/Utils/auth-utils.js +159 -159
- package/lib/Utils/baileys-event-stream.js +32 -32
- package/lib/Utils/bot-capabilities.js +40 -40
- package/lib/Utils/bot-planning-replay.js +43 -43
- package/lib/Utils/browser-utils.js +29 -29
- package/lib/Utils/business.js +74 -74
- package/lib/Utils/chat-utils.js +316 -316
- package/lib/Utils/companion-reg-client-utils.js +19 -19
- package/lib/Utils/consumer-application.js +37 -37
- package/lib/Utils/crypto.js +52 -52
- package/lib/Utils/cstoken.js +14 -14
- package/lib/Utils/decode-wa-message.js +199 -199
- package/lib/Utils/event-buffer.js +272 -272
- package/lib/Utils/extras.js +186 -186
- package/lib/Utils/generics.js +194 -194
- package/lib/Utils/history.js +50 -50
- package/lib/Utils/identity-change-handler.js +18 -18
- package/lib/Utils/index.js +40 -40
- package/lib/Utils/link-preview.js +50 -50
- package/lib/Utils/logger.js +2 -2
- package/lib/Utils/lt-hash.js +3 -3
- package/lib/Utils/make-mutex.js +15 -15
- package/lib/Utils/message-composer.js +61 -61
- package/lib/Utils/message-retry-manager.js +47 -47
- package/lib/Utils/messages-media.js +501 -501
- package/lib/Utils/messages.js +942 -942
- package/lib/Utils/meta-ai-msmsg.js +121 -121
- package/lib/Utils/meta-compositing.js +74 -74
- package/lib/Utils/modern-messages.js +234 -234
- package/lib/Utils/native-flow.js +80 -80
- package/lib/Utils/noise-handler.js +160 -160
- package/lib/Utils/pre-key-manager.js +75 -75
- package/lib/Utils/process-message.js +400 -400
- package/lib/Utils/reporting-utils.js +170 -170
- package/lib/Utils/signal.js +166 -166
- package/lib/Utils/spam-report-utils.js +165 -165
- package/lib/Utils/sync-action-utils.js +33 -33
- package/lib/Utils/tc-token-utils.js +153 -153
- package/lib/Utils/use-keyv-auth-state.js +199 -199
- package/lib/Utils/use-multi-file-auth-state.js +83 -83
- package/lib/Utils/validate-connection.js +171 -171
- package/lib/WABinary/constants.js +1320 -1320
- package/lib/WABinary/decode.js +151 -151
- package/lib/WABinary/encode.js +139 -139
- package/lib/WABinary/generic-utils.js +202 -202
- package/lib/WABinary/index.js +6 -6
- package/lib/WABinary/jid-utils.js +235 -235
- package/lib/WABinary/types.js +4 -4
- package/lib/WAM/BinaryInfo.js +9 -9
- package/lib/WAM/constants.js +22852 -22852
- package/lib/WAM/encode.js +149 -149
- package/lib/WAM/index.js +3 -3
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
- package/lib/WAUSync/Protocols/index.js +12 -12
- package/lib/WAUSync/USyncQuery.js +88 -88
- package/lib/WAUSync/USyncUser.js +20 -20
- package/lib/WAUSync/index.js +3 -3
- package/lib/index.js +66 -66
- package/package.json +191 -192
package/lib/Utils/generics.js
CHANGED
|
@@ -1,195 +1,195 @@
|
|
|
1
|
-
import { Boom } from '@hapi/boom'
|
|
2
|
-
import { createHash, randomBytes } from 'crypto'
|
|
3
|
-
import { createRequire } from 'module'
|
|
4
|
-
import { proto, fetchProtoBundle } from '../../WAProto/index.js'
|
|
5
|
-
import { DisconnectReason } from '../Types/index.js'
|
|
6
|
-
import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js'
|
|
7
|
-
import { sha256 } from './crypto.js'
|
|
8
|
-
|
|
9
|
-
export const BufferJSON = {
|
|
10
|
-
replacer: (k, value) => {
|
|
11
|
-
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
|
|
12
|
-
return value
|
|
13
|
-
},
|
|
14
|
-
reviver: (_, value) => {
|
|
15
|
-
if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') return Buffer.from(value.data, 'base64')
|
|
16
|
-
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
17
|
-
const keys = Object.keys(value)
|
|
18
|
-
if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
|
|
19
|
-
const values = Object.values(value)
|
|
20
|
-
if (values.every(v => typeof v === 'number')) return Buffer.from(values)
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
return value
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
|
|
28
|
-
export const isStringNullOrEmpty = value => value == null || value === ''
|
|
29
|
-
|
|
30
|
-
export const writeRandomPadMax16 = msg => { const pad = randomBytes(1); const padLength = (pad[0] & 0x0f) + 1; return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]) }
|
|
31
|
-
export const unpadRandomMax16 = e => { const t = new Uint8Array(e); if (!t.length) throw new Error('unpadPkcs7 given empty bytes'); const r = t[t.length - 1]; if (r > t.length) throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`); return new Uint8Array(t.buffer, t.byteOffset, t.length - r) }
|
|
32
|
-
|
|
33
|
-
export const generateParticipantHashV2 = participants => { participants.sort(); return '2:' + sha256(Buffer.from(participants.join(''))).toString('base64').slice(0, 6) }
|
|
34
|
-
|
|
35
|
-
export const encodeWAMessage = message => {
|
|
36
|
-
try { return writeRandomPadMax16(proto.Message.encode(message?.$type === proto.Message ? message : proto.Message.fromObject(message)).finish()) }
|
|
37
|
-
catch (error) {
|
|
38
|
-
try { return writeRandomPadMax16(proto.Message.encode(message).finish()) }
|
|
39
|
-
catch (e) { console.warn('Message encoding failed:', error.message, e.message); throw new Error(`Failed to encode message: ${error.message}`) }
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export const generateRegistrationId = () => Uint16Array.from(randomBytes(2))[0] & 16383
|
|
44
|
-
|
|
45
|
-
export const encodeBigEndian = (e, t = 4) => { let r = e; const a = new Uint8Array(t); for (let i = t - 1; i >= 0; i--) { a[i] = 255 & r; r >>>= 8 }; return a }
|
|
46
|
-
|
|
47
|
-
export const toNumber = t => { if (typeof t === 'bigint') return Number(t); if (typeof t === 'object' && t) return 'toNumber' in t ? t.toNumber() : (t.low ?? 0); return t || 0 }
|
|
48
|
-
export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
|
|
49
|
-
|
|
50
|
-
export const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
51
|
-
let timeout
|
|
52
|
-
return {
|
|
53
|
-
start: (newIntervalMs, newTask) => { task = newTask || task; intervalMs = newIntervalMs || intervalMs; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => task?.(), intervalMs) },
|
|
54
|
-
cancel: () => { if (timeout) clearTimeout(timeout); timeout = undefined },
|
|
55
|
-
setTask: newTask => (task = newTask),
|
|
56
|
-
setInterval: newInterval => (intervalMs = newInterval)
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export const delay = ms => delayCancellable(ms).delay
|
|
61
|
-
export const delayCancellable = ms => {
|
|
62
|
-
const stack = new Error().stack
|
|
63
|
-
let timeout, reject
|
|
64
|
-
const delay = new Promise((resolve, _reject) => { timeout = setTimeout(resolve, ms); reject = _reject })
|
|
65
|
-
return { delay, cancel: () => { clearTimeout(timeout); reject(new Boom('Cancelled', { statusCode: 500, data: { stack } })) } }
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export const promiseTimeout = async (ms, promise) => {
|
|
69
|
-
if (!ms) return new Promise(promise)
|
|
70
|
-
const stack = new Error().stack
|
|
71
|
-
const { delay, cancel } = delayCancellable(ms)
|
|
72
|
-
return new Promise((resolve, reject) => {
|
|
73
|
-
delay.then(() => reject(new Boom('Timed Out', { statusCode: DisconnectReason.timedOut, data: { stack } }))).catch(reject)
|
|
74
|
-
promise(resolve, reject)
|
|
75
|
-
}).finally(cancel)
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export const generateMessageIDV2 = userId => {
|
|
79
|
-
const data = Buffer.alloc(8 + 20 + 16)
|
|
80
|
-
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
|
81
|
-
if (userId) { const id = jidDecode(userId); if (id?.user) { data.write(id.user, 8); data.write('@c.us', 8 + id.user.length) } }
|
|
82
|
-
randomBytes(16).copy(data, 28)
|
|
83
|
-
return 'ZERVONEX' + createHash('sha256').update(data).digest().toString('hex').toUpperCase().substring(0, 18)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export const generateMessageID = () => 'ZERVONEX' + randomBytes(18).toString('hex').toUpperCase()
|
|
87
|
-
|
|
88
|
-
export const bindWaitForEvent = (ev, event) => async (check, timeoutMs) => {
|
|
89
|
-
let listener, closeListener
|
|
90
|
-
await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
91
|
-
closeListener = ({ connection, lastDisconnect }) => { if (connection === 'close') reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })) }
|
|
92
|
-
ev.on('connection.update', closeListener)
|
|
93
|
-
listener = async update => { if (await check(update)) resolve() }
|
|
94
|
-
ev.on(event, listener)
|
|
95
|
-
}).finally(() => { ev.off(event, listener); ev.off('connection.update', closeListener) })
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update')
|
|
99
|
-
|
|
100
|
-
export const fetchLatestWaWebVersion = async () => {
|
|
101
|
-
const { version } = await fetchProtoBundle()
|
|
102
|
-
return { version: [2, 3000, parseInt(version)], isLatest: true }
|
|
103
|
-
}
|
|
104
|
-
export const fetchLatestBaileysVersion = fetchLatestWaWebVersion
|
|
105
|
-
|
|
106
|
-
export const generateMdTagPrefix = () => { const b = randomBytes(4); return `${b.readUInt16BE()}.${b.readUInt16BE(2)}-` }
|
|
107
|
-
|
|
108
|
-
const STATUS_MAP = { sender: proto.WebMessageInfo.Status.SERVER_ACK, played: proto.WebMessageInfo.Status.PLAYED, read: proto.WebMessageInfo.Status.READ, 'read-self': proto.WebMessageInfo.Status.READ }
|
|
109
|
-
export const getStatusFromReceiptType = type => typeof type === 'undefined' ? proto.WebMessageInfo.Status.DELIVERY_ACK : STATUS_MAP[type]
|
|
110
|
-
|
|
111
|
-
const CODE_MAP = { conflict: DisconnectReason.connectionReplaced }
|
|
112
|
-
export const getErrorCodeFromStreamError = node => { const [reasonNode] = getAllBinaryNodeChildren(node); let reason = reasonNode?.tag || 'unknown'; const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession); if (statusCode === DisconnectReason.restartRequired) reason = 'restart required'; return { reason, statusCode } }
|
|
113
|
-
|
|
114
|
-
export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
115
|
-
switch (tag) {
|
|
116
|
-
case 'offer': case 'offer_notice': return 'offer'
|
|
117
|
-
case 'terminate': return attrs.reason === 'timeout' ? 'timeout' : 'terminate'
|
|
118
|
-
case 'reject': return 'reject'
|
|
119
|
-
case 'accept': return 'accept'
|
|
120
|
-
default: return 'ringing'
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
|
|
125
|
-
export const getCodeFromWSError = error => {
|
|
126
|
-
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) { const code = +error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length); if (!Number.isNaN(code) && code >= 400) return code }
|
|
127
|
-
if (error?.code?.startsWith('E') || error?.message?.includes('timed out')) return 408
|
|
128
|
-
return 500
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export const isWABusinessPlatform = platform => platform === 'smbi' || platform === 'smba'
|
|
132
|
-
export const trimUndefined = obj => { for (const key in obj) if (typeof obj[key] === 'undefined') delete obj[key]; return obj }
|
|
133
|
-
|
|
134
|
-
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
|
|
135
|
-
export const bytesToCrockford = buffer => {
|
|
136
|
-
let value = 0, bitCount = 0
|
|
137
|
-
const crockford = []
|
|
138
|
-
for (const element of buffer) { value = (value << 8) | (element & 0xff); bitCount += 8; while (bitCount >= 5) { crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31)); bitCount -= 5 } }
|
|
139
|
-
if (bitCount > 0) crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
|
|
140
|
-
return crockford.join('')
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export const encodeNewsletterMessage = message => proto.Message.encode(message).finish()
|
|
144
|
-
|
|
145
|
-
const _require = createRequire(import.meta.url)
|
|
146
|
-
const Prism = _require('prismjs')
|
|
147
|
-
const loadPrismLanguages = _require('prismjs/components/index')
|
|
148
|
-
let _prismReady = false
|
|
149
|
-
const ensurePrism = () => { if (_prismReady) return; _prismReady = true; try { loadPrismLanguages() } catch { } }
|
|
150
|
-
|
|
151
|
-
const PRISM_TYPE_MAP = {
|
|
152
|
-
keyword: 1, 'keyword control': 1, builtin: 1, important: 1, bold: 1,
|
|
153
|
-
function: 2, 'function-definition': 2, method: 2, 'method-definition': 2,
|
|
154
|
-
string: 3, 'template-string': 3, 'string interpolation': 3, char: 3, regex: 3,
|
|
155
|
-
number: 4, constant: 4, boolean: 4, unit: 4,
|
|
156
|
-
comment: 5, 'block-comment': 5, prolog: 5, doctype: 5
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
const flattenPrism = (tokens, out = []) => {
|
|
160
|
-
for (const t of tokens) {
|
|
161
|
-
if (typeof t === 'string') { if (t) out.push({ codeContent: t, highlightType: 0 }); continue }
|
|
162
|
-
const type = PRISM_TYPE_MAP[t.type] ?? 0
|
|
163
|
-
const content = Array.isArray(t.content) ? flattenPrism(t.content, []).map(x => x.codeContent).join('') : String(t.content)
|
|
164
|
-
if (content) out.push({ codeContent: content, highlightType: type })
|
|
165
|
-
}
|
|
166
|
-
return out
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const TYPE_NAMES = ['DEFAULT', 'KEYWORD', 'METHOD', 'STR', 'NUMBER', 'COMMENT']
|
|
170
|
-
export const tokenizeCode = (code, language = 'javascript') => {
|
|
171
|
-
ensurePrism()
|
|
172
|
-
const grammar = Prism.languages[language.toLowerCase()] ?? Prism.languages.javascript
|
|
173
|
-
const raw = flattenPrism(Prism.tokenize(code, grammar))
|
|
174
|
-
const merged = []
|
|
175
|
-
for (const t of raw) { const prev = merged[merged.length - 1]; if (prev && prev.highlightType === t.highlightType) prev.codeContent += t.codeContent; else merged.push({ ...t }) }
|
|
176
|
-
return { codeBlocks: merged, unified_codeBlock: merged.map(t => ({ content: t.codeContent, type: TYPE_NAMES[t.highlightType] ?? 'DEFAULT' })) }
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
export const waitAllPromises = async value => {
|
|
180
|
-
if (value instanceof Promise) return waitAllPromises(await value)
|
|
181
|
-
if (Array.isArray(value)) return Promise.all(value.map(waitAllPromises))
|
|
182
|
-
if (value && typeof value === 'object' && value.constructor === Object) { const keys = Object.keys(value); const vals = await Promise.all(keys.map(k => waitAllPromises(value[k]))); return Object.fromEntries(keys.map((k, i) => [k, vals[i]])) }
|
|
183
|
-
return value
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export const extractIE = (text, extraEntities = []) => {
|
|
187
|
-
const entities = [...extraEntities]
|
|
188
|
-
let out = text
|
|
189
|
-
out = out.replace(/\[\[([^:]+):([^\]]+)\]\]/g, (_, key, url) => { entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAILatexItem', latex_expression: '.', font_height: 83.333, padding: 15, latex_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url, url_fallback: url, width: 400, height: 400, expiration_timestamp_ms: Date.now() + 86400000 } } }); return `{{${key}}}.{{/${key}}}` })
|
|
190
|
-
out = out.replace(/\[([^\]]+)\]\(>([^)]+)\)/g, (_, display, deeplink) => { const key = `dl_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIDeeplinkInlineEntityMetadata', deeplink, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
|
|
191
|
-
out = out.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, (_, display, url) => { const key = `lnk_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIHyperlinkInlineEntityMetadata', url, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
|
|
192
|
-
return { text: out, inline_entities: entities }
|
|
193
|
-
}
|
|
194
|
-
|
|
1
|
+
import { Boom } from '@hapi/boom'
|
|
2
|
+
import { createHash, randomBytes } from 'crypto'
|
|
3
|
+
import { createRequire } from 'module'
|
|
4
|
+
import { proto, fetchProtoBundle } from '../../WAProto/index.js'
|
|
5
|
+
import { DisconnectReason } from '../Types/index.js'
|
|
6
|
+
import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js'
|
|
7
|
+
import { sha256 } from './crypto.js'
|
|
8
|
+
|
|
9
|
+
export const BufferJSON = {
|
|
10
|
+
replacer: (k, value) => {
|
|
11
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
|
|
12
|
+
return value
|
|
13
|
+
},
|
|
14
|
+
reviver: (_, value) => {
|
|
15
|
+
if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') return Buffer.from(value.data, 'base64')
|
|
16
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
17
|
+
const keys = Object.keys(value)
|
|
18
|
+
if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
|
|
19
|
+
const values = Object.values(value)
|
|
20
|
+
if (values.every(v => typeof v === 'number')) return Buffer.from(values)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return value
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
|
|
28
|
+
export const isStringNullOrEmpty = value => value == null || value === ''
|
|
29
|
+
|
|
30
|
+
export const writeRandomPadMax16 = msg => { const pad = randomBytes(1); const padLength = (pad[0] & 0x0f) + 1; return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]) }
|
|
31
|
+
export const unpadRandomMax16 = e => { const t = new Uint8Array(e); if (!t.length) throw new Error('unpadPkcs7 given empty bytes'); const r = t[t.length - 1]; if (r > t.length) throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`); return new Uint8Array(t.buffer, t.byteOffset, t.length - r) }
|
|
32
|
+
|
|
33
|
+
export const generateParticipantHashV2 = participants => { participants.sort(); return '2:' + sha256(Buffer.from(participants.join(''))).toString('base64').slice(0, 6) }
|
|
34
|
+
|
|
35
|
+
export const encodeWAMessage = message => {
|
|
36
|
+
try { return writeRandomPadMax16(proto.Message.encode(message?.$type === proto.Message ? message : proto.Message.fromObject(message)).finish()) }
|
|
37
|
+
catch (error) {
|
|
38
|
+
try { return writeRandomPadMax16(proto.Message.encode(message).finish()) }
|
|
39
|
+
catch (e) { console.warn('Message encoding failed:', error.message, e.message); throw new Error(`Failed to encode message: ${error.message}`) }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const generateRegistrationId = () => Uint16Array.from(randomBytes(2))[0] & 16383
|
|
44
|
+
|
|
45
|
+
export const encodeBigEndian = (e, t = 4) => { let r = e; const a = new Uint8Array(t); for (let i = t - 1; i >= 0; i--) { a[i] = 255 & r; r >>>= 8 }; return a }
|
|
46
|
+
|
|
47
|
+
export const toNumber = t => { if (typeof t === 'bigint') return Number(t); if (typeof t === 'object' && t) return 'toNumber' in t ? t.toNumber() : (t.low ?? 0); return t || 0 }
|
|
48
|
+
export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
|
|
49
|
+
|
|
50
|
+
export const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
51
|
+
let timeout
|
|
52
|
+
return {
|
|
53
|
+
start: (newIntervalMs, newTask) => { task = newTask || task; intervalMs = newIntervalMs || intervalMs; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => task?.(), intervalMs) },
|
|
54
|
+
cancel: () => { if (timeout) clearTimeout(timeout); timeout = undefined },
|
|
55
|
+
setTask: newTask => (task = newTask),
|
|
56
|
+
setInterval: newInterval => (intervalMs = newInterval)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const delay = ms => delayCancellable(ms).delay
|
|
61
|
+
export const delayCancellable = ms => {
|
|
62
|
+
const stack = new Error().stack
|
|
63
|
+
let timeout, reject
|
|
64
|
+
const delay = new Promise((resolve, _reject) => { timeout = setTimeout(resolve, ms); reject = _reject })
|
|
65
|
+
return { delay, cancel: () => { clearTimeout(timeout); reject(new Boom('Cancelled', { statusCode: 500, data: { stack } })) } }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const promiseTimeout = async (ms, promise) => {
|
|
69
|
+
if (!ms) return new Promise(promise)
|
|
70
|
+
const stack = new Error().stack
|
|
71
|
+
const { delay, cancel } = delayCancellable(ms)
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
delay.then(() => reject(new Boom('Timed Out', { statusCode: DisconnectReason.timedOut, data: { stack } }))).catch(reject)
|
|
74
|
+
promise(resolve, reject)
|
|
75
|
+
}).finally(cancel)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const generateMessageIDV2 = userId => {
|
|
79
|
+
const data = Buffer.alloc(8 + 20 + 16)
|
|
80
|
+
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
|
81
|
+
if (userId) { const id = jidDecode(userId); if (id?.user) { data.write(id.user, 8); data.write('@c.us', 8 + id.user.length) } }
|
|
82
|
+
randomBytes(16).copy(data, 28)
|
|
83
|
+
return 'ZERVONEX' + createHash('sha256').update(data).digest().toString('hex').toUpperCase().substring(0, 18)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const generateMessageID = () => 'ZERVONEX' + randomBytes(18).toString('hex').toUpperCase()
|
|
87
|
+
|
|
88
|
+
export const bindWaitForEvent = (ev, event) => async (check, timeoutMs) => {
|
|
89
|
+
let listener, closeListener
|
|
90
|
+
await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
91
|
+
closeListener = ({ connection, lastDisconnect }) => { if (connection === 'close') reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })) }
|
|
92
|
+
ev.on('connection.update', closeListener)
|
|
93
|
+
listener = async update => { if (await check(update)) resolve() }
|
|
94
|
+
ev.on(event, listener)
|
|
95
|
+
}).finally(() => { ev.off(event, listener); ev.off('connection.update', closeListener) })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update')
|
|
99
|
+
|
|
100
|
+
export const fetchLatestWaWebVersion = async () => {
|
|
101
|
+
const { version } = await fetchProtoBundle()
|
|
102
|
+
return { version: [2, 3000, parseInt(version)], isLatest: true }
|
|
103
|
+
}
|
|
104
|
+
export const fetchLatestBaileysVersion = fetchLatestWaWebVersion
|
|
105
|
+
|
|
106
|
+
export const generateMdTagPrefix = () => { const b = randomBytes(4); return `${b.readUInt16BE()}.${b.readUInt16BE(2)}-` }
|
|
107
|
+
|
|
108
|
+
const STATUS_MAP = { sender: proto.WebMessageInfo.Status.SERVER_ACK, played: proto.WebMessageInfo.Status.PLAYED, read: proto.WebMessageInfo.Status.READ, 'read-self': proto.WebMessageInfo.Status.READ }
|
|
109
|
+
export const getStatusFromReceiptType = type => typeof type === 'undefined' ? proto.WebMessageInfo.Status.DELIVERY_ACK : STATUS_MAP[type]
|
|
110
|
+
|
|
111
|
+
const CODE_MAP = { conflict: DisconnectReason.connectionReplaced }
|
|
112
|
+
export const getErrorCodeFromStreamError = node => { const [reasonNode] = getAllBinaryNodeChildren(node); let reason = reasonNode?.tag || 'unknown'; const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession); if (statusCode === DisconnectReason.restartRequired) reason = 'restart required'; return { reason, statusCode } }
|
|
113
|
+
|
|
114
|
+
export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
115
|
+
switch (tag) {
|
|
116
|
+
case 'offer': case 'offer_notice': return 'offer'
|
|
117
|
+
case 'terminate': return attrs.reason === 'timeout' ? 'timeout' : 'terminate'
|
|
118
|
+
case 'reject': return 'reject'
|
|
119
|
+
case 'accept': return 'accept'
|
|
120
|
+
default: return 'ringing'
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
|
|
125
|
+
export const getCodeFromWSError = error => {
|
|
126
|
+
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) { const code = +error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length); if (!Number.isNaN(code) && code >= 400) return code }
|
|
127
|
+
if (error?.code?.startsWith('E') || error?.message?.includes('timed out')) return 408
|
|
128
|
+
return 500
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const isWABusinessPlatform = platform => platform === 'smbi' || platform === 'smba'
|
|
132
|
+
export const trimUndefined = obj => { for (const key in obj) if (typeof obj[key] === 'undefined') delete obj[key]; return obj }
|
|
133
|
+
|
|
134
|
+
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
|
|
135
|
+
export const bytesToCrockford = buffer => {
|
|
136
|
+
let value = 0, bitCount = 0
|
|
137
|
+
const crockford = []
|
|
138
|
+
for (const element of buffer) { value = (value << 8) | (element & 0xff); bitCount += 8; while (bitCount >= 5) { crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31)); bitCount -= 5 } }
|
|
139
|
+
if (bitCount > 0) crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
|
|
140
|
+
return crockford.join('')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export const encodeNewsletterMessage = message => proto.Message.encode(message).finish()
|
|
144
|
+
|
|
145
|
+
const _require = createRequire(import.meta.url)
|
|
146
|
+
const Prism = _require('prismjs')
|
|
147
|
+
const loadPrismLanguages = _require('prismjs/components/index')
|
|
148
|
+
let _prismReady = false
|
|
149
|
+
const ensurePrism = () => { if (_prismReady) return; _prismReady = true; try { loadPrismLanguages() } catch { } }
|
|
150
|
+
|
|
151
|
+
const PRISM_TYPE_MAP = {
|
|
152
|
+
keyword: 1, 'keyword control': 1, builtin: 1, important: 1, bold: 1,
|
|
153
|
+
function: 2, 'function-definition': 2, method: 2, 'method-definition': 2,
|
|
154
|
+
string: 3, 'template-string': 3, 'string interpolation': 3, char: 3, regex: 3,
|
|
155
|
+
number: 4, constant: 4, boolean: 4, unit: 4,
|
|
156
|
+
comment: 5, 'block-comment': 5, prolog: 5, doctype: 5
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const flattenPrism = (tokens, out = []) => {
|
|
160
|
+
for (const t of tokens) {
|
|
161
|
+
if (typeof t === 'string') { if (t) out.push({ codeContent: t, highlightType: 0 }); continue }
|
|
162
|
+
const type = PRISM_TYPE_MAP[t.type] ?? 0
|
|
163
|
+
const content = Array.isArray(t.content) ? flattenPrism(t.content, []).map(x => x.codeContent).join('') : String(t.content)
|
|
164
|
+
if (content) out.push({ codeContent: content, highlightType: type })
|
|
165
|
+
}
|
|
166
|
+
return out
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const TYPE_NAMES = ['DEFAULT', 'KEYWORD', 'METHOD', 'STR', 'NUMBER', 'COMMENT']
|
|
170
|
+
export const tokenizeCode = (code, language = 'javascript') => {
|
|
171
|
+
ensurePrism()
|
|
172
|
+
const grammar = Prism.languages[language.toLowerCase()] ?? Prism.languages.javascript
|
|
173
|
+
const raw = flattenPrism(Prism.tokenize(code, grammar))
|
|
174
|
+
const merged = []
|
|
175
|
+
for (const t of raw) { const prev = merged[merged.length - 1]; if (prev && prev.highlightType === t.highlightType) prev.codeContent += t.codeContent; else merged.push({ ...t }) }
|
|
176
|
+
return { codeBlocks: merged, unified_codeBlock: merged.map(t => ({ content: t.codeContent, type: TYPE_NAMES[t.highlightType] ?? 'DEFAULT' })) }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export const waitAllPromises = async value => {
|
|
180
|
+
if (value instanceof Promise) return waitAllPromises(await value)
|
|
181
|
+
if (Array.isArray(value)) return Promise.all(value.map(waitAllPromises))
|
|
182
|
+
if (value && typeof value === 'object' && value.constructor === Object) { const keys = Object.keys(value); const vals = await Promise.all(keys.map(k => waitAllPromises(value[k]))); return Object.fromEntries(keys.map((k, i) => [k, vals[i]])) }
|
|
183
|
+
return value
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const extractIE = (text, extraEntities = []) => {
|
|
187
|
+
const entities = [...extraEntities]
|
|
188
|
+
let out = text
|
|
189
|
+
out = out.replace(/\[\[([^:]+):([^\]]+)\]\]/g, (_, key, url) => { entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAILatexItem', latex_expression: '.', font_height: 83.333, padding: 15, latex_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url, url_fallback: url, width: 400, height: 400, expiration_timestamp_ms: Date.now() + 86400000 } } }); return `{{${key}}}.{{/${key}}}` })
|
|
190
|
+
out = out.replace(/\[([^\]]+)\]\(>([^)]+)\)/g, (_, display, deeplink) => { const key = `dl_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIDeeplinkInlineEntityMetadata', deeplink, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
|
|
191
|
+
out = out.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, (_, display, url) => { const key = `lnk_${entities.length}`; entities.push({ __typename: 'GenAITextInlineEntity', key, metadata: { __typename: 'GenAIHyperlinkInlineEntityMetadata', url, display_text: display } }); return `{{${key}}}${display}{{/${key}}}` })
|
|
192
|
+
return { text: out, inline_entities: entities }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
195
|
export const generateVerificationMetadata = () => ({ proofs: [{ version: 1, useCase: 1, signature: randomBytes(32), certificateChain: [randomBytes(64)], certificateChainSki: [] }] })
|
package/lib/Utils/history.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import { promisify } from 'util'
|
|
2
|
-
import { inflate } from 'zlib'
|
|
3
|
-
import { proto } from '../../WAProto/index.js'
|
|
4
|
-
import { WAMessageStubType } from '../Types/index.js'
|
|
5
|
-
import { isJidUser } from '../WABinary/index.js'
|
|
6
|
-
import { toNumber } from './generics.js'
|
|
7
|
-
import { normalizeMessageContent } from './messages.js'
|
|
8
|
-
import { downloadContentFromMessage } from './messages-media.js'
|
|
9
|
-
|
|
10
|
-
const inflatePromise = promisify(inflate)
|
|
11
|
-
|
|
12
|
-
export const downloadHistory = async (msg, options) => {
|
|
13
|
-
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
|
14
|
-
const chunks = []
|
|
15
|
-
for await (const chunk of stream) chunks.push(chunk)
|
|
16
|
-
return proto.HistorySync.decode(await inflatePromise(Buffer.concat(chunks)))
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export const processHistoryMessage = item => {
|
|
20
|
-
const messages = [], contacts = [], chats = []
|
|
21
|
-
switch (item.syncType) {
|
|
22
|
-
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
23
|
-
case proto.HistorySync.HistorySyncType.RECENT:
|
|
24
|
-
case proto.HistorySync.HistorySyncType.FULL:
|
|
25
|
-
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
26
|
-
for (const chat of (item.conversations ?? [])) {
|
|
27
|
-
contacts.push({ id: chat.id, name: chat.name || undefined, lid: chat.lidJid || undefined, phoneNumber: chat.pnJid || undefined, jid: isJidUser(chat.id) ? chat.id : undefined })
|
|
28
|
-
const msgs = chat.messages || []
|
|
29
|
-
delete chat.messages; delete chat.archived; delete chat.muteEndTime; delete chat.pinned
|
|
30
|
-
for (const item of msgs) {
|
|
31
|
-
const { message } = item
|
|
32
|
-
messages.push(message)
|
|
33
|
-
if (!chat.messages?.length) chat.messages = [{ message }]
|
|
34
|
-
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
|
35
|
-
if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) && message.messageStubParameters?.[0]) contacts.push({ id: message.key.participant || message.key.remoteJid, verifiedName: message.messageStubParameters[0] })
|
|
36
|
-
}
|
|
37
|
-
if (isJidUser(chat.id) && chat.readOnly && chat.archived) delete chat.readOnly
|
|
38
|
-
chats.push({ ...chat })
|
|
39
|
-
}
|
|
40
|
-
break
|
|
41
|
-
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
42
|
-
for (const c of (item.pushnames ?? [])) contacts.push({ id: c.id, notify: c.pushname })
|
|
43
|
-
for (const c of (item.inlineContacts ?? [])) { if (c.id) contacts.push({ id: c.id, name: c.fullName || c.firstName || undefined, notify: c.pushName || undefined, lid: c.lidJid || undefined, phoneNumber: c.pnJid || undefined }) }
|
|
44
|
-
break
|
|
45
|
-
}
|
|
46
|
-
return { chats, contacts, messages, syncType: item.syncType, progress: item.progress, nctSalt: item.nctSalt || undefined }
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export const downloadAndProcessHistorySyncNotification = async (msg, options) => processHistoryMessage(await downloadHistory(msg, options))
|
|
50
|
-
|
|
1
|
+
import { promisify } from 'util'
|
|
2
|
+
import { inflate } from 'zlib'
|
|
3
|
+
import { proto } from '../../WAProto/index.js'
|
|
4
|
+
import { WAMessageStubType } from '../Types/index.js'
|
|
5
|
+
import { isJidUser } from '../WABinary/index.js'
|
|
6
|
+
import { toNumber } from './generics.js'
|
|
7
|
+
import { normalizeMessageContent } from './messages.js'
|
|
8
|
+
import { downloadContentFromMessage } from './messages-media.js'
|
|
9
|
+
|
|
10
|
+
const inflatePromise = promisify(inflate)
|
|
11
|
+
|
|
12
|
+
export const downloadHistory = async (msg, options) => {
|
|
13
|
+
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
|
14
|
+
const chunks = []
|
|
15
|
+
for await (const chunk of stream) chunks.push(chunk)
|
|
16
|
+
return proto.HistorySync.decode(await inflatePromise(Buffer.concat(chunks)))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const processHistoryMessage = item => {
|
|
20
|
+
const messages = [], contacts = [], chats = []
|
|
21
|
+
switch (item.syncType) {
|
|
22
|
+
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
23
|
+
case proto.HistorySync.HistorySyncType.RECENT:
|
|
24
|
+
case proto.HistorySync.HistorySyncType.FULL:
|
|
25
|
+
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
26
|
+
for (const chat of (item.conversations ?? [])) {
|
|
27
|
+
contacts.push({ id: chat.id, name: chat.name || undefined, lid: chat.lidJid || undefined, phoneNumber: chat.pnJid || undefined, jid: isJidUser(chat.id) ? chat.id : undefined })
|
|
28
|
+
const msgs = chat.messages || []
|
|
29
|
+
delete chat.messages; delete chat.archived; delete chat.muteEndTime; delete chat.pinned
|
|
30
|
+
for (const item of msgs) {
|
|
31
|
+
const { message } = item
|
|
32
|
+
messages.push(message)
|
|
33
|
+
if (!chat.messages?.length) chat.messages = [{ message }]
|
|
34
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
|
35
|
+
if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) && message.messageStubParameters?.[0]) contacts.push({ id: message.key.participant || message.key.remoteJid, verifiedName: message.messageStubParameters[0] })
|
|
36
|
+
}
|
|
37
|
+
if (isJidUser(chat.id) && chat.readOnly && chat.archived) delete chat.readOnly
|
|
38
|
+
chats.push({ ...chat })
|
|
39
|
+
}
|
|
40
|
+
break
|
|
41
|
+
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
42
|
+
for (const c of (item.pushnames ?? [])) contacts.push({ id: c.id, notify: c.pushname })
|
|
43
|
+
for (const c of (item.inlineContacts ?? [])) { if (c.id) contacts.push({ id: c.id, name: c.fullName || c.firstName || undefined, notify: c.pushName || undefined, lid: c.lidJid || undefined, phoneNumber: c.pnJid || undefined }) }
|
|
44
|
+
break
|
|
45
|
+
}
|
|
46
|
+
return { chats, contacts, messages, syncType: item.syncType, progress: item.progress, nctSalt: item.nctSalt || undefined }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const downloadAndProcessHistorySyncNotification = async (msg, options) => processHistoryMessage(await downloadHistory(msg, options))
|
|
50
|
+
|
|
51
51
|
export const getHistoryMsg = message => message ? normalizeMessageContent(message)?.protocolMessage?.historySyncNotification : undefined
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js'
|
|
2
|
-
import { isStringNullOrEmpty } from './generics.js'
|
|
3
|
-
|
|
4
|
-
export async function handleIdentityChange(node, ctx) {
|
|
5
|
-
const from = node.attrs.from
|
|
6
|
-
if (!from) return { action: 'invalid_notification' }
|
|
7
|
-
if (!getBinaryNodeChild(node, 'identity')) return { action: 'no_identity_node' }
|
|
8
|
-
ctx.logger.info({ jid: from }, 'identity changed')
|
|
9
|
-
const decoded = jidDecode(from)
|
|
10
|
-
if (decoded?.device && decoded.device !== 0) { ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device'); return { action: 'skipped_companion_device', device: decoded.device } }
|
|
11
|
-
if (ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)))) { ctx.logger.info({ jid: from }, 'self primary identity changed'); return { action: 'skipped_self_primary' } }
|
|
12
|
-
if (ctx.debounceCache.get(from)) { ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)'); return { action: 'debounced' } }
|
|
13
|
-
ctx.debounceCache.set(from, true)
|
|
14
|
-
if (!(await ctx.validateSession(from)).exists) { ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh'); return { action: 'skipped_no_session' } }
|
|
15
|
-
ctx.logger.debug({ jid: from }, 'old session exists, will refresh session')
|
|
16
|
-
if (!isStringNullOrEmpty(node.attrs.offline)) { ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing'); return { action: 'skipped_offline' } }
|
|
17
|
-
try { await ctx.assertSessions([from], true); return { action: 'session_refreshed' } }
|
|
18
|
-
catch (error) { ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change'); return { action: 'session_refresh_failed', error } }
|
|
1
|
+
import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js'
|
|
2
|
+
import { isStringNullOrEmpty } from './generics.js'
|
|
3
|
+
|
|
4
|
+
export async function handleIdentityChange(node, ctx) {
|
|
5
|
+
const from = node.attrs.from
|
|
6
|
+
if (!from) return { action: 'invalid_notification' }
|
|
7
|
+
if (!getBinaryNodeChild(node, 'identity')) return { action: 'no_identity_node' }
|
|
8
|
+
ctx.logger.info({ jid: from }, 'identity changed')
|
|
9
|
+
const decoded = jidDecode(from)
|
|
10
|
+
if (decoded?.device && decoded.device !== 0) { ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device'); return { action: 'skipped_companion_device', device: decoded.device } }
|
|
11
|
+
if (ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)))) { ctx.logger.info({ jid: from }, 'self primary identity changed'); return { action: 'skipped_self_primary' } }
|
|
12
|
+
if (ctx.debounceCache.get(from)) { ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)'); return { action: 'debounced' } }
|
|
13
|
+
ctx.debounceCache.set(from, true)
|
|
14
|
+
if (!(await ctx.validateSession(from)).exists) { ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh'); return { action: 'skipped_no_session' } }
|
|
15
|
+
ctx.logger.debug({ jid: from }, 'old session exists, will refresh session')
|
|
16
|
+
if (!isStringNullOrEmpty(node.attrs.offline)) { ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing'); return { action: 'skipped_offline' } }
|
|
17
|
+
try { await ctx.assertSessions([from], true); return { action: 'session_refreshed' } }
|
|
18
|
+
catch (error) { ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change'); return { action: 'session_refresh_failed', error } }
|
|
19
19
|
}
|
package/lib/Utils/index.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
export * from './generics.js'
|
|
2
|
-
export * from './decode-wa-message.js'
|
|
3
|
-
export * from './messages.js'
|
|
4
|
-
export * from './messages-media.js'
|
|
5
|
-
export * from './validate-connection.js'
|
|
6
|
-
export * from './crypto.js'
|
|
7
|
-
export * from './signal.js'
|
|
8
|
-
export * from './make-mutex.js'
|
|
9
|
-
export * from './logger.js'
|
|
10
|
-
export * from './noise-handler.js'
|
|
11
|
-
export * from './history.js'
|
|
12
|
-
export * from './chat-utils.js'
|
|
13
|
-
export * from './cstoken.js'
|
|
14
|
-
export * from './lt-hash.js'
|
|
15
|
-
export * from './auth-utils.js'
|
|
16
|
-
export * from './baileys-event-stream.js'
|
|
17
|
-
export * from './use-multi-file-auth-state.js'
|
|
18
|
-
export * from './use-keyv-auth-state.js'
|
|
19
|
-
export * from './link-preview.js'
|
|
20
|
-
export * from './event-buffer.js'
|
|
21
|
-
export * from './process-message.js'
|
|
22
|
-
export * from './message-retry-manager.js'
|
|
23
|
-
export * from './browser-utils.js'
|
|
24
|
-
export * from './identity-change-handler.js'
|
|
25
|
-
export * from './reporting-utils.js'
|
|
26
|
-
export * from './companion-reg-client-utils.js'
|
|
27
|
-
export * from './tc-token-utils.js'
|
|
28
|
-
export * from './meta-ai-msmsg.js'
|
|
29
|
-
export * from './spam-report-utils.js'
|
|
30
|
-
export * from './modern-messages.js'
|
|
31
|
-
export * from './extras.js'
|
|
32
|
-
export * from './native-flow.js'
|
|
33
|
-
export * from './consumer-application.js'
|
|
34
|
-
export * from './bot-capabilities.js'
|
|
35
|
-
export * from './meta-compositing.js'
|
|
36
|
-
export * from './bot-planning-replay.js'
|
|
37
|
-
export * from './message-composer.js'
|
|
38
|
-
export * from './business.js'
|
|
39
|
-
export * from './pre-key-manager.js'
|
|
40
|
-
export * from './sync-action-utils.js'
|
|
1
|
+
export * from './generics.js'
|
|
2
|
+
export * from './decode-wa-message.js'
|
|
3
|
+
export * from './messages.js'
|
|
4
|
+
export * from './messages-media.js'
|
|
5
|
+
export * from './validate-connection.js'
|
|
6
|
+
export * from './crypto.js'
|
|
7
|
+
export * from './signal.js'
|
|
8
|
+
export * from './make-mutex.js'
|
|
9
|
+
export * from './logger.js'
|
|
10
|
+
export * from './noise-handler.js'
|
|
11
|
+
export * from './history.js'
|
|
12
|
+
export * from './chat-utils.js'
|
|
13
|
+
export * from './cstoken.js'
|
|
14
|
+
export * from './lt-hash.js'
|
|
15
|
+
export * from './auth-utils.js'
|
|
16
|
+
export * from './baileys-event-stream.js'
|
|
17
|
+
export * from './use-multi-file-auth-state.js'
|
|
18
|
+
export * from './use-keyv-auth-state.js'
|
|
19
|
+
export * from './link-preview.js'
|
|
20
|
+
export * from './event-buffer.js'
|
|
21
|
+
export * from './process-message.js'
|
|
22
|
+
export * from './message-retry-manager.js'
|
|
23
|
+
export * from './browser-utils.js'
|
|
24
|
+
export * from './identity-change-handler.js'
|
|
25
|
+
export * from './reporting-utils.js'
|
|
26
|
+
export * from './companion-reg-client-utils.js'
|
|
27
|
+
export * from './tc-token-utils.js'
|
|
28
|
+
export * from './meta-ai-msmsg.js'
|
|
29
|
+
export * from './spam-report-utils.js'
|
|
30
|
+
export * from './modern-messages.js'
|
|
31
|
+
export * from './extras.js'
|
|
32
|
+
export * from './native-flow.js'
|
|
33
|
+
export * from './consumer-application.js'
|
|
34
|
+
export * from './bot-capabilities.js'
|
|
35
|
+
export * from './meta-compositing.js'
|
|
36
|
+
export * from './bot-planning-replay.js'
|
|
37
|
+
export * from './message-composer.js'
|
|
38
|
+
export * from './business.js'
|
|
39
|
+
export * from './pre-key-manager.js'
|
|
40
|
+
export * from './sync-action-utils.js'
|