@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/extras.js
CHANGED
|
@@ -1,186 +1,186 @@
|
|
|
1
|
-
import { trimUndefined } from './generics.js'
|
|
2
|
-
import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'crypto'
|
|
3
|
-
import { proto } from '../../WAProto/index.js'
|
|
4
|
-
|
|
5
|
-
export const SCHEDULED_MSG_META_TYPE = 'scheduled_message'
|
|
6
|
-
export const SCHEDULED_MSG_MAX_PER_CHAT = 30
|
|
7
|
-
export const SCHEDULED_MSG_MAX_MEDIA = 1
|
|
8
|
-
export const SCHEDULED_MSG_RESOURCE_LIMIT_NACK_CODE = 419
|
|
9
|
-
export const SCHEDULED_MSG_REVEAL_KEY_BYTES = 32
|
|
10
|
-
export const SCHEDULED_MSG_REVEAL_KEY_IV_BYTES = 12
|
|
11
|
-
export const SCHEDULED_MSG_REVEAL_KEY_RETENTION_DAYS = 30
|
|
12
|
-
export const SCHEDULED_MSG_TAG_BYTES = 16
|
|
13
|
-
export const SCHEDULED_MSG_WINDOW = Object.freeze({ chat: { minSeconds: 600, maxSeconds: 1209600 }, newsletter: { minSeconds: 600, maxSeconds: 2592000 } })
|
|
14
|
-
export const generateRevealKey = () => randomBytes(SCHEDULED_MSG_REVEAL_KEY_BYTES)
|
|
15
|
-
export const generateRevealKeyId = () => randomUUID()
|
|
16
|
-
export const encryptWithRevealKey = (plaintext, revealKey) => {
|
|
17
|
-
const key = Buffer.from(revealKey)
|
|
18
|
-
if (key.length !== SCHEDULED_MSG_REVEAL_KEY_BYTES) throw new TypeError(`reveal key must be ${SCHEDULED_MSG_REVEAL_KEY_BYTES} bytes`)
|
|
19
|
-
const encIv = randomBytes(SCHEDULED_MSG_REVEAL_KEY_IV_BYTES)
|
|
20
|
-
const cipher = createCipheriv('aes-256-gcm', key, encIv)
|
|
21
|
-
const body = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()])
|
|
22
|
-
return { encIv, encPayload: Buffer.concat([body, cipher.getAuthTag()]) }
|
|
23
|
-
}
|
|
24
|
-
export const decryptWithRevealKey = (encPayload, encIv, revealKey) => {
|
|
25
|
-
const key = Buffer.from(revealKey)
|
|
26
|
-
const payload = Buffer.from(encPayload)
|
|
27
|
-
if (payload.length < SCHEDULED_MSG_TAG_BYTES) throw new TypeError('encrypted payload is too short to carry an auth tag')
|
|
28
|
-
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(encIv), { authTagLength: SCHEDULED_MSG_TAG_BYTES })
|
|
29
|
-
decipher.setAuthTag(payload.subarray(payload.length - SCHEDULED_MSG_TAG_BYTES))
|
|
30
|
-
return Buffer.concat([decipher.update(payload.subarray(0, payload.length - SCHEDULED_MSG_TAG_BYTES)), decipher.final()])
|
|
31
|
-
}
|
|
32
|
-
export const buildConditionalRevealMessage = ({ encPayload, encIv, revealKeyId }) => ({ conditionalRevealMessage: { conditionalRevealMessageType: proto.Message.ConditionalRevealMessage.ConditionalRevealMessageType.SCHEDULED_MESSAGE, encPayload: Buffer.from(encPayload), encIv: Buffer.from(encIv), revealKeyId } })
|
|
33
|
-
export const encodeScheduledMessage = (message, revealKey = generateRevealKey()) => {
|
|
34
|
-
const plaintext = proto.Message.encode(proto.Message.fromObject(message)).finish()
|
|
35
|
-
const { encIv, encPayload } = encryptWithRevealKey(plaintext, revealKey)
|
|
36
|
-
const revealKeyId = generateRevealKeyId()
|
|
37
|
-
return { revealKey, revealKeyId, encIv, encPayload, message: buildConditionalRevealMessage({ encPayload, encIv, revealKeyId }) }
|
|
38
|
-
}
|
|
39
|
-
export const decodeScheduledMessage = (conditionalRevealMessage, revealKey) => {
|
|
40
|
-
const inner = conditionalRevealMessage?.conditionalRevealMessage ?? conditionalRevealMessage
|
|
41
|
-
if (!inner?.encPayload || !inner?.encIv) throw new TypeError('conditionalRevealMessage is missing encPayload or encIv')
|
|
42
|
-
return proto.Message.decode(decryptWithRevealKey(inner.encPayload, inner.encIv, revealKey))
|
|
43
|
-
}
|
|
44
|
-
export const buildScheduledMsgMetaNode = ({ kind = 'schedule', scheduledTimestampS, revealKeyId, revealKey }) => {
|
|
45
|
-
if (!revealKeyId) throw new TypeError('revealKeyId is required')
|
|
46
|
-
if (kind === 'schedule' && !revealKey) throw new TypeError('scheduling requires the reveal key')
|
|
47
|
-
const attrs = { type: SCHEDULED_MSG_META_TYPE }
|
|
48
|
-
if (kind === 'schedule') {
|
|
49
|
-
if (!Number.isFinite(Number(scheduledTimestampS))) throw new TypeError('scheduledTimestampS must be a unix timestamp in seconds')
|
|
50
|
-
attrs.st = String(Math.floor(Number(scheduledTimestampS)))
|
|
51
|
-
}
|
|
52
|
-
return { tag: 'meta', attrs, content: [{ tag: 'key', attrs: { rkid: revealKeyId }, content: kind === 'schedule' ? Buffer.from(revealKey) : undefined }] }
|
|
53
|
-
}
|
|
54
|
-
export const buildUnscheduleProtocolMessage = (key) => ({ protocolMessage: { key, type: proto.Message.ProtocolMessage.Type.MESSAGE_UNSCHEDULE } })
|
|
55
|
-
export const isScheduledTimeValid = (scheduledTimestampS, nowSeconds = Math.floor(Date.now() / 1000), window = SCHEDULED_MSG_WINDOW.chat) => {
|
|
56
|
-
const rounded = Math.floor(nowSeconds / 60) * 60
|
|
57
|
-
return scheduledTimestampS - rounded >= window.minSeconds && scheduledTimestampS - nowSeconds <= window.maxSeconds
|
|
58
|
-
}
|
|
59
|
-
export const SplitPaymentStatus = Object.freeze({ PENDING: 0, PAID: 1 })
|
|
60
|
-
export const ReminderFrequency = Object.freeze({ REMINDER_FREQUENCY_UNKNOWN: 0, WEEKLY: 1, BI_WEEKLY: 2, MONTHLY: 3, QUARTERLY: 4 })
|
|
61
|
-
export const ReminderStatus = Object.freeze({ REMINDER_STATUS_UNKNOWN: 0, ACTIVE: 1, CANCELLED_BY_CREATOR: 2, STOPPED_BY_RECEIVER: 3, EXPIRED: 4, PAID: 5 })
|
|
62
|
-
export const MONEY_OFFSET = 1000
|
|
63
|
-
const drop = (object) => { for (const key of Object.keys(object)) { if (object[key] === undefined || object[key] === null) delete object[key] } return object }
|
|
64
|
-
export const money = (amount, currencyCode, offset = MONEY_OFFSET) => {
|
|
65
|
-
const value = Number(amount)
|
|
66
|
-
if (!Number.isFinite(value) || value < 0) throw new TypeError('money needs a non-negative amount')
|
|
67
|
-
if (typeof currencyCode !== 'string' || currencyCode.length !== 3) throw new TypeError('money needs a three letter currency code, like IDR or USD')
|
|
68
|
-
if (!Number.isInteger(offset) || offset <= 0) throw new TypeError('money offset must be a positive integer')
|
|
69
|
-
return { value: Math.round(value * offset), offset, currencyCode: currencyCode.toUpperCase() }
|
|
70
|
-
}
|
|
71
|
-
export const readMoney = (value) => { if (!value?.offset) return undefined; return { amount: Number(value.value) / Number(value.offset), currencyCode: value.currencyCode } }
|
|
72
|
-
export const buildSplitPayment = ({ splitId, total, currency, description, requesterJid, participants = [], createdAt } = {}) => {
|
|
73
|
-
if (!splitId) throw new TypeError('buildSplitPayment needs a splitId')
|
|
74
|
-
if (!participants.length) throw new TypeError('buildSplitPayment needs at least one participant')
|
|
75
|
-
return drop({ splitId: String(splitId), totalAmount: total === undefined ? undefined : money(total, currency), description, requesterJid, participants: participants.map((p, i) => { if (!p?.jid) throw new TypeError(`participant ${i} needs a jid`); return drop({ jid: p.jid, amount: p.amount === undefined ? undefined : money(p.amount, p.currency ?? currency), status: p.status ?? SplitPaymentStatus.PENDING }) }), createdAtMs: createdAt === undefined ? Date.now() : Number(createdAt) })
|
|
76
|
-
}
|
|
77
|
-
export const buildSplitPaymentUpdate = ({ splitId, participantJid } = {}) => { if (!splitId || !participantJid) throw new TypeError('buildSplitPaymentUpdate needs both splitId and participantJid'); return { splitId: String(splitId), participantJid } }
|
|
78
|
-
export const buildPaymentReminder = ({ reminderId, instanceId, description, frequency = ReminderFrequency.MONTHLY, status = ReminderStatus.ACTIVE, amount, currency, payeeVpa, payeeJid, payerJid } = {}) => {
|
|
79
|
-
if (!reminderId) throw new TypeError('buildPaymentReminder needs a reminderId')
|
|
80
|
-
return drop({ reminderId: String(reminderId), instanceId: instanceId === undefined ? undefined : String(instanceId), description, frequency, status, amount: amount === undefined ? undefined : money(amount, currency), payeeVpa, payeeJid, payerJid })
|
|
81
|
-
}
|
|
82
|
-
export const readSplitPayment = (msg) => {
|
|
83
|
-
const split = (msg?.message ?? msg)?.splitPaymentMessage
|
|
84
|
-
if (!split) return null
|
|
85
|
-
return drop({ splitId: split.splitId, total: readMoney(split.totalAmount), description: split.description, requesterJid: split.requesterJid, createdAtMs: split.createdAtMs === undefined ? undefined : Number(split.createdAtMs), participants: (split.participants ?? []).map(p => drop({ jid: p.jid, amount: readMoney(p.amount), status: p.status })) })
|
|
86
|
-
}
|
|
87
|
-
export const readPaymentReminder = (msg) => {
|
|
88
|
-
const reminder = (msg?.message ?? msg)?.paymentReminderMessage
|
|
89
|
-
if (!reminder) return null
|
|
90
|
-
return drop({ reminderId: reminder.reminderId, instanceId: reminder.instanceId, description: reminder.description, frequency: reminder.frequency, status: reminder.status, amount: readMoney(reminder.amount), payeeVpa: reminder.payeeVpa, payeeJid: reminder.payeeJid, payerJid: reminder.payerJid })
|
|
91
|
-
}
|
|
92
|
-
export const StatusLinkType = Object.freeze({ RASTERIZED_LINK_PREVIEW: 1, RASTERIZED_LINK_TRUNCATED: 2, RASTERIZED_LINK_FULL_URL: 3 })
|
|
93
|
-
export const STICKER_DEFAULT_AREA = Object.freeze({ x: 0.25, y: 0.4, width: 0.5, height: 0.2 })
|
|
94
|
-
const fraction = (value, name) => { const n = Number(value); if (!Number.isFinite(n) || n < 0 || n > 1) throw new TypeError(`${name} must be between 0 and 1`); return n }
|
|
95
|
-
export const stickerArea = ({ x, y, width, height } = STICKER_DEFAULT_AREA) => {
|
|
96
|
-
const left = fraction(x, 'x'), top = fraction(y, 'y'), right = fraction(left + Number(width), 'x + width'), bottom = fraction(top + Number(height), 'y + height')
|
|
97
|
-
if (right <= left || bottom <= top) throw new TypeError('a sticker area needs a positive width and height')
|
|
98
|
-
return [{ x: left, y: top }, { x: right, y: top }, { x: right, y: bottom }, { x: left, y: bottom }]
|
|
99
|
-
}
|
|
100
|
-
const annotation = (area, fields) => ({ polygonVertices: Array.isArray(area) ? area : stickerArea(area), ...fields })
|
|
101
|
-
export const locationSticker = ({ latitude, longitude, name, area, skipConfirmation } = {}) => {
|
|
102
|
-
const degreesLatitude = Number(latitude), degreesLongitude = Number(longitude)
|
|
103
|
-
if (!Number.isFinite(degreesLatitude) || !Number.isFinite(degreesLongitude)) throw new TypeError('locationSticker needs a numeric latitude and longitude')
|
|
104
|
-
return annotation(area, { location: { degreesLatitude, degreesLongitude, ...(name ? { name } : {}) }, ...(skipConfirmation === undefined ? {} : { shouldSkipConfirmation: !!skipConfirmation }) })
|
|
105
|
-
}
|
|
106
|
-
export const channelSticker = ({ jid, name, serverMessageId = 0, accessibilityText, area } = {}) => {
|
|
107
|
-
if (typeof jid !== 'string' || !jid.endsWith('@newsletter')) throw new TypeError('channelSticker needs the channel jid ending in @newsletter')
|
|
108
|
-
return annotation(area, { newsletter: { newsletterJid: jid, serverMessageId: Number(serverMessageId), ...(name ? { newsletterName: name } : {}), ...(accessibilityText ? { accessibilityText } : {}) } })
|
|
109
|
-
}
|
|
110
|
-
export const linkSticker = ({ url, title, area, linkType = StatusLinkType.RASTERIZED_LINK_PREVIEW } = {}) => {
|
|
111
|
-
if (typeof url !== 'string' || !url) throw new TypeError('linkSticker needs a url')
|
|
112
|
-
return annotation(area, { tapAction: { tapUrl: url, ...(title ? { title } : {}) }, statusLinkType: linkType })
|
|
113
|
-
}
|
|
114
|
-
export const musicSticker = ({ songId, title, author, mediaId, artworkDirectPath, artworkSha256, artworkEncSha256, artworkMediaKey, artistAttribution, countryBlocklist, isExplicit, startTimeMs = 0, derivedStartTimeMs, durationMs, area } = {}) => {
|
|
115
|
-
if (!songId && !mediaId) throw new TypeError('musicSticker needs at least a songId or a musicContentMediaId')
|
|
116
|
-
const bytes = v => v === undefined ? undefined : Buffer.isBuffer(v) ? v : Buffer.from(v, 'base64')
|
|
117
|
-
const em = { ...(songId ? { songId: String(songId) } : {}), ...(mediaId ? { musicContentMediaId: String(mediaId) } : {}), ...(title ? { title } : {}), ...(author ? { author } : {}), ...(artistAttribution ? { artistAttribution } : {}), ...(artworkDirectPath ? { artworkDirectPath } : {}), ...(isExplicit === undefined ? {} : { isExplicit: !!isExplicit }), musicSongStartTimeInMs: Number(startTimeMs), ...(derivedStartTimeMs === undefined ? {} : { derivedContentStartTimeInMs: Number(derivedStartTimeMs) }), ...(durationMs === undefined ? {} : { overlapDurationInMs: Number(durationMs) }) }
|
|
118
|
-
for (const [k, v] of [['artworkSha256', artworkSha256], ['artworkEncSha256', artworkEncSha256], ['artworkMediaKey', artworkMediaKey], ['countryBlocklist', countryBlocklist]]) { const b = bytes(v); if (b) em[k] = b }
|
|
119
|
-
return annotation(area, { embeddedContent: { embeddedMusic: em } })
|
|
120
|
-
}
|
|
121
|
-
export const messageSticker = ({ stanzaId, message, area } = {}) => {
|
|
122
|
-
if (!message) throw new TypeError('messageSticker needs the message it embeds')
|
|
123
|
-
return annotation(area, { embeddedContent: { embeddedMessage: { ...(stanzaId ? { stanzaId } : {}), message } } })
|
|
124
|
-
}
|
|
125
|
-
const STICKER_ACTIONS = ['location', 'newsletter', 'embeddedAction', 'tapAction']
|
|
126
|
-
export const normalizeStickers = (stickers) => {
|
|
127
|
-
const list = Array.isArray(stickers) ? stickers : [stickers]
|
|
128
|
-
return list.filter(Boolean).map((sticker, i) => {
|
|
129
|
-
const v = sticker.polygonVertices
|
|
130
|
-
if (!Array.isArray(v) || v.length !== 4) throw new TypeError(`sticker ${i} needs four polygonVertices`)
|
|
131
|
-
const actions = STICKER_ACTIONS.filter(n => sticker[n] !== undefined && sticker[n] !== null)
|
|
132
|
-
if (actions.length > 1) throw new TypeError(`sticker ${i} sets ${actions.join(' and ')}, but only one action is allowed per sticker`)
|
|
133
|
-
return proto.InteractiveAnnotation.fromObject(sticker)
|
|
134
|
-
})
|
|
135
|
-
}
|
|
136
|
-
export const readStickers = (message) => {
|
|
137
|
-
const media = message?.imageMessage ?? message?.videoMessage ?? message
|
|
138
|
-
const annotations = media?.interactiveAnnotations
|
|
139
|
-
if (!Array.isArray(annotations) || !annotations.length) return []
|
|
140
|
-
return annotations.map(item => {
|
|
141
|
-
const [topLeft, , bottomRight] = item.polygonVertices ?? []
|
|
142
|
-
const music = item.embeddedContent?.embeddedMusic
|
|
143
|
-
return { kind: item.location ? 'location' : item.newsletter ? 'channel' : item.tapAction ? 'link' : music ? 'music' : item.embeddedContent?.embeddedMessage ? 'message' : 'unknown', area: topLeft && bottomRight ? { x: topLeft.x, y: topLeft.y, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y } : undefined, location: item.location ?? undefined, channel: item.newsletter ?? undefined, link: item.tapAction ? { url: item.tapAction.tapUrl, title: item.tapAction.title, linkType: item.statusLinkType } : undefined, music: music ? { songId: music.songId, title: music.title, author: music.author } : undefined, message: item.embeddedContent?.embeddedMessage ?? undefined, annotation: item }
|
|
144
|
-
})
|
|
145
|
-
}
|
|
146
|
-
export const MusicMessageStyle = Object.freeze({ UNKNOWN: 0, VINYL: 1 })
|
|
147
|
-
export const MUSIC_ALLOWED_HOSTS = Object.freeze(['.whatsapp.net', '.whatsapp.com', '.fbcdn.net', '.facebook.com', '.instagram.com', '.cdninstagram.com'])
|
|
148
|
-
export const isMusicHostAllowed = (value) => { let host; try { host = new URL(String(value)).hostname.toLowerCase() } catch { return false } return MUSIC_ALLOWED_HOSTS.some(s => host.endsWith(s) || host === s.slice(1)) }
|
|
149
|
-
const assertMusicHost = (value, label) => { if (value === undefined) return undefined; if (!isMusicHostAllowed(value)) throw new TypeError(`${label} must be hosted on ${MUSIC_ALLOWED_HOSTS.join(', ')}`); return value }
|
|
150
|
-
const embeddedMusicOf = (options) => musicSticker(options).embeddedContent.embeddedMusic
|
|
151
|
-
export const buildMusicMessage = ({ songUri, artworkUri, style = MusicMessageStyle.VINYL, contextInfo, ...music } = {}) => trimUndefined({ embeddedMusic: embeddedMusicOf(music), songUri: assertMusicHost(songUri, 'songUri'), artworkUri: assertMusicHost(artworkUri, 'artworkUri'), style, contextInfo })
|
|
152
|
-
export const readMusicMessage = (msg) => {
|
|
153
|
-
const music = (msg?.message ?? msg)?.musicMessage
|
|
154
|
-
if (!music) return null
|
|
155
|
-
const em = music.embeddedMusic ?? {}
|
|
156
|
-
return { songId: em.songId, mediaId: em.musicContentMediaId, title: em.title, author: em.author, artistAttribution: em.artistAttribution, isExplicit: em.isExplicit, startTimeMs: em.musicSongStartTimeInMs, durationMs: em.overlapDurationInMs, songUri: music.songUri, artworkUri: music.artworkUri, style: music.style, embeddedMusic: em }
|
|
157
|
-
}
|
|
158
|
-
export function buildAckStanza(node, errorCode, meId) {
|
|
159
|
-
const { tag, attrs } = node
|
|
160
|
-
const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
|
|
161
|
-
if (errorCode) stanza.attrs.error = errorCode.toString()
|
|
162
|
-
if (attrs.participant) stanza.attrs.participant = attrs.participant
|
|
163
|
-
if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
|
|
164
|
-
if (attrs.type) stanza.attrs.type = attrs.type
|
|
165
|
-
if (tag === 'message' && meId) stanza.attrs.from = meId
|
|
166
|
-
return stanza
|
|
167
|
-
}
|
|
168
|
-
export const pickSenderKeyRecipients = (devices, senderKeyMap, { force = false, skip } = {}) => {
|
|
169
|
-
const recipients = []
|
|
170
|
-
for (const device of devices) {
|
|
171
|
-
const deviceJid = device?.jid
|
|
172
|
-
if (!deviceJid || (!force && senderKeyMap[deviceJid]) || (skip && skip(device))) continue
|
|
173
|
-
recipients.push(deviceJid)
|
|
174
|
-
}
|
|
175
|
-
return recipients
|
|
176
|
-
}
|
|
177
|
-
export const deliveredSenderKeyJids = nodes => { const delivered = new Set(); for (const node of nodes || []) { const jid = node?.attrs?.jid; if (jid) delivered.add(jid) } return delivered }
|
|
178
|
-
export const senderKeyResetSummary = (stored, jid) => { const devices = Object.keys(stored?.[jid] || {}); return { jid, cleared: devices.length, devices } }
|
|
179
|
-
export const commitSenderKeyDelivery = (senderKeyMap, recipients, nodes) => {
|
|
180
|
-
const delivered = deliveredSenderKeyJids(nodes), marked = [], skipped = []
|
|
181
|
-
for (const jid of recipients) { if (delivered.has(jid)) { senderKeyMap[jid] = true; marked.push(jid) } else { delete senderKeyMap[jid]; skipped.push(jid) } }
|
|
182
|
-
return { marked, skipped }
|
|
183
|
-
}
|
|
184
|
-
export const GROUP_ADDRESSING_MODES = Object.freeze(['pn', 'lid'])
|
|
185
|
-
export const isUsableGroupMetadata = metadata => { if (!metadata || typeof metadata !== 'object') return false; if (!Array.isArray(metadata.participants)) return false; return GROUP_ADDRESSING_MODES.includes(metadata.addressingMode) }
|
|
186
|
-
export const describeUnusableGroupMetadata = metadata => { if (!metadata || typeof metadata !== 'object') return 'nothing cached'; if (!Array.isArray(metadata.participants)) return 'no participants'; if (metadata.addressingMode === undefined || metadata.addressingMode === null) return 'no addressingMode'; return `addressingMode ${JSON.stringify(metadata.addressingMode)} is not pn or lid` }
|
|
1
|
+
import { trimUndefined } from './generics.js'
|
|
2
|
+
import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'crypto'
|
|
3
|
+
import { proto } from '../../WAProto/index.js'
|
|
4
|
+
|
|
5
|
+
export const SCHEDULED_MSG_META_TYPE = 'scheduled_message'
|
|
6
|
+
export const SCHEDULED_MSG_MAX_PER_CHAT = 30
|
|
7
|
+
export const SCHEDULED_MSG_MAX_MEDIA = 1
|
|
8
|
+
export const SCHEDULED_MSG_RESOURCE_LIMIT_NACK_CODE = 419
|
|
9
|
+
export const SCHEDULED_MSG_REVEAL_KEY_BYTES = 32
|
|
10
|
+
export const SCHEDULED_MSG_REVEAL_KEY_IV_BYTES = 12
|
|
11
|
+
export const SCHEDULED_MSG_REVEAL_KEY_RETENTION_DAYS = 30
|
|
12
|
+
export const SCHEDULED_MSG_TAG_BYTES = 16
|
|
13
|
+
export const SCHEDULED_MSG_WINDOW = Object.freeze({ chat: { minSeconds: 600, maxSeconds: 1209600 }, newsletter: { minSeconds: 600, maxSeconds: 2592000 } })
|
|
14
|
+
export const generateRevealKey = () => randomBytes(SCHEDULED_MSG_REVEAL_KEY_BYTES)
|
|
15
|
+
export const generateRevealKeyId = () => randomUUID()
|
|
16
|
+
export const encryptWithRevealKey = (plaintext, revealKey) => {
|
|
17
|
+
const key = Buffer.from(revealKey)
|
|
18
|
+
if (key.length !== SCHEDULED_MSG_REVEAL_KEY_BYTES) throw new TypeError(`reveal key must be ${SCHEDULED_MSG_REVEAL_KEY_BYTES} bytes`)
|
|
19
|
+
const encIv = randomBytes(SCHEDULED_MSG_REVEAL_KEY_IV_BYTES)
|
|
20
|
+
const cipher = createCipheriv('aes-256-gcm', key, encIv)
|
|
21
|
+
const body = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()])
|
|
22
|
+
return { encIv, encPayload: Buffer.concat([body, cipher.getAuthTag()]) }
|
|
23
|
+
}
|
|
24
|
+
export const decryptWithRevealKey = (encPayload, encIv, revealKey) => {
|
|
25
|
+
const key = Buffer.from(revealKey)
|
|
26
|
+
const payload = Buffer.from(encPayload)
|
|
27
|
+
if (payload.length < SCHEDULED_MSG_TAG_BYTES) throw new TypeError('encrypted payload is too short to carry an auth tag')
|
|
28
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(encIv), { authTagLength: SCHEDULED_MSG_TAG_BYTES })
|
|
29
|
+
decipher.setAuthTag(payload.subarray(payload.length - SCHEDULED_MSG_TAG_BYTES))
|
|
30
|
+
return Buffer.concat([decipher.update(payload.subarray(0, payload.length - SCHEDULED_MSG_TAG_BYTES)), decipher.final()])
|
|
31
|
+
}
|
|
32
|
+
export const buildConditionalRevealMessage = ({ encPayload, encIv, revealKeyId }) => ({ conditionalRevealMessage: { conditionalRevealMessageType: proto.Message.ConditionalRevealMessage.ConditionalRevealMessageType.SCHEDULED_MESSAGE, encPayload: Buffer.from(encPayload), encIv: Buffer.from(encIv), revealKeyId } })
|
|
33
|
+
export const encodeScheduledMessage = (message, revealKey = generateRevealKey()) => {
|
|
34
|
+
const plaintext = proto.Message.encode(proto.Message.fromObject(message)).finish()
|
|
35
|
+
const { encIv, encPayload } = encryptWithRevealKey(plaintext, revealKey)
|
|
36
|
+
const revealKeyId = generateRevealKeyId()
|
|
37
|
+
return { revealKey, revealKeyId, encIv, encPayload, message: buildConditionalRevealMessage({ encPayload, encIv, revealKeyId }) }
|
|
38
|
+
}
|
|
39
|
+
export const decodeScheduledMessage = (conditionalRevealMessage, revealKey) => {
|
|
40
|
+
const inner = conditionalRevealMessage?.conditionalRevealMessage ?? conditionalRevealMessage
|
|
41
|
+
if (!inner?.encPayload || !inner?.encIv) throw new TypeError('conditionalRevealMessage is missing encPayload or encIv')
|
|
42
|
+
return proto.Message.decode(decryptWithRevealKey(inner.encPayload, inner.encIv, revealKey))
|
|
43
|
+
}
|
|
44
|
+
export const buildScheduledMsgMetaNode = ({ kind = 'schedule', scheduledTimestampS, revealKeyId, revealKey }) => {
|
|
45
|
+
if (!revealKeyId) throw new TypeError('revealKeyId is required')
|
|
46
|
+
if (kind === 'schedule' && !revealKey) throw new TypeError('scheduling requires the reveal key')
|
|
47
|
+
const attrs = { type: SCHEDULED_MSG_META_TYPE }
|
|
48
|
+
if (kind === 'schedule') {
|
|
49
|
+
if (!Number.isFinite(Number(scheduledTimestampS))) throw new TypeError('scheduledTimestampS must be a unix timestamp in seconds')
|
|
50
|
+
attrs.st = String(Math.floor(Number(scheduledTimestampS)))
|
|
51
|
+
}
|
|
52
|
+
return { tag: 'meta', attrs, content: [{ tag: 'key', attrs: { rkid: revealKeyId }, content: kind === 'schedule' ? Buffer.from(revealKey) : undefined }] }
|
|
53
|
+
}
|
|
54
|
+
export const buildUnscheduleProtocolMessage = (key) => ({ protocolMessage: { key, type: proto.Message.ProtocolMessage.Type.MESSAGE_UNSCHEDULE } })
|
|
55
|
+
export const isScheduledTimeValid = (scheduledTimestampS, nowSeconds = Math.floor(Date.now() / 1000), window = SCHEDULED_MSG_WINDOW.chat) => {
|
|
56
|
+
const rounded = Math.floor(nowSeconds / 60) * 60
|
|
57
|
+
return scheduledTimestampS - rounded >= window.minSeconds && scheduledTimestampS - nowSeconds <= window.maxSeconds
|
|
58
|
+
}
|
|
59
|
+
export const SplitPaymentStatus = Object.freeze({ PENDING: 0, PAID: 1 })
|
|
60
|
+
export const ReminderFrequency = Object.freeze({ REMINDER_FREQUENCY_UNKNOWN: 0, WEEKLY: 1, BI_WEEKLY: 2, MONTHLY: 3, QUARTERLY: 4 })
|
|
61
|
+
export const ReminderStatus = Object.freeze({ REMINDER_STATUS_UNKNOWN: 0, ACTIVE: 1, CANCELLED_BY_CREATOR: 2, STOPPED_BY_RECEIVER: 3, EXPIRED: 4, PAID: 5 })
|
|
62
|
+
export const MONEY_OFFSET = 1000
|
|
63
|
+
const drop = (object) => { for (const key of Object.keys(object)) { if (object[key] === undefined || object[key] === null) delete object[key] } return object }
|
|
64
|
+
export const money = (amount, currencyCode, offset = MONEY_OFFSET) => {
|
|
65
|
+
const value = Number(amount)
|
|
66
|
+
if (!Number.isFinite(value) || value < 0) throw new TypeError('money needs a non-negative amount')
|
|
67
|
+
if (typeof currencyCode !== 'string' || currencyCode.length !== 3) throw new TypeError('money needs a three letter currency code, like IDR or USD')
|
|
68
|
+
if (!Number.isInteger(offset) || offset <= 0) throw new TypeError('money offset must be a positive integer')
|
|
69
|
+
return { value: Math.round(value * offset), offset, currencyCode: currencyCode.toUpperCase() }
|
|
70
|
+
}
|
|
71
|
+
export const readMoney = (value) => { if (!value?.offset) return undefined; return { amount: Number(value.value) / Number(value.offset), currencyCode: value.currencyCode } }
|
|
72
|
+
export const buildSplitPayment = ({ splitId, total, currency, description, requesterJid, participants = [], createdAt } = {}) => {
|
|
73
|
+
if (!splitId) throw new TypeError('buildSplitPayment needs a splitId')
|
|
74
|
+
if (!participants.length) throw new TypeError('buildSplitPayment needs at least one participant')
|
|
75
|
+
return drop({ splitId: String(splitId), totalAmount: total === undefined ? undefined : money(total, currency), description, requesterJid, participants: participants.map((p, i) => { if (!p?.jid) throw new TypeError(`participant ${i} needs a jid`); return drop({ jid: p.jid, amount: p.amount === undefined ? undefined : money(p.amount, p.currency ?? currency), status: p.status ?? SplitPaymentStatus.PENDING }) }), createdAtMs: createdAt === undefined ? Date.now() : Number(createdAt) })
|
|
76
|
+
}
|
|
77
|
+
export const buildSplitPaymentUpdate = ({ splitId, participantJid } = {}) => { if (!splitId || !participantJid) throw new TypeError('buildSplitPaymentUpdate needs both splitId and participantJid'); return { splitId: String(splitId), participantJid } }
|
|
78
|
+
export const buildPaymentReminder = ({ reminderId, instanceId, description, frequency = ReminderFrequency.MONTHLY, status = ReminderStatus.ACTIVE, amount, currency, payeeVpa, payeeJid, payerJid } = {}) => {
|
|
79
|
+
if (!reminderId) throw new TypeError('buildPaymentReminder needs a reminderId')
|
|
80
|
+
return drop({ reminderId: String(reminderId), instanceId: instanceId === undefined ? undefined : String(instanceId), description, frequency, status, amount: amount === undefined ? undefined : money(amount, currency), payeeVpa, payeeJid, payerJid })
|
|
81
|
+
}
|
|
82
|
+
export const readSplitPayment = (msg) => {
|
|
83
|
+
const split = (msg?.message ?? msg)?.splitPaymentMessage
|
|
84
|
+
if (!split) return null
|
|
85
|
+
return drop({ splitId: split.splitId, total: readMoney(split.totalAmount), description: split.description, requesterJid: split.requesterJid, createdAtMs: split.createdAtMs === undefined ? undefined : Number(split.createdAtMs), participants: (split.participants ?? []).map(p => drop({ jid: p.jid, amount: readMoney(p.amount), status: p.status })) })
|
|
86
|
+
}
|
|
87
|
+
export const readPaymentReminder = (msg) => {
|
|
88
|
+
const reminder = (msg?.message ?? msg)?.paymentReminderMessage
|
|
89
|
+
if (!reminder) return null
|
|
90
|
+
return drop({ reminderId: reminder.reminderId, instanceId: reminder.instanceId, description: reminder.description, frequency: reminder.frequency, status: reminder.status, amount: readMoney(reminder.amount), payeeVpa: reminder.payeeVpa, payeeJid: reminder.payeeJid, payerJid: reminder.payerJid })
|
|
91
|
+
}
|
|
92
|
+
export const StatusLinkType = Object.freeze({ RASTERIZED_LINK_PREVIEW: 1, RASTERIZED_LINK_TRUNCATED: 2, RASTERIZED_LINK_FULL_URL: 3 })
|
|
93
|
+
export const STICKER_DEFAULT_AREA = Object.freeze({ x: 0.25, y: 0.4, width: 0.5, height: 0.2 })
|
|
94
|
+
const fraction = (value, name) => { const n = Number(value); if (!Number.isFinite(n) || n < 0 || n > 1) throw new TypeError(`${name} must be between 0 and 1`); return n }
|
|
95
|
+
export const stickerArea = ({ x, y, width, height } = STICKER_DEFAULT_AREA) => {
|
|
96
|
+
const left = fraction(x, 'x'), top = fraction(y, 'y'), right = fraction(left + Number(width), 'x + width'), bottom = fraction(top + Number(height), 'y + height')
|
|
97
|
+
if (right <= left || bottom <= top) throw new TypeError('a sticker area needs a positive width and height')
|
|
98
|
+
return [{ x: left, y: top }, { x: right, y: top }, { x: right, y: bottom }, { x: left, y: bottom }]
|
|
99
|
+
}
|
|
100
|
+
const annotation = (area, fields) => ({ polygonVertices: Array.isArray(area) ? area : stickerArea(area), ...fields })
|
|
101
|
+
export const locationSticker = ({ latitude, longitude, name, area, skipConfirmation } = {}) => {
|
|
102
|
+
const degreesLatitude = Number(latitude), degreesLongitude = Number(longitude)
|
|
103
|
+
if (!Number.isFinite(degreesLatitude) || !Number.isFinite(degreesLongitude)) throw new TypeError('locationSticker needs a numeric latitude and longitude')
|
|
104
|
+
return annotation(area, { location: { degreesLatitude, degreesLongitude, ...(name ? { name } : {}) }, ...(skipConfirmation === undefined ? {} : { shouldSkipConfirmation: !!skipConfirmation }) })
|
|
105
|
+
}
|
|
106
|
+
export const channelSticker = ({ jid, name, serverMessageId = 0, accessibilityText, area } = {}) => {
|
|
107
|
+
if (typeof jid !== 'string' || !jid.endsWith('@newsletter')) throw new TypeError('channelSticker needs the channel jid ending in @newsletter')
|
|
108
|
+
return annotation(area, { newsletter: { newsletterJid: jid, serverMessageId: Number(serverMessageId), ...(name ? { newsletterName: name } : {}), ...(accessibilityText ? { accessibilityText } : {}) } })
|
|
109
|
+
}
|
|
110
|
+
export const linkSticker = ({ url, title, area, linkType = StatusLinkType.RASTERIZED_LINK_PREVIEW } = {}) => {
|
|
111
|
+
if (typeof url !== 'string' || !url) throw new TypeError('linkSticker needs a url')
|
|
112
|
+
return annotation(area, { tapAction: { tapUrl: url, ...(title ? { title } : {}) }, statusLinkType: linkType })
|
|
113
|
+
}
|
|
114
|
+
export const musicSticker = ({ songId, title, author, mediaId, artworkDirectPath, artworkSha256, artworkEncSha256, artworkMediaKey, artistAttribution, countryBlocklist, isExplicit, startTimeMs = 0, derivedStartTimeMs, durationMs, area } = {}) => {
|
|
115
|
+
if (!songId && !mediaId) throw new TypeError('musicSticker needs at least a songId or a musicContentMediaId')
|
|
116
|
+
const bytes = v => v === undefined ? undefined : Buffer.isBuffer(v) ? v : Buffer.from(v, 'base64')
|
|
117
|
+
const em = { ...(songId ? { songId: String(songId) } : {}), ...(mediaId ? { musicContentMediaId: String(mediaId) } : {}), ...(title ? { title } : {}), ...(author ? { author } : {}), ...(artistAttribution ? { artistAttribution } : {}), ...(artworkDirectPath ? { artworkDirectPath } : {}), ...(isExplicit === undefined ? {} : { isExplicit: !!isExplicit }), musicSongStartTimeInMs: Number(startTimeMs), ...(derivedStartTimeMs === undefined ? {} : { derivedContentStartTimeInMs: Number(derivedStartTimeMs) }), ...(durationMs === undefined ? {} : { overlapDurationInMs: Number(durationMs) }) }
|
|
118
|
+
for (const [k, v] of [['artworkSha256', artworkSha256], ['artworkEncSha256', artworkEncSha256], ['artworkMediaKey', artworkMediaKey], ['countryBlocklist', countryBlocklist]]) { const b = bytes(v); if (b) em[k] = b }
|
|
119
|
+
return annotation(area, { embeddedContent: { embeddedMusic: em } })
|
|
120
|
+
}
|
|
121
|
+
export const messageSticker = ({ stanzaId, message, area } = {}) => {
|
|
122
|
+
if (!message) throw new TypeError('messageSticker needs the message it embeds')
|
|
123
|
+
return annotation(area, { embeddedContent: { embeddedMessage: { ...(stanzaId ? { stanzaId } : {}), message } } })
|
|
124
|
+
}
|
|
125
|
+
const STICKER_ACTIONS = ['location', 'newsletter', 'embeddedAction', 'tapAction']
|
|
126
|
+
export const normalizeStickers = (stickers) => {
|
|
127
|
+
const list = Array.isArray(stickers) ? stickers : [stickers]
|
|
128
|
+
return list.filter(Boolean).map((sticker, i) => {
|
|
129
|
+
const v = sticker.polygonVertices
|
|
130
|
+
if (!Array.isArray(v) || v.length !== 4) throw new TypeError(`sticker ${i} needs four polygonVertices`)
|
|
131
|
+
const actions = STICKER_ACTIONS.filter(n => sticker[n] !== undefined && sticker[n] !== null)
|
|
132
|
+
if (actions.length > 1) throw new TypeError(`sticker ${i} sets ${actions.join(' and ')}, but only one action is allowed per sticker`)
|
|
133
|
+
return proto.InteractiveAnnotation.fromObject(sticker)
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
export const readStickers = (message) => {
|
|
137
|
+
const media = message?.imageMessage ?? message?.videoMessage ?? message
|
|
138
|
+
const annotations = media?.interactiveAnnotations
|
|
139
|
+
if (!Array.isArray(annotations) || !annotations.length) return []
|
|
140
|
+
return annotations.map(item => {
|
|
141
|
+
const [topLeft, , bottomRight] = item.polygonVertices ?? []
|
|
142
|
+
const music = item.embeddedContent?.embeddedMusic
|
|
143
|
+
return { kind: item.location ? 'location' : item.newsletter ? 'channel' : item.tapAction ? 'link' : music ? 'music' : item.embeddedContent?.embeddedMessage ? 'message' : 'unknown', area: topLeft && bottomRight ? { x: topLeft.x, y: topLeft.y, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y } : undefined, location: item.location ?? undefined, channel: item.newsletter ?? undefined, link: item.tapAction ? { url: item.tapAction.tapUrl, title: item.tapAction.title, linkType: item.statusLinkType } : undefined, music: music ? { songId: music.songId, title: music.title, author: music.author } : undefined, message: item.embeddedContent?.embeddedMessage ?? undefined, annotation: item }
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
export const MusicMessageStyle = Object.freeze({ UNKNOWN: 0, VINYL: 1 })
|
|
147
|
+
export const MUSIC_ALLOWED_HOSTS = Object.freeze(['.whatsapp.net', '.whatsapp.com', '.fbcdn.net', '.facebook.com', '.instagram.com', '.cdninstagram.com'])
|
|
148
|
+
export const isMusicHostAllowed = (value) => { let host; try { host = new URL(String(value)).hostname.toLowerCase() } catch { return false } return MUSIC_ALLOWED_HOSTS.some(s => host.endsWith(s) || host === s.slice(1)) }
|
|
149
|
+
const assertMusicHost = (value, label) => { if (value === undefined) return undefined; if (!isMusicHostAllowed(value)) throw new TypeError(`${label} must be hosted on ${MUSIC_ALLOWED_HOSTS.join(', ')}`); return value }
|
|
150
|
+
const embeddedMusicOf = (options) => musicSticker(options).embeddedContent.embeddedMusic
|
|
151
|
+
export const buildMusicMessage = ({ songUri, artworkUri, style = MusicMessageStyle.VINYL, contextInfo, ...music } = {}) => trimUndefined({ embeddedMusic: embeddedMusicOf(music), songUri: assertMusicHost(songUri, 'songUri'), artworkUri: assertMusicHost(artworkUri, 'artworkUri'), style, contextInfo })
|
|
152
|
+
export const readMusicMessage = (msg) => {
|
|
153
|
+
const music = (msg?.message ?? msg)?.musicMessage
|
|
154
|
+
if (!music) return null
|
|
155
|
+
const em = music.embeddedMusic ?? {}
|
|
156
|
+
return { songId: em.songId, mediaId: em.musicContentMediaId, title: em.title, author: em.author, artistAttribution: em.artistAttribution, isExplicit: em.isExplicit, startTimeMs: em.musicSongStartTimeInMs, durationMs: em.overlapDurationInMs, songUri: music.songUri, artworkUri: music.artworkUri, style: music.style, embeddedMusic: em }
|
|
157
|
+
}
|
|
158
|
+
export function buildAckStanza(node, errorCode, meId) {
|
|
159
|
+
const { tag, attrs } = node
|
|
160
|
+
const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
|
|
161
|
+
if (errorCode) stanza.attrs.error = errorCode.toString()
|
|
162
|
+
if (attrs.participant) stanza.attrs.participant = attrs.participant
|
|
163
|
+
if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
|
|
164
|
+
if (attrs.type) stanza.attrs.type = attrs.type
|
|
165
|
+
if (tag === 'message' && meId) stanza.attrs.from = meId
|
|
166
|
+
return stanza
|
|
167
|
+
}
|
|
168
|
+
export const pickSenderKeyRecipients = (devices, senderKeyMap, { force = false, skip } = {}) => {
|
|
169
|
+
const recipients = []
|
|
170
|
+
for (const device of devices) {
|
|
171
|
+
const deviceJid = device?.jid
|
|
172
|
+
if (!deviceJid || (!force && senderKeyMap[deviceJid]) || (skip && skip(device))) continue
|
|
173
|
+
recipients.push(deviceJid)
|
|
174
|
+
}
|
|
175
|
+
return recipients
|
|
176
|
+
}
|
|
177
|
+
export const deliveredSenderKeyJids = nodes => { const delivered = new Set(); for (const node of nodes || []) { const jid = node?.attrs?.jid; if (jid) delivered.add(jid) } return delivered }
|
|
178
|
+
export const senderKeyResetSummary = (stored, jid) => { const devices = Object.keys(stored?.[jid] || {}); return { jid, cleared: devices.length, devices } }
|
|
179
|
+
export const commitSenderKeyDelivery = (senderKeyMap, recipients, nodes) => {
|
|
180
|
+
const delivered = deliveredSenderKeyJids(nodes), marked = [], skipped = []
|
|
181
|
+
for (const jid of recipients) { if (delivered.has(jid)) { senderKeyMap[jid] = true; marked.push(jid) } else { delete senderKeyMap[jid]; skipped.push(jid) } }
|
|
182
|
+
return { marked, skipped }
|
|
183
|
+
}
|
|
184
|
+
export const GROUP_ADDRESSING_MODES = Object.freeze(['pn', 'lid'])
|
|
185
|
+
export const isUsableGroupMetadata = metadata => { if (!metadata || typeof metadata !== 'object') return false; if (!Array.isArray(metadata.participants)) return false; return GROUP_ADDRESSING_MODES.includes(metadata.addressingMode) }
|
|
186
|
+
export const describeUnusableGroupMetadata = metadata => { if (!metadata || typeof metadata !== 'object') return 'nothing cached'; if (!Array.isArray(metadata.participants)) return 'no participants'; if (metadata.addressingMode === undefined || metadata.addressingMode === null) return 'no addressingMode'; return `addressingMode ${JSON.stringify(metadata.addressingMode)} is not pn or lid` }
|