@eduh_dev021/baileys 0.0.0-stage → 1.1.0
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 +23 -0
- package/README.md +1843 -2
- package/WAProto/index.d.ts +22220 -0
- package/WAProto/index.js +5 -0
- package/cjs/WAProto/index.d.ts +22220 -0
- package/cjs/WAProto/index.js +60125 -0
- package/cjs/engine-requirements.js +12 -0
- package/cjs/lib/Addon/cache.js +179 -0
- package/cjs/lib/Addon/crc32.js +41 -0
- package/cjs/lib/Addon/file-type.js +217 -0
- package/cjs/lib/Addon/get-file.js +99 -0
- package/cjs/lib/Addon/http-error.d.ts +18 -0
- package/cjs/lib/Addon/http-error.js +66 -0
- package/cjs/lib/Addon/index.d.ts +96 -0
- package/cjs/lib/Addon/index.js +58 -0
- package/cjs/lib/Addon/keyed-db.d.ts +14 -0
- package/cjs/lib/Addon/keyed-db.js +264 -0
- package/cjs/lib/Addon/link-preview.d.ts +15 -0
- package/cjs/lib/Addon/link-preview.js +104 -0
- package/cjs/lib/Addon/media-info.js +98 -0
- package/cjs/lib/Addon/mutex.js +78 -0
- package/cjs/lib/Addon/qr.js +464 -0
- package/cjs/lib/Addon/queue.js +54 -0
- package/cjs/lib/Addon/waveform.js +130 -0
- package/cjs/lib/Addon/zip.js +136 -0
- package/cjs/lib/Defaults/index.d.ts +184 -0
- package/cjs/lib/Defaults/index.js +292 -0
- package/cjs/lib/Signal/Group/ciphertext-message.d.ts +9 -0
- package/cjs/lib/Signal/Group/ciphertext-message.js +37 -0
- package/cjs/lib/Signal/Group/group-cipher.d.ts +10 -0
- package/cjs/lib/Signal/Group/group-cipher.js +105 -0
- package/cjs/lib/Signal/Group/group-session-builder.d.ts +7 -0
- package/cjs/lib/Signal/Group/group-session-builder.js +65 -0
- package/cjs/lib/Signal/Group/index.d.ts +11 -0
- package/cjs/lib/Signal/Group/index.js +67 -0
- package/cjs/lib/Signal/Group/keyhelper.d.ts +6 -0
- package/cjs/lib/Signal/Group/keyhelper.js +47 -0
- package/cjs/lib/Signal/Group/sender-chain-key.d.ts +13 -0
- package/cjs/lib/Signal/Group/sender-chain-key.js +51 -0
- package/cjs/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
- package/cjs/lib/Signal/Group/sender-key-distribution-message.js +80 -0
- package/cjs/lib/Signal/Group/sender-key-message.d.ts +18 -0
- package/cjs/lib/Signal/Group/sender-key-message.js +87 -0
- package/cjs/lib/Signal/Group/sender-key-name.d.ts +11 -0
- package/cjs/lib/Signal/Group/sender-key-name.js +73 -0
- package/cjs/lib/Signal/Group/sender-key-record.d.ts +12 -0
- package/cjs/lib/Signal/Group/sender-key-record.js +66 -0
- package/cjs/lib/Signal/Group/sender-key-state.d.ts +16 -0
- package/cjs/lib/Signal/Group/sender-key-state.js +106 -0
- package/cjs/lib/Signal/Group/sender-message-key.d.ts +11 -0
- package/cjs/lib/Signal/Group/sender-message-key.js +51 -0
- package/cjs/lib/Signal/libsignal.d.ts +54 -0
- package/cjs/lib/Signal/libsignal.js +421 -0
- package/cjs/lib/Signal/lid-mapping.d.ts +20 -0
- package/cjs/lib/Signal/lid-mapping.js +292 -0
- package/cjs/lib/Socket/Client/index.d.ts +2 -0
- package/cjs/lib/Socket/Client/index.js +23 -0
- package/cjs/lib/Socket/Client/types.d.ts +5 -0
- package/cjs/lib/Socket/Client/types.js +36 -0
- package/cjs/lib/Socket/Client/websocket.d.ts +12 -0
- package/cjs/lib/Socket/Client/websocket.js +143 -0
- package/cjs/lib/Socket/business.d.ts +387 -0
- package/cjs/lib/Socket/business.js +402 -0
- package/cjs/lib/Socket/chats.d.ts +144 -0
- package/cjs/lib/Socket/chats.js +1118 -0
- package/cjs/lib/Socket/communities.d.ts +554 -0
- package/cjs/lib/Socket/communities.js +456 -0
- package/cjs/lib/Socket/groups.d.ts +286 -0
- package/cjs/lib/Socket/groups.js +366 -0
- package/cjs/lib/Socket/index.d.ts +522 -0
- package/cjs/lib/Socket/index.js +32 -0
- package/cjs/lib/Socket/messages-recv.d.ts +326 -0
- package/cjs/lib/Socket/messages-recv.js +1670 -0
- package/cjs/lib/Socket/messages-send.d.ts +321 -0
- package/cjs/lib/Socket/messages-send.js +1252 -0
- package/cjs/lib/Socket/mex.d.ts +1 -0
- package/cjs/lib/Socket/mex.js +65 -0
- package/cjs/lib/Socket/newsletter.d.ts +283 -0
- package/cjs/lib/Socket/newsletter.js +243 -0
- package/cjs/lib/Socket/socket.d.ts +61 -0
- package/cjs/lib/Socket/socket.js +908 -0
- package/cjs/lib/Store/index.d.ts +3 -0
- package/cjs/lib/Store/index.js +25 -0
- package/cjs/lib/Store/make-in-memory-store.d.ts +63 -0
- package/cjs/lib/Store/make-in-memory-store.js +431 -0
- package/cjs/lib/Store/make-ordered-dictionary.d.ts +12 -0
- package/cjs/lib/Store/make-ordered-dictionary.js +101 -0
- package/cjs/lib/Store/object-repository.d.ts +10 -0
- package/cjs/lib/Store/object-repository.js +49 -0
- package/cjs/lib/Transport/crypto.d.ts +6 -0
- package/cjs/lib/Transport/crypto.js +107 -0
- package/cjs/lib/Transport/curve.d.ts +8 -0
- package/cjs/lib/Transport/curve.js +94 -0
- package/cjs/lib/Transport/index.d.ts +16 -0
- package/cjs/lib/Transport/index.js +67 -0
- package/cjs/lib/Transport/internals.d.ts +57 -0
- package/cjs/lib/Transport/internals.js +203 -0
- package/cjs/lib/Transport/session-builder.d.ts +40 -0
- package/cjs/lib/Transport/session-builder.js +169 -0
- package/cjs/lib/Transport/session-cipher.d.ts +26 -0
- package/cjs/lib/Transport/session-cipher.js +328 -0
- package/cjs/lib/Transport/session-record.d.ts +55 -0
- package/cjs/lib/Transport/session-record.js +289 -0
- package/cjs/lib/Types/Auth.d.ts +1 -0
- package/cjs/lib/Types/Auth.js +15 -0
- package/cjs/lib/Types/Bussines.d.ts +1 -0
- package/cjs/lib/Types/Bussines.js +15 -0
- package/cjs/lib/Types/Call.d.ts +1 -0
- package/cjs/lib/Types/Call.js +15 -0
- package/cjs/lib/Types/Chat.d.ts +1 -0
- package/cjs/lib/Types/Chat.js +33 -0
- package/cjs/lib/Types/Contact.d.ts +1 -0
- package/cjs/lib/Types/Contact.js +15 -0
- package/cjs/lib/Types/Events.d.ts +1 -0
- package/cjs/lib/Types/Events.js +1 -0
- package/cjs/lib/Types/GroupMetadata.d.ts +1 -0
- package/cjs/lib/Types/GroupMetadata.js +15 -0
- package/cjs/lib/Types/Label.d.ts +2 -0
- package/cjs/lib/Types/Label.js +49 -0
- package/cjs/lib/Types/LabelAssociation.d.ts +2 -0
- package/cjs/lib/Types/LabelAssociation.js +31 -0
- package/cjs/lib/Types/Message.d.ts +11 -0
- package/cjs/lib/Types/Message.js +58 -0
- package/cjs/lib/Types/Mex.d.ts +2 -0
- package/cjs/lib/Types/Mex.js +66 -0
- package/cjs/lib/Types/Product.d.ts +1 -0
- package/cjs/lib/Types/Product.js +15 -0
- package/cjs/lib/Types/RichType.d.ts +2 -0
- package/cjs/lib/Types/RichType.js +50 -0
- package/cjs/lib/Types/Signal.d.ts +1 -0
- package/cjs/lib/Types/Signal.js +1 -0
- package/cjs/lib/Types/Socket.d.ts +1 -0
- package/cjs/lib/Types/Socket.js +1 -0
- package/cjs/lib/Types/State.d.ts +5 -0
- package/cjs/lib/Types/State.js +83 -0
- package/cjs/lib/Types/USync.d.ts +1 -0
- package/cjs/lib/Types/USync.js +1 -0
- package/cjs/lib/Types/index.d.ts +13 -0
- package/cjs/lib/Types/index.js +64 -0
- package/cjs/lib/Utils/auth-utils.d.ts +58 -0
- package/cjs/lib/Utils/auth-utils.js +275 -0
- package/cjs/lib/Utils/browser-utils.d.ts +9 -0
- package/cjs/lib/Utils/browser-utils.js +56 -0
- package/cjs/lib/Utils/business.d.ts +49 -0
- package/cjs/lib/Utils/business.js +259 -0
- package/cjs/lib/Utils/chat-utils.d.ts +408 -0
- package/cjs/lib/Utils/chat-utils.js +821 -0
- package/cjs/lib/Utils/companion-reg-client-utils.d.ts +4 -0
- package/cjs/lib/Utils/companion-reg-client-utils.js +71 -0
- package/cjs/lib/Utils/crypto.d.ts +39 -0
- package/cjs/lib/Utils/crypto.js +155 -0
- package/cjs/lib/Utils/decode-wa-message.d.ts +83 -0
- package/cjs/lib/Utils/decode-wa-message.js +316 -0
- package/cjs/lib/Utils/event-buffer.d.ts +12 -0
- package/cjs/lib/Utils/event-buffer.js +605 -0
- package/cjs/lib/Utils/generics.d.ts +63 -0
- package/cjs/lib/Utils/generics.js +440 -0
- package/cjs/lib/Utils/history.d.ts +75 -0
- package/cjs/lib/Utils/history.js +153 -0
- package/cjs/lib/Utils/identity-change-handler.d.ts +13 -0
- package/cjs/lib/Utils/identity-change-handler.js +73 -0
- package/cjs/lib/Utils/index.d.ts +24 -0
- package/cjs/lib/Utils/index.js +67 -0
- package/cjs/lib/Utils/link-preview.d.ts +13 -0
- package/cjs/lib/Utils/link-preview.js +87 -0
- package/cjs/lib/Utils/logger.d.ts +12 -0
- package/cjs/lib/Utils/logger.js +40 -0
- package/cjs/lib/Utils/lt-hash.d.ts +6 -0
- package/cjs/lib/Utils/lt-hash.js +28 -0
- package/cjs/lib/Utils/make-mutex.d.ts +6 -0
- package/cjs/lib/Utils/make-mutex.js +58 -0
- package/cjs/lib/Utils/message-retry-manager.d.ts +79 -0
- package/cjs/lib/Utils/message-retry-manager.js +274 -0
- package/cjs/lib/Utils/messages-media.d.ts +134 -0
- package/cjs/lib/Utils/messages-media.js +799 -0
- package/cjs/lib/Utils/messages.d.ts +47 -0
- package/cjs/lib/Utils/messages.js +1667 -0
- package/cjs/lib/Utils/noise-handler.d.ts +20 -0
- package/cjs/lib/Utils/noise-handler.js +223 -0
- package/cjs/lib/Utils/offline-node-processor.d.ts +10 -0
- package/cjs/lib/Utils/offline-node-processor.js +60 -0
- package/cjs/lib/Utils/pre-key-manager.d.ts +25 -0
- package/cjs/lib/Utils/pre-key-manager.js +116 -0
- package/cjs/lib/Utils/process-message.d.ts +83 -0
- package/cjs/lib/Utils/process-message.js +607 -0
- package/cjs/lib/Utils/reporting-utils.d.ts +12 -0
- package/cjs/lib/Utils/reporting-utils.js +282 -0
- package/cjs/lib/Utils/rich-message-utils.d.ts +48 -0
- package/cjs/lib/Utils/rich-message-utils.js +381 -0
- package/cjs/lib/Utils/signal.d.ts +82 -0
- package/cjs/lib/Utils/signal.js +232 -0
- package/cjs/lib/Utils/stanza-ack.d.ts +16 -0
- package/cjs/lib/Utils/stanza-ack.js +53 -0
- package/cjs/lib/Utils/sync-action-utils.d.ts +2 -0
- package/cjs/lib/Utils/sync-action-utils.js +68 -0
- package/cjs/lib/Utils/tc-token-utils.d.ts +29 -0
- package/cjs/lib/Utils/tc-token-utils.js +182 -0
- package/cjs/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
- package/cjs/lib/Utils/use-multi-file-auth-state.js +135 -0
- package/cjs/lib/Utils/use-single-file-auth-state.d.ts +11 -0
- package/cjs/lib/Utils/use-single-file-auth-state.js +115 -0
- package/cjs/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
- package/cjs/lib/Utils/use-sqlite-auth-state.js +140 -0
- package/cjs/lib/Utils/validate-connection.d.ts +44 -0
- package/cjs/lib/Utils/validate-connection.js +229 -0
- package/cjs/lib/WABinary/constants.d.ts +61 -0
- package/cjs/lib/WABinary/constants.js +1992 -0
- package/cjs/lib/WABinary/decode.d.ts +9 -0
- package/cjs/lib/WABinary/decode.js +292 -0
- package/cjs/lib/WABinary/encode.d.ts +2 -0
- package/cjs/lib/WABinary/encode.js +240 -0
- package/cjs/lib/WABinary/generic-utils.d.ts +79 -0
- package/cjs/lib/WABinary/generic-utils.js +252 -0
- package/cjs/lib/WABinary/index.d.ts +5 -0
- package/cjs/lib/WABinary/index.js +29 -0
- package/cjs/lib/WABinary/jid-utils.d.ts +28 -0
- package/cjs/lib/WABinary/jid-utils.js +151 -0
- package/cjs/lib/WABinary/types.d.ts +1 -0
- package/cjs/lib/WABinary/types.js +23 -0
- package/cjs/lib/WACrypto/appstate-keys.js +39 -0
- package/cjs/lib/WACrypto/curves/constants.js +37 -0
- package/cjs/lib/WACrypto/hkdf.js +38 -0
- package/cjs/lib/WACrypto/index.js +51 -0
- package/cjs/lib/WACrypto/lthash.js +59 -0
- package/cjs/lib/WACrypto/math/constants.js +53 -0
- package/cjs/lib/WACrypto/math/edwards.js +206 -0
- package/cjs/lib/WACrypto/math/fe.js +449 -0
- package/cjs/lib/WACrypto/math/le.js +44 -0
- package/cjs/lib/WACrypto/math/mod.js +36 -0
- package/cjs/lib/WACrypto/util/bytes.js +348 -0
- package/cjs/lib/WACrypto/x25519.js +157 -0
- package/cjs/lib/WACrypto/xeddsa.js +134 -0
- package/cjs/lib/WAM/BinaryInfo.d.ts +7 -0
- package/cjs/lib/WAM/BinaryInfo.js +35 -0
- package/cjs/lib/WAM/constants.d.ts +34926 -0
- package/cjs/lib/WAM/constants.js +22890 -0
- package/cjs/lib/WAM/encode.d.ts +1 -0
- package/cjs/lib/WAM/encode.js +162 -0
- package/cjs/lib/WAM/index.d.ts +3 -0
- package/cjs/lib/WAM/index.js +25 -0
- package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
- package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +77 -0
- package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +76 -0
- package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +52 -0
- package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +61 -0
- package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
- package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +50 -0
- package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
- package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
- package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
- package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +53 -0
- package/cjs/lib/WAUSync/Protocols/index.d.ts +5 -0
- package/cjs/lib/WAUSync/Protocols/index.js +29 -0
- package/cjs/lib/WAUSync/USyncQuery.d.ts +20 -0
- package/cjs/lib/WAUSync/USyncQuery.js +113 -0
- package/cjs/lib/WAUSync/USyncUser.d.ts +16 -0
- package/cjs/lib/WAUSync/USyncUser.js +56 -0
- package/cjs/lib/WAUSync/index.d.ts +3 -0
- package/cjs/lib/WAUSync/index.js +25 -0
- package/cjs/lib/index.d.ts +11 -0
- package/cjs/lib/index.js +56 -0
- package/cjs/package.json +3 -0
- package/engine-requirements.js +12 -0
- package/lib/Addon/cache.js +201 -0
- package/lib/Addon/crc32.js +21 -0
- package/lib/Addon/file-type.js +198 -0
- package/lib/Addon/get-file.js +98 -0
- package/lib/Addon/http-error.d.ts +18 -0
- package/lib/Addon/http-error.js +40 -0
- package/lib/Addon/index.d.ts +96 -0
- package/lib/Addon/index.js +26 -0
- package/lib/Addon/keyed-db.d.ts +14 -0
- package/lib/Addon/keyed-db.js +241 -0
- package/lib/Addon/link-preview.d.ts +15 -0
- package/lib/Addon/link-preview.js +79 -0
- package/lib/Addon/media-info.js +96 -0
- package/lib/Addon/mutex.js +76 -0
- package/lib/Addon/qr.js +531 -0
- package/lib/Addon/queue.js +44 -0
- package/lib/Addon/waveform.js +135 -0
- package/lib/Addon/zip.js +144 -0
- package/lib/Defaults/index.d.ts +184 -0
- package/lib/Defaults/index.js +181 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
- package/lib/Signal/Group/ciphertext-message.js +11 -0
- package/lib/Signal/Group/group-cipher.d.ts +10 -0
- package/lib/Signal/Group/group-cipher.js +81 -0
- package/lib/Signal/Group/group-session-builder.d.ts +7 -0
- package/lib/Signal/Group/group-session-builder.js +29 -0
- package/lib/Signal/Group/index.d.ts +11 -0
- package/lib/Signal/Group/index.js +11 -0
- package/lib/Signal/Group/keyhelper.d.ts +6 -0
- package/lib/Signal/Group/keyhelper.js +17 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
- package/lib/Signal/Group/sender-chain-key.js +25 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
- package/lib/Signal/Group/sender-key-message.d.ts +18 -0
- package/lib/Signal/Group/sender-key-message.js +65 -0
- package/lib/Signal/Group/sender-key-name.d.ts +11 -0
- package/lib/Signal/Group/sender-key-name.js +47 -0
- package/lib/Signal/Group/sender-key-record.d.ts +12 -0
- package/lib/Signal/Group/sender-key-record.js +40 -0
- package/lib/Signal/Group/sender-key-state.d.ts +16 -0
- package/lib/Signal/Group/sender-key-state.js +83 -0
- package/lib/Signal/Group/sender-message-key.d.ts +11 -0
- package/lib/Signal/Group/sender-message-key.js +25 -0
- package/lib/Signal/libsignal.d.ts +54 -0
- package/lib/Signal/libsignal.js +426 -0
- package/lib/Signal/lid-mapping.d.ts +20 -0
- package/lib/Signal/lid-mapping.js +274 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +2 -0
- package/lib/Socket/Client/types.d.ts +5 -0
- package/lib/Socket/Client/types.js +10 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +119 -0
- package/lib/Socket/business.d.ts +387 -0
- package/lib/Socket/business.js +379 -0
- package/lib/Socket/chats.d.ts +144 -0
- package/lib/Socket/chats.js +1216 -0
- package/lib/Socket/communities.d.ts +554 -0
- package/lib/Socket/communities.js +431 -0
- package/lib/Socket/groups.d.ts +286 -0
- package/lib/Socket/groups.js +347 -0
- package/lib/Socket/index.d.ts +522 -0
- package/lib/Socket/index.js +11 -0
- package/lib/Socket/messages-recv.d.ts +326 -0
- package/lib/Socket/messages-recv.js +1822 -0
- package/lib/Socket/messages-send.d.ts +321 -0
- package/lib/Socket/messages-send.js +1378 -0
- package/lib/Socket/mex.d.ts +1 -0
- package/lib/Socket/mex.js +41 -0
- package/lib/Socket/newsletter.d.ts +283 -0
- package/lib/Socket/newsletter.js +225 -0
- package/lib/Socket/socket.d.ts +61 -0
- package/lib/Socket/socket.js +992 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +3 -0
- package/lib/Store/make-in-memory-store.d.ts +63 -0
- package/lib/Store/make-in-memory-store.js +419 -0
- package/lib/Store/make-ordered-dictionary.d.ts +12 -0
- package/lib/Store/make-ordered-dictionary.js +78 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +23 -0
- package/lib/Transport/crypto.d.ts +6 -0
- package/lib/Transport/crypto.js +61 -0
- package/lib/Transport/curve.d.ts +8 -0
- package/lib/Transport/curve.js +66 -0
- package/lib/Transport/index.d.ts +16 -0
- package/lib/Transport/index.js +9 -0
- package/lib/Transport/internals.d.ts +57 -0
- package/lib/Transport/internals.js +155 -0
- package/lib/Transport/session-builder.d.ts +40 -0
- package/lib/Transport/session-builder.js +143 -0
- package/lib/Transport/session-cipher.d.ts +26 -0
- package/lib/Transport/session-cipher.js +301 -0
- package/lib/Transport/session-record.d.ts +55 -0
- package/lib/Transport/session-record.js +272 -0
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Auth.js +1 -0
- package/lib/Types/Bussines.d.ts +1 -0
- package/lib/Types/Bussines.js +1 -0
- package/lib/Types/Call.d.ts +1 -0
- package/lib/Types/Call.js +1 -0
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.js +7 -0
- package/lib/Types/Contact.d.ts +1 -0
- package/lib/Types/Contact.js +1 -0
- package/lib/Types/Events.d.ts +1 -0
- package/lib/Types/Events.js +1 -0
- package/lib/Types/GroupMetadata.d.ts +1 -0
- package/lib/Types/GroupMetadata.js +1 -0
- package/lib/Types/Label.d.ts +2 -0
- package/lib/Types/Label.js +24 -0
- package/lib/Types/LabelAssociation.d.ts +2 -0
- package/lib/Types/LabelAssociation.js +6 -0
- package/lib/Types/Message.d.ts +11 -0
- package/lib/Types/Message.js +17 -0
- package/lib/Types/Mex.d.ts +2 -0
- package/lib/Types/Mex.js +38 -0
- package/lib/Types/Product.d.ts +1 -0
- package/lib/Types/Product.js +1 -0
- package/lib/Types/RichType.d.ts +2 -0
- package/lib/Types/RichType.js +22 -0
- package/lib/Types/Signal.d.ts +1 -0
- package/lib/Types/Signal.js +1 -0
- package/lib/Types/Socket.d.ts +1 -0
- package/lib/Types/Socket.js +1 -0
- package/lib/Types/State.d.ts +5 -0
- package/lib/Types/State.js +54 -0
- package/lib/Types/USync.d.ts +1 -0
- package/lib/Types/USync.js +1 -0
- package/lib/Types/index.d.ts +13 -0
- package/lib/Types/index.js +25 -0
- package/lib/Utils/auth-utils.d.ts +58 -0
- package/lib/Utils/auth-utils.js +316 -0
- package/lib/Utils/browser-utils.d.ts +9 -0
- package/lib/Utils/browser-utils.js +28 -0
- package/lib/Utils/business.d.ts +49 -0
- package/lib/Utils/business.js +230 -0
- package/lib/Utils/chat-utils.d.ts +408 -0
- package/lib/Utils/chat-utils.js +871 -0
- package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
- package/lib/Utils/companion-reg-client-utils.js +39 -0
- package/lib/Utils/crypto.d.ts +39 -0
- package/lib/Utils/crypto.js +117 -0
- package/lib/Utils/decode-wa-message.d.ts +83 -0
- package/lib/Utils/decode-wa-message.js +316 -0
- package/lib/Utils/event-buffer.d.ts +12 -0
- package/lib/Utils/event-buffer.js +621 -0
- package/lib/Utils/generics.d.ts +63 -0
- package/lib/Utils/generics.js +394 -0
- package/lib/Utils/history.d.ts +75 -0
- package/lib/Utils/history.js +133 -0
- package/lib/Utils/identity-change-handler.d.ts +13 -0
- package/lib/Utils/identity-change-handler.js +48 -0
- package/lib/Utils/index.d.ts +24 -0
- package/lib/Utils/index.js +24 -0
- package/lib/Utils/link-preview.d.ts +13 -0
- package/lib/Utils/link-preview.js +73 -0
- package/lib/Utils/logger.d.ts +12 -0
- package/lib/Utils/logger.js +12 -0
- package/lib/Utils/lt-hash.d.ts +6 -0
- package/lib/Utils/lt-hash.js +7 -0
- package/lib/Utils/make-mutex.d.ts +6 -0
- package/lib/Utils/make-mutex.js +32 -0
- package/lib/Utils/message-retry-manager.d.ts +79 -0
- package/lib/Utils/message-retry-manager.js +259 -0
- package/lib/Utils/messages-media.d.ts +134 -0
- package/lib/Utils/messages-media.js +802 -0
- package/lib/Utils/messages.d.ts +47 -0
- package/lib/Utils/messages.js +1907 -0
- package/lib/Utils/noise-handler.d.ts +20 -0
- package/lib/Utils/noise-handler.js +200 -0
- package/lib/Utils/offline-node-processor.d.ts +10 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/pre-key-manager.d.ts +25 -0
- package/lib/Utils/pre-key-manager.js +105 -0
- package/lib/Utils/process-message.d.ts +83 -0
- package/lib/Utils/process-message.js +748 -0
- package/lib/Utils/reporting-utils.d.ts +12 -0
- package/lib/Utils/reporting-utils.js +257 -0
- package/lib/Utils/rich-message-utils.d.ts +48 -0
- package/lib/Utils/rich-message-utils.js +366 -0
- package/lib/Utils/signal.d.ts +82 -0
- package/lib/Utils/signal.js +200 -0
- package/lib/Utils/stanza-ack.d.ts +16 -0
- package/lib/Utils/stanza-ack.js +37 -0
- package/lib/Utils/sync-action-utils.d.ts +2 -0
- package/lib/Utils/sync-action-utils.js +48 -0
- package/lib/Utils/tc-token-utils.d.ts +29 -0
- package/lib/Utils/tc-token-utils.js +163 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
- package/lib/Utils/use-multi-file-auth-state.js +116 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
- package/lib/Utils/use-single-file-auth-state.js +94 -0
- package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
- package/lib/Utils/use-sqlite-auth-state.js +109 -0
- package/lib/Utils/validate-connection.d.ts +44 -0
- package/lib/Utils/validate-connection.js +210 -0
- package/lib/WABinary/constants.d.ts +61 -0
- package/lib/WABinary/constants.js +1466 -0
- package/lib/WABinary/decode.d.ts +9 -0
- package/lib/WABinary/decode.js +261 -0
- package/lib/WABinary/encode.d.ts +2 -0
- package/lib/WABinary/encode.js +219 -0
- package/lib/WABinary/generic-utils.d.ts +79 -0
- package/lib/WABinary/generic-utils.js +226 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +5 -0
- package/lib/WABinary/jid-utils.d.ts +28 -0
- package/lib/WABinary/jid-utils.js +95 -0
- package/lib/WABinary/types.d.ts +1 -0
- package/lib/WABinary/types.js +1 -0
- package/lib/WACrypto/appstate-keys.js +26 -0
- package/lib/WACrypto/curves/constants.js +12 -0
- package/lib/WACrypto/hkdf.js +27 -0
- package/lib/WACrypto/index.js +20 -0
- package/lib/WACrypto/lthash.js +54 -0
- package/lib/WACrypto/math/constants.js +24 -0
- package/lib/WACrypto/math/edwards.js +194 -0
- package/lib/WACrypto/math/fe.js +698 -0
- package/lib/WACrypto/math/le.js +23 -0
- package/lib/WACrypto/math/mod.js +15 -0
- package/lib/WACrypto/util/bytes.js +339 -0
- package/lib/WACrypto/x25519.js +145 -0
- package/lib/WACrypto/xeddsa.js +92 -0
- package/lib/WAM/BinaryInfo.d.ts +7 -0
- package/lib/WAM/BinaryInfo.js +9 -0
- package/lib/WAM/constants.d.ts +34926 -0
- package/lib/WAM/constants.js +22852 -0
- package/lib/WAM/encode.d.ts +1 -0
- package/lib/WAM/encode.js +149 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +3 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
- package/lib/WAUSync/Protocols/index.d.ts +5 -0
- package/lib/WAUSync/Protocols/index.js +5 -0
- package/lib/WAUSync/USyncQuery.d.ts +20 -0
- package/lib/WAUSync/USyncQuery.js +97 -0
- package/lib/WAUSync/USyncUser.d.ts +16 -0
- package/lib/WAUSync/USyncUser.js +30 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +3 -0
- package/lib/index.d.ts +11 -0
- package/lib/index.js +11 -0
- package/package.json +74 -5
- package/tests/addon-test.mjs +162 -0
- package/tests/differential-test.mjs +90 -0
|
@@ -0,0 +1,1907 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
import { HttpError, createZip, detectFileType } from '../Addon/index.js';
|
|
5
|
+
import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
6
|
+
import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
|
|
7
|
+
import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
|
|
8
|
+
import { sha256 } from './crypto.js';
|
|
9
|
+
import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
|
|
10
|
+
import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioData, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
|
|
11
|
+
import { prepareRichResponseMessage } from './rich-message-utils.js';
|
|
12
|
+
import { shouldIncludeReportingToken } from './reporting-utils.js';
|
|
13
|
+
const MIMETYPE_MAP = {
|
|
14
|
+
image: 'image/jpeg',
|
|
15
|
+
video: 'video/mp4',
|
|
16
|
+
document: 'application/pdf',
|
|
17
|
+
audio: 'audio/ogg; codecs=opus',
|
|
18
|
+
sticker: 'image/webp',
|
|
19
|
+
'product-catalog-image': 'image/jpeg'
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Uses a regex to test whether the string contains a URL, and returns the URL if it does.
|
|
23
|
+
* @param text eg. hello https://google.com
|
|
24
|
+
* @returns the URL, eg. https://google.com
|
|
25
|
+
*/
|
|
26
|
+
export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
|
|
27
|
+
export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
|
|
28
|
+
const url = extractUrlFromText(text);
|
|
29
|
+
if (!!getUrlInfo && url) {
|
|
30
|
+
try {
|
|
31
|
+
const urlInfo = await getUrlInfo(url);
|
|
32
|
+
return urlInfo;
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
// ignore if fails
|
|
36
|
+
logger?.warn({ trace: error.stack }, 'url generation failed');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const ensureMessageProto = (m) => {
|
|
41
|
+
if (m instanceof WAProto.Message)
|
|
42
|
+
return m;
|
|
43
|
+
return WAProto.Message.fromObject(m);
|
|
44
|
+
};
|
|
45
|
+
const assertColor = (color) => {
|
|
46
|
+
if (typeof color === 'number') {
|
|
47
|
+
return color < 0
|
|
48
|
+
? 0xffffffff + color + 1
|
|
49
|
+
: color;
|
|
50
|
+
}
|
|
51
|
+
let hex = color.trim();
|
|
52
|
+
if (hex.charCodeAt(0) === 35) {
|
|
53
|
+
hex = hex.slice(1);
|
|
54
|
+
}
|
|
55
|
+
if (hex.length <= 6) {
|
|
56
|
+
hex = hex.padStart(6, '0');
|
|
57
|
+
hex = 'FF' + hex;
|
|
58
|
+
}
|
|
59
|
+
return parseInt(hex, 16);
|
|
60
|
+
};
|
|
61
|
+
export const prepareWAMessageMedia = async (message, options) => {
|
|
62
|
+
const logger = options.logger;
|
|
63
|
+
let mediaType;
|
|
64
|
+
for (const key of MEDIA_KEYS) {
|
|
65
|
+
if (key in message) {
|
|
66
|
+
mediaType = key;
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!mediaType) {
|
|
71
|
+
throw new HttpError('Invalid media type', { statusCode: 400 });
|
|
72
|
+
}
|
|
73
|
+
const uploadData = {
|
|
74
|
+
...message,
|
|
75
|
+
media: message[mediaType]
|
|
76
|
+
};
|
|
77
|
+
delete uploadData[mediaType];
|
|
78
|
+
// check if cacheable + generate cache key
|
|
79
|
+
const cacheableKey = typeof uploadData.media === 'object' &&
|
|
80
|
+
'url' in uploadData.media &&
|
|
81
|
+
!!uploadData.media.url &&
|
|
82
|
+
!!options.mediaCache &&
|
|
83
|
+
mediaType + ':' + uploadData.media.url.toString();
|
|
84
|
+
if (mediaType === 'document' && !uploadData.fileName) {
|
|
85
|
+
uploadData.fileName = LIBRARY_NAME;
|
|
86
|
+
}
|
|
87
|
+
if (cacheableKey) {
|
|
88
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey);
|
|
89
|
+
if (mediaBuff) {
|
|
90
|
+
logger?.debug({ cacheableKey }, 'got media cache hit');
|
|
91
|
+
const obj = proto.Message.decode(mediaBuff);
|
|
92
|
+
const key = `${mediaType}Message`;
|
|
93
|
+
Object.assign(obj[key], { ...uploadData, media: undefined });
|
|
94
|
+
return obj;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const isNewsletter = isJidNewsletter(options.jid);
|
|
98
|
+
const requiresMimetypeDetection = uploadData.mimetype == null;
|
|
99
|
+
const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && uploadData.jpegThumbnail == null;
|
|
100
|
+
const requiresDurationComputation = mediaType === 'audio' && uploadData.seconds == null;
|
|
101
|
+
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && uploadData.waveform == null;
|
|
102
|
+
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
|
|
103
|
+
if (isNewsletter) {
|
|
104
|
+
logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
|
|
105
|
+
const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
|
|
106
|
+
const fileSha256B64 = fileSha256.toString('base64');
|
|
107
|
+
const [{ mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 }] = await Promise.all([
|
|
108
|
+
(async () => {
|
|
109
|
+
const result = await options.upload(filePath, {
|
|
110
|
+
fileEncSha256B64: fileSha256B64,
|
|
111
|
+
mediaType: mediaType,
|
|
112
|
+
timeoutMs: options.mediaUploadTimeoutMs,
|
|
113
|
+
newsletter: isNewsletter
|
|
114
|
+
});
|
|
115
|
+
logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
|
|
116
|
+
return result;
|
|
117
|
+
})(),
|
|
118
|
+
(async () => {
|
|
119
|
+
try {
|
|
120
|
+
if (requiresMimetypeDetection) {
|
|
121
|
+
const { mime } = uploadData.ptt === true ? { mime: MIMETYPE_MAP['audio'] } : (await detectFileType(filePath));
|
|
122
|
+
uploadData.mimetype = mime || MIMETYPE_MAP[mediaType];
|
|
123
|
+
logger?.debug('detected media mime');
|
|
124
|
+
}
|
|
125
|
+
if (requiresDurationComputation || requiresWaveformProcessing) {
|
|
126
|
+
const computedData = await getAudioData(filePath, logger);
|
|
127
|
+
uploadData.seconds = computedData.durationSeconds;
|
|
128
|
+
uploadData.waveform = computedData.waveform;
|
|
129
|
+
logger?.debug('computed audio data');
|
|
130
|
+
}
|
|
131
|
+
if (requiresAudioBackground) {
|
|
132
|
+
uploadData.backgroundArgb = assertColor(options.backgroundColor);
|
|
133
|
+
logger?.debug('computed backgroundColor audio');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
]).finally(async () => {
|
|
141
|
+
try {
|
|
142
|
+
await fs.unlink(filePath);
|
|
143
|
+
logger?.debug('removed tmp files');
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
logger?.warn('failed to remove tmp file');
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
const obj = ensureMessageProto({
|
|
150
|
+
// todo: add more support here
|
|
151
|
+
[`${mediaType}Message`]: {
|
|
152
|
+
url: mediaUrl,
|
|
153
|
+
directPath,
|
|
154
|
+
fileSha256,
|
|
155
|
+
fileLength,
|
|
156
|
+
thumbnailDirectPath,
|
|
157
|
+
thumbnailSha256,
|
|
158
|
+
...uploadData,
|
|
159
|
+
media: undefined
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
if (uploadData.ptv) {
|
|
163
|
+
obj.ptvMessage = obj.videoMessage;
|
|
164
|
+
delete obj.videoMessage;
|
|
165
|
+
}
|
|
166
|
+
if (obj.stickerMessage) {
|
|
167
|
+
obj.stickerMessage.stickerSentTs = Date.now();
|
|
168
|
+
}
|
|
169
|
+
if (cacheableKey) {
|
|
170
|
+
logger?.debug({ cacheableKey }, 'set cache');
|
|
171
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
|
|
172
|
+
}
|
|
173
|
+
return obj;
|
|
174
|
+
}
|
|
175
|
+
const requiresOriginalForSomeProcessing = requiresMimetypeDetection || requiresDurationComputation || requiresWaveformProcessing || requiresThumbnailComputation;
|
|
176
|
+
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
|
|
177
|
+
logger,
|
|
178
|
+
saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
|
|
179
|
+
opts: options.options
|
|
180
|
+
});
|
|
181
|
+
const fileEncSha256B64 = fileEncSha256.toString('base64');
|
|
182
|
+
const [{ mediaUrl, directPath }] = await Promise.all([
|
|
183
|
+
(async () => {
|
|
184
|
+
const result = await options.upload(encFilePath, {
|
|
185
|
+
fileEncSha256B64,
|
|
186
|
+
mediaType,
|
|
187
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
188
|
+
});
|
|
189
|
+
logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
|
|
190
|
+
return result;
|
|
191
|
+
})(),
|
|
192
|
+
(async () => {
|
|
193
|
+
try {
|
|
194
|
+
if (requiresThumbnailComputation) {
|
|
195
|
+
const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
|
|
196
|
+
uploadData.jpegThumbnail = thumbnail;
|
|
197
|
+
if (!uploadData.width && originalImageDimensions) {
|
|
198
|
+
uploadData.width = originalImageDimensions.width;
|
|
199
|
+
uploadData.height = originalImageDimensions.height;
|
|
200
|
+
logger?.debug('set dimensions');
|
|
201
|
+
}
|
|
202
|
+
logger?.debug('generated thumbnail');
|
|
203
|
+
}
|
|
204
|
+
if (requiresMimetypeDetection) {
|
|
205
|
+
const { mime } = uploadData.ptt === true ? { mime: MIMETYPE_MAP['audio'] } : (await detectFileType(originalFilePath));
|
|
206
|
+
uploadData.mimetype = mime || MIMETYPE_MAP[mediaType];
|
|
207
|
+
logger?.debug('detected media mime');
|
|
208
|
+
}
|
|
209
|
+
if (requiresDurationComputation || requiresWaveformProcessing) {
|
|
210
|
+
const computedData = await getAudioData(originalFilePath, logger);
|
|
211
|
+
uploadData.seconds = computedData.durationSeconds;
|
|
212
|
+
uploadData.waveform = computedData.waveform;
|
|
213
|
+
logger?.debug('computed audio data');
|
|
214
|
+
}
|
|
215
|
+
if (requiresAudioBackground) {
|
|
216
|
+
uploadData.backgroundArgb = assertColor(options.backgroundColor);
|
|
217
|
+
logger?.debug('computed backgroundColor audio');
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
|
|
222
|
+
}
|
|
223
|
+
})
|
|
224
|
+
]).finally(async () => {
|
|
225
|
+
try {
|
|
226
|
+
await fs.unlink(encFilePath);
|
|
227
|
+
if (originalFilePath) {
|
|
228
|
+
await fs.unlink(originalFilePath);
|
|
229
|
+
}
|
|
230
|
+
logger?.debug('removed tmp files');
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
logger?.warn('failed to remove tmp file');
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
const obj = ensureMessageProto({
|
|
237
|
+
[`${mediaType}Message`]: {
|
|
238
|
+
url: mediaUrl,
|
|
239
|
+
directPath,
|
|
240
|
+
mediaKey,
|
|
241
|
+
fileEncSha256,
|
|
242
|
+
fileSha256,
|
|
243
|
+
fileLength,
|
|
244
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
245
|
+
...uploadData,
|
|
246
|
+
media: undefined
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
if (uploadData.ptv) {
|
|
250
|
+
obj.ptvMessage = obj.videoMessage;
|
|
251
|
+
delete obj.videoMessage;
|
|
252
|
+
}
|
|
253
|
+
if (cacheableKey) {
|
|
254
|
+
logger?.debug({ cacheableKey }, 'set cache');
|
|
255
|
+
await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
|
|
256
|
+
}
|
|
257
|
+
return obj;
|
|
258
|
+
};
|
|
259
|
+
// Extract product message into a standalone function so it can also be reused as the header for interactive messages
|
|
260
|
+
const prepareProductMessage = async (message, options) => {
|
|
261
|
+
if (!message.businessOwnerJid) {
|
|
262
|
+
throw new HttpError('"businessOwnerJid" is missing from the content', { statusCode: 400 });
|
|
263
|
+
}
|
|
264
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
|
|
265
|
+
// Add product message default value
|
|
266
|
+
const { image, ...content } = message;
|
|
267
|
+
content.product = {
|
|
268
|
+
currencyCode: 'IDR',
|
|
269
|
+
priceAmount1000: 1000,
|
|
270
|
+
title: LIBRARY_NAME,
|
|
271
|
+
...message.product,
|
|
272
|
+
productImage: imageMessage
|
|
273
|
+
};
|
|
274
|
+
return content;
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
277
|
+
* Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
|
|
278
|
+
* based on https://github.com/WhiskeySockets/Baileys/pull/1561
|
|
279
|
+
*/
|
|
280
|
+
// Enhanced prepareStickerPackMessage
|
|
281
|
+
const prepareStickerPackMessage = async (message, options) => {
|
|
282
|
+
const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: eduh_dev021', description = '🏷️ eduh_dev021/baileys' } = message;
|
|
283
|
+
if (stickers.length > 60) {
|
|
284
|
+
throw new HttpError('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
|
|
285
|
+
}
|
|
286
|
+
if (stickers.length === 0) {
|
|
287
|
+
throw new HttpError('Sticker pack must contain at least one sticker', { statusCode: 400 });
|
|
288
|
+
}
|
|
289
|
+
if (!cover) {
|
|
290
|
+
throw new HttpError('Sticker pack must contain a cover', { statusCode: 400 });
|
|
291
|
+
}
|
|
292
|
+
const logger = options.logger;
|
|
293
|
+
// Add caching for sticker pack
|
|
294
|
+
let cacheableKey = false;
|
|
295
|
+
if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
|
|
296
|
+
const urls = [];
|
|
297
|
+
for (let i = 0; i < stickers.length; i++) {
|
|
298
|
+
const data = stickers[i].data;
|
|
299
|
+
if (typeof data === 'object' && data?.url) {
|
|
300
|
+
urls.push(data.url);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (urls.length > 0) {
|
|
304
|
+
cacheableKey = 'sticker:' + urls.join('@');
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (cacheableKey) {
|
|
308
|
+
const mediaBuff = await options.mediaCache.get(cacheableKey);
|
|
309
|
+
if (mediaBuff) {
|
|
310
|
+
logger?.debug({ cacheableKey }, 'got media cache hit');
|
|
311
|
+
return proto.Message.decode(mediaBuff);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const lib = await getImageProcessingLibrary();
|
|
315
|
+
const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
|
|
316
|
+
const hasImage = 'image' in lib && !!lib.image?.Transformer;
|
|
317
|
+
const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
|
|
318
|
+
if (!hasSharp && !hasImage) {
|
|
319
|
+
throw new HttpError('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
|
|
320
|
+
}
|
|
321
|
+
const isNewsletter = isJidNewsletter(options.jid);
|
|
322
|
+
const stickerPackIdValue = generateMessageIDV2();
|
|
323
|
+
const stickerData = new Array(stickers.length);
|
|
324
|
+
const stickerMetadata = new Array(stickers.length);
|
|
325
|
+
await Promise.all(stickers.map(async (sticker, index) => {
|
|
326
|
+
const { stream } = await getStream(sticker.data);
|
|
327
|
+
const buffer = await toBuffer(stream);
|
|
328
|
+
let webpBuffer;
|
|
329
|
+
let isAnimated = false;
|
|
330
|
+
if (isWebPBuffer(buffer)) {
|
|
331
|
+
webpBuffer = buffer;
|
|
332
|
+
isAnimated = isAnimatedWebP(buffer);
|
|
333
|
+
}
|
|
334
|
+
else if (hasSharp) {
|
|
335
|
+
webpBuffer = await lib.sharp.default(buffer)
|
|
336
|
+
.resize(512, 512, { fit: 'inside' })
|
|
337
|
+
.webp({ quality: 80 })
|
|
338
|
+
.toBuffer();
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
webpBuffer = await new lib.image.Transformer(buffer)
|
|
342
|
+
.resize(512, 512)
|
|
343
|
+
.webp(80);
|
|
344
|
+
}
|
|
345
|
+
if (webpBuffer.length > 1024 * 1024) {
|
|
346
|
+
throw new HttpError(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
|
|
347
|
+
}
|
|
348
|
+
const hash = sha256(webpBuffer)
|
|
349
|
+
.toString('base64')
|
|
350
|
+
.replace(/\//g, '-');
|
|
351
|
+
const fileName = `${hash}.webp`;
|
|
352
|
+
stickerData[index] = {
|
|
353
|
+
name: fileName,
|
|
354
|
+
data: webpBuffer
|
|
355
|
+
};
|
|
356
|
+
stickerMetadata[index] = {
|
|
357
|
+
fileName,
|
|
358
|
+
mimetype: 'image/webp',
|
|
359
|
+
isAnimated,
|
|
360
|
+
isLottie: sticker.isLottie || false,
|
|
361
|
+
emojis: sticker.emojis || ['✨'],
|
|
362
|
+
accessibilityLabel: sticker.accessibilityLabel || ''
|
|
363
|
+
};
|
|
364
|
+
}));
|
|
365
|
+
const trayIconFileName = `${stickerPackIdValue}.webp`;
|
|
366
|
+
const { stream: coverStream } = await getStream(cover);
|
|
367
|
+
const coverBuffer = await toBuffer(coverStream);
|
|
368
|
+
let coverWebpBuffer;
|
|
369
|
+
if (isWebPBuffer(coverBuffer)) {
|
|
370
|
+
coverWebpBuffer = coverBuffer;
|
|
371
|
+
}
|
|
372
|
+
else if (hasSharp) {
|
|
373
|
+
coverWebpBuffer = await lib.sharp.default(coverBuffer)
|
|
374
|
+
.resize(512, 512, { fit: 'inside' })
|
|
375
|
+
.webp({ quality: 80 })
|
|
376
|
+
.toBuffer();
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
|
|
380
|
+
.resize(512, 512)
|
|
381
|
+
.webp(80);
|
|
382
|
+
}
|
|
383
|
+
stickerData[stickers.length] = {
|
|
384
|
+
name: trayIconFileName,
|
|
385
|
+
data: coverWebpBuffer
|
|
386
|
+
};
|
|
387
|
+
const zipBuffer = await createZip(stickerData);
|
|
388
|
+
const { encFilePath, filePath, fileEncSha256, fileSha256, mediaKey, fileLength } = isNewsletter
|
|
389
|
+
? (await getRawMediaUploadData(zipBuffer, 'sticker-pack', logger))
|
|
390
|
+
: (await encryptedStream(zipBuffer, 'sticker-pack', {
|
|
391
|
+
logger,
|
|
392
|
+
opts: options.options
|
|
393
|
+
}));
|
|
394
|
+
let stickerPackUploadResult;
|
|
395
|
+
try {
|
|
396
|
+
stickerPackUploadResult = await options.upload(encFilePath || filePath, {
|
|
397
|
+
fileEncSha256B64: (fileEncSha256 || fileSha256).toString('base64'),
|
|
398
|
+
mediaType: 'sticker-pack',
|
|
399
|
+
timeoutMs: options.mediaUploadTimeoutMs,
|
|
400
|
+
newsletter: isNewsletter
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
finally {
|
|
404
|
+
await fs.unlink(encFilePath || filePath).catch(() => logger?.warn('failed to remove tmp file'));
|
|
405
|
+
}
|
|
406
|
+
const obj = {
|
|
407
|
+
name,
|
|
408
|
+
publisher,
|
|
409
|
+
stickerPackId: stickerPackIdValue,
|
|
410
|
+
packDescription: description,
|
|
411
|
+
stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
|
|
412
|
+
stickerPackSize: zipBuffer.length,
|
|
413
|
+
stickers: stickerMetadata,
|
|
414
|
+
fileSha256,
|
|
415
|
+
fileEncSha256,
|
|
416
|
+
mediaKey,
|
|
417
|
+
directPath: stickerPackUploadResult.directPath,
|
|
418
|
+
fileLength,
|
|
419
|
+
mediaKeyTimestamp: unixTimestampSeconds(),
|
|
420
|
+
trayIconFileName
|
|
421
|
+
};
|
|
422
|
+
try {
|
|
423
|
+
let thumbnailBuffer;
|
|
424
|
+
if (hasSharp) {
|
|
425
|
+
thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
|
|
426
|
+
}
|
|
427
|
+
else if (hasImage) {
|
|
428
|
+
thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
|
|
429
|
+
}
|
|
430
|
+
else if (hasJimp) {
|
|
431
|
+
const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
|
|
432
|
+
thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
throw new Error('No image processing library available for thumbnail generation');
|
|
436
|
+
}
|
|
437
|
+
if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
|
|
438
|
+
throw new Error('Failed to generate thumbnail buffer');
|
|
439
|
+
}
|
|
440
|
+
const thumbUpload = isNewsletter
|
|
441
|
+
? (await await getRawMediaUploadData(thumbnailBuffer, 'thumbnail-sticker-pack', logger))
|
|
442
|
+
: (await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
|
|
443
|
+
logger,
|
|
444
|
+
opts: options.options,
|
|
445
|
+
mediaKey
|
|
446
|
+
}));
|
|
447
|
+
let thumbUploadResult;
|
|
448
|
+
try {
|
|
449
|
+
thumbUploadResult = await options.upload(thumbUpload.encFilePath || thumbUpload.filePath, {
|
|
450
|
+
fileEncSha256B64: (thumbUpload.fileEncSha256 || thumbUpload.fileSha256).toString('base64'),
|
|
451
|
+
mediaType: 'thumbnail-sticker-pack',
|
|
452
|
+
timeoutMs: options.mediaUploadTimeoutMs,
|
|
453
|
+
newsletter: isNewsletter
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
finally {
|
|
457
|
+
await fs.unlink(thumbUpload.encFilePath || thumbUpload.filePath).catch(() => logger?.warn('failed to remove tmp file'));
|
|
458
|
+
}
|
|
459
|
+
Object.assign(obj, {
|
|
460
|
+
thumbnailDirectPath: thumbUploadResult.directPath,
|
|
461
|
+
thumbnailSha256: thumbUpload.fileSha256,
|
|
462
|
+
thumbnailEncSha256: thumbUpload.fileEncSha256,
|
|
463
|
+
thumbnailHeight: 252,
|
|
464
|
+
thumbnailWidth: 252,
|
|
465
|
+
imageDataHash: sha256(thumbnailBuffer).toString('base64')
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
logger?.warn(`Thumbnail generation failed: ${error}`);
|
|
470
|
+
}
|
|
471
|
+
const payload = ensureMessageProto({ stickerPackMessage: obj });
|
|
472
|
+
if (cacheableKey) {
|
|
473
|
+
logger?.debug({ cacheableKey }, 'set cache (background)');
|
|
474
|
+
options.mediaCache.set(cacheableKey, WAProto.Message.encode(payload).finish());
|
|
475
|
+
}
|
|
476
|
+
return payload;
|
|
477
|
+
};
|
|
478
|
+
// Add native flow button helper for interactive message
|
|
479
|
+
const prepareNativeFlowButtons = (message) => {
|
|
480
|
+
const buttons = message.nativeFlow;
|
|
481
|
+
const isButtonsFieldArray = Array.isArray(buttons);
|
|
482
|
+
const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
|
|
483
|
+
const messageParamsJson = {};
|
|
484
|
+
// Add offer and options inside interactive message
|
|
485
|
+
if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
|
|
486
|
+
Object.assign(messageParamsJson, {
|
|
487
|
+
limited_time_offer: {
|
|
488
|
+
text: message.offerText || LIBRARY_NAME,
|
|
489
|
+
url: message.offerUrl || DONATE_URL, // Apologies if this feels cheeky, just a fallback
|
|
490
|
+
copy_code: message.offerCode,
|
|
491
|
+
expiration_time: message.offerExpiration
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
|
|
496
|
+
Object.assign(messageParamsJson, {
|
|
497
|
+
bottom_sheet: {
|
|
498
|
+
in_thread_buttons_limit: 1,
|
|
499
|
+
divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
|
|
500
|
+
list_title: message.optionTitle || '📄 Select Options',
|
|
501
|
+
button_title: message.optionText
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
return {
|
|
506
|
+
buttons: correctedField.map(button => {
|
|
507
|
+
const buttonText = button.text || button.buttonText;
|
|
508
|
+
const buttonIcon = button.icon?.toUpperCase();
|
|
509
|
+
if (hasOptionalProperty(button, 'id') && !!button.id) {
|
|
510
|
+
return {
|
|
511
|
+
name: 'quick_reply',
|
|
512
|
+
buttonParamsJson: JSON.stringify({
|
|
513
|
+
display_text: buttonText || '👉🏻 Click',
|
|
514
|
+
id: button.id,
|
|
515
|
+
icon: buttonIcon
|
|
516
|
+
})
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
|
|
520
|
+
return {
|
|
521
|
+
name: 'cta_copy',
|
|
522
|
+
buttonParamsJson: JSON.stringify({
|
|
523
|
+
display_text: buttonText || '📋 Copy',
|
|
524
|
+
copy_code: button.copy,
|
|
525
|
+
icon: buttonIcon
|
|
526
|
+
})
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
else if (hasOptionalProperty(button, 'url') && !!button.url) {
|
|
530
|
+
return {
|
|
531
|
+
name: 'cta_url',
|
|
532
|
+
buttonParamsJson: JSON.stringify({
|
|
533
|
+
display_text: buttonText || '🌐 Visit',
|
|
534
|
+
url: button.url,
|
|
535
|
+
merchant_url: button.url,
|
|
536
|
+
webview_interaction: button.useWebview,
|
|
537
|
+
icon: buttonIcon
|
|
538
|
+
})
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
else if (hasOptionalProperty(button, 'call') && !!button.call) {
|
|
542
|
+
return {
|
|
543
|
+
name: 'cta_call',
|
|
544
|
+
buttonParamsJson: JSON.stringify({
|
|
545
|
+
display_text: buttonText || '📞 Call',
|
|
546
|
+
phone_number: button.call,
|
|
547
|
+
icon: buttonIcon
|
|
548
|
+
})
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
// Add "single_select" shortcut \(°o°)/
|
|
552
|
+
else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
|
|
553
|
+
return {
|
|
554
|
+
name: 'single_select',
|
|
555
|
+
buttonParamsJson: JSON.stringify({
|
|
556
|
+
title: buttonText || '📋 Select',
|
|
557
|
+
sections: button.sections,
|
|
558
|
+
icon: buttonIcon
|
|
559
|
+
})
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
return button;
|
|
563
|
+
}),
|
|
564
|
+
messageParamsJson: JSON.stringify(messageParamsJson)
|
|
565
|
+
};
|
|
566
|
+
};
|
|
567
|
+
export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
|
|
568
|
+
ephemeralExpiration = ephemeralExpiration || 0;
|
|
569
|
+
const content = {
|
|
570
|
+
ephemeralMessage: {
|
|
571
|
+
message: {
|
|
572
|
+
protocolMessage: {
|
|
573
|
+
type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
574
|
+
ephemeralExpiration
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
return ensureMessageProto(content);
|
|
580
|
+
};
|
|
581
|
+
/**
|
|
582
|
+
* Generate forwarded message content like WA does
|
|
583
|
+
* @param message the message to forward
|
|
584
|
+
* @param options.forceForward will show the message as forwarded even if it is from you
|
|
585
|
+
*/
|
|
586
|
+
export const generateForwardMessageContent = (message, forceForward) => {
|
|
587
|
+
let content = message.message;
|
|
588
|
+
if (!content) {
|
|
589
|
+
throw new HttpError('no content in message', { statusCode: 400 });
|
|
590
|
+
}
|
|
591
|
+
// hacky copy
|
|
592
|
+
content = normalizeMessageContent(content);
|
|
593
|
+
content = proto.Message.decode(proto.Message.encode(content).finish());
|
|
594
|
+
let key = Object.keys(content)[0];
|
|
595
|
+
let score = content?.[key]?.contextInfo?.forwardingScore || 0;
|
|
596
|
+
score += message.key.fromMe && !forceForward ? 0 : 1;
|
|
597
|
+
if (key === 'conversation') {
|
|
598
|
+
content.extendedTextMessage = { text: content[key] };
|
|
599
|
+
delete content.conversation;
|
|
600
|
+
key = 'extendedTextMessage';
|
|
601
|
+
}
|
|
602
|
+
const key_ = content?.[key];
|
|
603
|
+
if (score > 0) {
|
|
604
|
+
key_.contextInfo = { forwardingScore: score, isForwarded: true };
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
key_.contextInfo = {};
|
|
608
|
+
}
|
|
609
|
+
return content;
|
|
610
|
+
};
|
|
611
|
+
export const hasNonNullishProperty = (message, key) => {
|
|
612
|
+
return message != null &&
|
|
613
|
+
typeof message === 'object' &&
|
|
614
|
+
key in message &&
|
|
615
|
+
message[key] != null;
|
|
616
|
+
};
|
|
617
|
+
export const hasOptionalProperty = (obj, key) => {
|
|
618
|
+
return obj != null &&
|
|
619
|
+
typeof obj === 'object' &&
|
|
620
|
+
key in obj &&
|
|
621
|
+
obj[key] != null;
|
|
622
|
+
};
|
|
623
|
+
// Validate album message media to avoid errors
|
|
624
|
+
export const hasValidAlbumMedia = (message) => {
|
|
625
|
+
return !!(message.imageMessage ||
|
|
626
|
+
message.videoMessage);
|
|
627
|
+
};
|
|
628
|
+
export const hasValidInteractiveHeader = (message) => {
|
|
629
|
+
return !!(message.imageMessage ||
|
|
630
|
+
message.videoMessage ||
|
|
631
|
+
message.documentMessage ||
|
|
632
|
+
message.productMessage ||
|
|
633
|
+
message.locationMessage);
|
|
634
|
+
};
|
|
635
|
+
// Validate carousel cards header to avoid errors
|
|
636
|
+
export const hasValidCarouselHeader = (message) => {
|
|
637
|
+
return !!(message.imageMessage ||
|
|
638
|
+
message.videoMessage ||
|
|
639
|
+
message.productMessage);
|
|
640
|
+
};
|
|
641
|
+
export const markViewOnce = (m) => {
|
|
642
|
+
const type = getContentType(m);
|
|
643
|
+
if (!type)
|
|
644
|
+
return;
|
|
645
|
+
const content = m[type];
|
|
646
|
+
if (!content || typeof content !== 'object')
|
|
647
|
+
return;
|
|
648
|
+
const MessageType = WAProto.Message[type.charAt(0).toUpperCase() + type.slice(1)];
|
|
649
|
+
if (!MessageType?.prototype || !('viewOnce' in MessageType.prototype))
|
|
650
|
+
return;
|
|
651
|
+
content.viewOnce = true;
|
|
652
|
+
};
|
|
653
|
+
export const generateWAMessageContent = async (message, options) => {
|
|
654
|
+
var _a, _b;
|
|
655
|
+
let m = {};
|
|
656
|
+
// Add "raw" boolean to send raw messages directly via generateWAMessage
|
|
657
|
+
if (hasNonNullishProperty(message, 'raw')) {
|
|
658
|
+
delete message.raw;
|
|
659
|
+
return message;
|
|
660
|
+
}
|
|
661
|
+
// Add support for code block and table with richResponseMessage
|
|
662
|
+
else if (hasNonNullishProperty(message, 'code') ||
|
|
663
|
+
hasNonNullishProperty(message, 'links') ||
|
|
664
|
+
hasNonNullishProperty(message, 'table') ||
|
|
665
|
+
hasNonNullishProperty(message, 'richResponse')) {
|
|
666
|
+
m = prepareRichResponseMessage(message);
|
|
667
|
+
}
|
|
668
|
+
else if (hasNonNullishProperty(message, 'text')) {
|
|
669
|
+
const extContent = { text: message.text };
|
|
670
|
+
let urlInfo = message.linkPreview;
|
|
671
|
+
if (urlInfo == null) {
|
|
672
|
+
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
|
|
673
|
+
}
|
|
674
|
+
if (urlInfo) {
|
|
675
|
+
extContent.matchedText = urlInfo['matched-text'];
|
|
676
|
+
extContent.jpegThumbnail = urlInfo.jpegThumbnail;
|
|
677
|
+
extContent.description = urlInfo.description;
|
|
678
|
+
extContent.title = urlInfo.title;
|
|
679
|
+
extContent.previewType = urlInfo.previewType ?? urlInfo['preview-type'] ?? 0;
|
|
680
|
+
extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
|
|
681
|
+
const img = urlInfo.highQualityThumbnail;
|
|
682
|
+
if (img) {
|
|
683
|
+
extContent.thumbnailDirectPath = img.directPath;
|
|
684
|
+
extContent.mediaKey = img.mediaKey;
|
|
685
|
+
extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
|
|
686
|
+
extContent.thumbnailWidth = img.width;
|
|
687
|
+
extContent.thumbnailHeight = img.height;
|
|
688
|
+
extContent.thumbnailSha256 = img.fileSha256;
|
|
689
|
+
extContent.thumbnailEncSha256 = img.fileEncSha256;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
const customFavicon = message.favicon;
|
|
693
|
+
const favicon = customFavicon && typeof options.upload === 'function'
|
|
694
|
+
? (await prepareWAMessageMedia({ image: customFavicon }, options)).imageMessage
|
|
695
|
+
: urlInfo?.favicon;
|
|
696
|
+
if (favicon) {
|
|
697
|
+
extContent.faviconMmsMetadata = {
|
|
698
|
+
thumbnailDirectPath: favicon.directPath,
|
|
699
|
+
mediaKey: favicon.mediaKey,
|
|
700
|
+
mediaKeyTimestamp: favicon.mediaKeyTimestamp,
|
|
701
|
+
thumbnailWidth: 32,
|
|
702
|
+
thumbnailHeight: 32,
|
|
703
|
+
thumbnailSha256: favicon.fileSha256,
|
|
704
|
+
thumbnailEncSha256: favicon.fileEncSha256
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
if (options.backgroundColor) {
|
|
708
|
+
extContent.backgroundArgb = assertColor(options.backgroundColor);
|
|
709
|
+
}
|
|
710
|
+
if (options.font) {
|
|
711
|
+
extContent.font = options.font;
|
|
712
|
+
}
|
|
713
|
+
m.extendedTextMessage = extContent;
|
|
714
|
+
}
|
|
715
|
+
else if (hasNonNullishProperty(message, 'contacts')) {
|
|
716
|
+
const contactLen = message.contacts.contacts.length;
|
|
717
|
+
if (!contactLen) {
|
|
718
|
+
throw new HttpError('require atleast 1 contact', { statusCode: 400 });
|
|
719
|
+
}
|
|
720
|
+
if (contactLen === 1) {
|
|
721
|
+
m.contactMessage = message.contacts.contacts[0];
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
m.contactsArrayMessage = message.contacts;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
else if (hasNonNullishProperty(message, 'location')) {
|
|
728
|
+
m.locationMessage = message.location;
|
|
729
|
+
}
|
|
730
|
+
else if (hasNonNullishProperty(message, 'react')) {
|
|
731
|
+
if (!message.react.senderTimestampMs) {
|
|
732
|
+
message.react.senderTimestampMs = Date.now();
|
|
733
|
+
}
|
|
734
|
+
m.reactionMessage = message.react;
|
|
735
|
+
}
|
|
736
|
+
else if (hasNonNullishProperty(message, 'delete')) {
|
|
737
|
+
m.protocolMessage = {
|
|
738
|
+
key: message.delete,
|
|
739
|
+
type: WAProto.Message.ProtocolMessage.Type.REVOKE
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
else if (hasNonNullishProperty(message, 'forward')) {
|
|
743
|
+
m = generateForwardMessageContent(message.forward, message.force);
|
|
744
|
+
}
|
|
745
|
+
else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
|
|
746
|
+
const exp = typeof message.disappearingMessagesInChat === 'boolean'
|
|
747
|
+
? message.disappearingMessagesInChat
|
|
748
|
+
? WA_DEFAULT_EPHEMERAL
|
|
749
|
+
: 0
|
|
750
|
+
: message.disappearingMessagesInChat;
|
|
751
|
+
m = prepareDisappearingMessageSettingContent(exp);
|
|
752
|
+
}
|
|
753
|
+
else if (hasNonNullishProperty(message, 'groupInvite')) {
|
|
754
|
+
m.groupInviteMessage = {};
|
|
755
|
+
m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
|
|
756
|
+
m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
|
|
757
|
+
m.groupInviteMessage.caption = message.groupInvite.text;
|
|
758
|
+
m.groupInviteMessage.groupJid = message.groupInvite.jid;
|
|
759
|
+
m.groupInviteMessage.groupName = message.groupInvite.subject;
|
|
760
|
+
//TODO: use built-in interface and get disappearing mode info etc.
|
|
761
|
+
//TODO: cache / use store!?
|
|
762
|
+
if (options.getProfilePicUrl) {
|
|
763
|
+
const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
|
|
764
|
+
if (pfpUrl) {
|
|
765
|
+
const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
|
|
766
|
+
if (resp.ok) {
|
|
767
|
+
const buf = Buffer.from(await resp.arrayBuffer());
|
|
768
|
+
m.groupInviteMessage.jpegThumbnail = buf;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
else if (hasNonNullishProperty(message, 'pin')) {
|
|
774
|
+
m.pinInChatMessage = {};
|
|
775
|
+
m.messageContextInfo = {};
|
|
776
|
+
m.pinInChatMessage.key = message.pin;
|
|
777
|
+
m.pinInChatMessage.type = message.type;
|
|
778
|
+
m.pinInChatMessage.senderTimestampMs = Date.now();
|
|
779
|
+
m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
|
|
780
|
+
}
|
|
781
|
+
else if (hasNonNullishProperty(message, 'keep')) {
|
|
782
|
+
m.keepInChatMessage = {};
|
|
783
|
+
m.keepInChatMessage.key = message.keep;
|
|
784
|
+
m.keepInChatMessage.keepType = message.type;
|
|
785
|
+
m.keepInChatMessage.timestampMs = Date.now();
|
|
786
|
+
}
|
|
787
|
+
else if (hasNonNullishProperty(message, 'flowReply')) {
|
|
788
|
+
m.interactiveResponseMessage = {
|
|
789
|
+
body: {
|
|
790
|
+
format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
|
|
791
|
+
text: message.flowReply.text
|
|
792
|
+
},
|
|
793
|
+
nativeFlowResponseMessage: {
|
|
794
|
+
name: message.flowReply.name,
|
|
795
|
+
paramsJson: message.flowReply.paramsJson || '{}',
|
|
796
|
+
version: message.flowReply.version || 1
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
else if (hasNonNullishProperty(message, 'buttonReply')) {
|
|
801
|
+
switch (message.type) {
|
|
802
|
+
case 'template':
|
|
803
|
+
m.templateButtonReplyMessage = {
|
|
804
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
805
|
+
selectedId: message.buttonReply.id,
|
|
806
|
+
selectedIndex: message.buttonReply.index
|
|
807
|
+
};
|
|
808
|
+
break;
|
|
809
|
+
case 'plain':
|
|
810
|
+
m.buttonsResponseMessage = {
|
|
811
|
+
selectedButtonId: message.buttonReply.id,
|
|
812
|
+
selectedDisplayText: message.buttonReply.displayText,
|
|
813
|
+
type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
|
|
814
|
+
};
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
else if (hasNonNullishProperty(message, 'listReply')) {
|
|
819
|
+
m.listResponseMessage = {
|
|
820
|
+
description: message.listReply.description,
|
|
821
|
+
listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
|
|
822
|
+
singleSelectReply: {
|
|
823
|
+
selectedRowId: message.listReply.id
|
|
824
|
+
},
|
|
825
|
+
title: message.listReply.title
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
|
|
829
|
+
const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
|
|
830
|
+
m.ptvMessage = videoMessage;
|
|
831
|
+
}
|
|
832
|
+
else if (hasNonNullishProperty(message, 'product')) {
|
|
833
|
+
m.productMessage = await prepareProductMessage(message, options);
|
|
834
|
+
}
|
|
835
|
+
else if (hasNonNullishProperty(message, 'event')) {
|
|
836
|
+
m.eventMessage = {};
|
|
837
|
+
const startTime = Math.floor(message.event.startDate.getTime() / 1000);
|
|
838
|
+
if (message.event.call && options.getCallLink) {
|
|
839
|
+
const token = await options.getCallLink(message.event.call, { startTime });
|
|
840
|
+
m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
|
|
841
|
+
}
|
|
842
|
+
m.messageContextInfo = {
|
|
843
|
+
// encKey
|
|
844
|
+
messageSecret: message.event.messageSecret || randomBytes(32)
|
|
845
|
+
};
|
|
846
|
+
m.eventMessage.name = message.event.name;
|
|
847
|
+
m.eventMessage.description = message.event.description;
|
|
848
|
+
m.eventMessage.startTime = startTime;
|
|
849
|
+
m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
|
|
850
|
+
m.eventMessage.isCanceled = message.event.isCancelled ?? false;
|
|
851
|
+
m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
|
|
852
|
+
m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
|
|
853
|
+
m.eventMessage.location = message.event.location;
|
|
854
|
+
}
|
|
855
|
+
else if (hasNonNullishProperty(message, 'poll')) {
|
|
856
|
+
(_a = message.poll).selectableCount || (_a.selectableCount = 0);
|
|
857
|
+
(_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
|
|
858
|
+
if (!Array.isArray(message.poll.values)) {
|
|
859
|
+
throw new HttpError('Invalid poll values', { statusCode: 400 });
|
|
860
|
+
}
|
|
861
|
+
if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
|
|
862
|
+
throw new HttpError(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
|
|
863
|
+
statusCode: 400
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
const pollCreationMessage = {
|
|
867
|
+
name: message.poll.name,
|
|
868
|
+
selectableOptionsCount: message.poll.selectableCount,
|
|
869
|
+
options: message.poll.values.map(optionName => ({ optionName })),
|
|
870
|
+
endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
|
|
871
|
+
hideParticipantName: message.poll.hideVoter ?? false,
|
|
872
|
+
allowAddOption: message.poll.canAddOption ?? false
|
|
873
|
+
};
|
|
874
|
+
if (message.poll.toAnnouncementGroup) {
|
|
875
|
+
// poll v2 is for community announcement groups (single select and multiple)
|
|
876
|
+
m.pollCreationMessageV2 = pollCreationMessage;
|
|
877
|
+
}
|
|
878
|
+
else {
|
|
879
|
+
// Add quiz message support
|
|
880
|
+
if (message.poll.pollType === 1) {
|
|
881
|
+
if (!message.poll.correctAnswer) {
|
|
882
|
+
throw new HttpError('No "correctAnswer" provided for quiz', { statusCode: 400 });
|
|
883
|
+
}
|
|
884
|
+
m.pollCreationMessageV5 = {
|
|
885
|
+
// quiz for newsletter only
|
|
886
|
+
...pollCreationMessage,
|
|
887
|
+
correctAnswer: {
|
|
888
|
+
optionName: message.poll.correctAnswer.toString
|
|
889
|
+
},
|
|
890
|
+
pollType: 1,
|
|
891
|
+
selectableOptionsCount: 1
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
else if (message.poll.selectableCount === 1) {
|
|
895
|
+
//poll v3 is for single select polls
|
|
896
|
+
m.pollCreationMessageV3 = pollCreationMessage;
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
// poll for multiple choice polls
|
|
900
|
+
m.pollCreationMessage = pollCreationMessage;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
m.messageContextInfo = {
|
|
904
|
+
// encKey
|
|
905
|
+
messageSecret: message.poll.messageSecret || randomBytes(32)
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
// Add poll result snapshot message
|
|
909
|
+
else if (hasNonNullishProperty(message, 'pollResult')) {
|
|
910
|
+
const pollResultSnapshotMessage = {
|
|
911
|
+
name: message.pollResult.name,
|
|
912
|
+
pollVotes: message.pollResult.votes.map(vote => ({
|
|
913
|
+
optionName: vote.name,
|
|
914
|
+
optionVoteCount: parseInt(vote.voteCount)
|
|
915
|
+
}))
|
|
916
|
+
};
|
|
917
|
+
if (message.pollResult.pollType === 1) {
|
|
918
|
+
pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
|
|
919
|
+
m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
|
|
920
|
+
}
|
|
921
|
+
else {
|
|
922
|
+
pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
|
|
923
|
+
m.pollResultSnapshotMessage = pollResultSnapshotMessage;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
// Add poll update message
|
|
927
|
+
else if (hasNonNullishProperty(message, 'pollUpdate')) {
|
|
928
|
+
if (!message.pollUpdate.key) {
|
|
929
|
+
throw new HttpError('Message key is required', { statusCode: 400 });
|
|
930
|
+
}
|
|
931
|
+
if (!message.pollUpdate.vote) {
|
|
932
|
+
throw new HttpError('Encrypted vote payload is required', { statusCode: 400 });
|
|
933
|
+
}
|
|
934
|
+
m.pollUpdateMessage = {
|
|
935
|
+
metadata: message.pollUpdate.metadata,
|
|
936
|
+
pollCreationMessageKey: message.pollUpdate.key,
|
|
937
|
+
senderTimestampMs: Date.now(),
|
|
938
|
+
vote: message.pollUpdate.vote
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
// Add payment invite message
|
|
942
|
+
else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
|
|
943
|
+
m.paymentInviteMessage = {
|
|
944
|
+
expiryTimestamp: Date.now(),
|
|
945
|
+
serviceType: message.paymentInviteServiceType
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
// Add order message
|
|
949
|
+
else if (hasNonNullishProperty(message, 'orderText')) {
|
|
950
|
+
if (!Buffer.isBuffer(message.thumbnail)) {
|
|
951
|
+
throw new HttpError('Must provide thumbnail buffer in order message', { statusCode: 400 });
|
|
952
|
+
}
|
|
953
|
+
m.orderMessage = {
|
|
954
|
+
itemCount: 1,
|
|
955
|
+
messageVersion: 1,
|
|
956
|
+
orderTitle: LIBRARY_NAME,
|
|
957
|
+
status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
|
|
958
|
+
surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
|
|
959
|
+
token: generateMessageIDV2(),
|
|
960
|
+
totalAmount1000: 1000,
|
|
961
|
+
totalCurrencyCode: 'IDR',
|
|
962
|
+
...message,
|
|
963
|
+
message: message.orderText
|
|
964
|
+
};
|
|
965
|
+
delete m.orderMessage.orderText;
|
|
966
|
+
}
|
|
967
|
+
// Add support for album messages
|
|
968
|
+
else if (hasNonNullishProperty(message, 'album')) {
|
|
969
|
+
if (!Array.isArray(message.album)) {
|
|
970
|
+
throw new HttpError('Invalid album type. Expected an array.', { statusCode: 400 });
|
|
971
|
+
}
|
|
972
|
+
let videoCount = 0;
|
|
973
|
+
for (let i = 0; i < message.album.length; i++) {
|
|
974
|
+
if (message.album[i].video)
|
|
975
|
+
videoCount++;
|
|
976
|
+
}
|
|
977
|
+
;
|
|
978
|
+
let imageCount = 0;
|
|
979
|
+
for (let i = 0; i < message.album.length; i++) {
|
|
980
|
+
if (message.album[i].image)
|
|
981
|
+
imageCount++;
|
|
982
|
+
}
|
|
983
|
+
;
|
|
984
|
+
if ((videoCount + imageCount) < 2) {
|
|
985
|
+
throw new HttpError('Minimum provide 2 media to upload album message', { statusCode: 400 });
|
|
986
|
+
}
|
|
987
|
+
m.albumMessage = {
|
|
988
|
+
expectedImageCount: imageCount,
|
|
989
|
+
expectedVideoCount: videoCount
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
|
|
993
|
+
m.protocolMessage = {
|
|
994
|
+
type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
|
|
998
|
+
m.requestPhoneNumberMessage = {};
|
|
999
|
+
}
|
|
1000
|
+
else if (hasNonNullishProperty(message, 'limitSharing')) {
|
|
1001
|
+
m.protocolMessage = {
|
|
1002
|
+
type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
|
|
1003
|
+
limitSharing: {
|
|
1004
|
+
sharingLimited: message.limitSharing === true,
|
|
1005
|
+
trigger: 1,
|
|
1006
|
+
limitSharingSettingTimestamp: Date.now(),
|
|
1007
|
+
initiatedByMe: true
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
else if (hasNonNullishProperty(message, 'stickers')) {
|
|
1012
|
+
m = await prepareStickerPackMessage(message, options);
|
|
1013
|
+
}
|
|
1014
|
+
else {
|
|
1015
|
+
m = await prepareWAMessageMedia(message, options);
|
|
1016
|
+
}
|
|
1017
|
+
// Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
|
|
1018
|
+
if (hasNonNullishProperty(message, 'buttons')) {
|
|
1019
|
+
const buttonsMessage = {
|
|
1020
|
+
buttons: message.buttons.map(button => {
|
|
1021
|
+
// Add "single_select" shortcut!
|
|
1022
|
+
const buttonText = button.text || button.buttonText;
|
|
1023
|
+
if (hasOptionalProperty(button, 'sections')) {
|
|
1024
|
+
return {
|
|
1025
|
+
nativeFlowInfo: {
|
|
1026
|
+
name: 'single_select',
|
|
1027
|
+
paramsJson: JSON.stringify({
|
|
1028
|
+
title: buttonText,
|
|
1029
|
+
sections: button.sections
|
|
1030
|
+
})
|
|
1031
|
+
},
|
|
1032
|
+
type: ButtonType.NATIVE_FLOW
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
else if (hasOptionalProperty(button, 'name')) {
|
|
1036
|
+
return {
|
|
1037
|
+
nativeFlowInfo: {
|
|
1038
|
+
name: button.name,
|
|
1039
|
+
paramsJson: button.paramsJson
|
|
1040
|
+
},
|
|
1041
|
+
type: ButtonType.NATIVE_FLOW
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
return {
|
|
1045
|
+
buttonId: button.id || button.buttonId,
|
|
1046
|
+
buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
|
|
1047
|
+
type: button.type || ButtonType.RESPONSE
|
|
1048
|
+
};
|
|
1049
|
+
})
|
|
1050
|
+
};
|
|
1051
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1052
|
+
buttonsMessage.contentText = message.text;
|
|
1053
|
+
buttonsMessage.headerType = ButtonHeaderType.EMPTY;
|
|
1054
|
+
}
|
|
1055
|
+
else {
|
|
1056
|
+
if (hasOptionalProperty(message, 'caption')) {
|
|
1057
|
+
buttonsMessage.contentText = message.caption;
|
|
1058
|
+
}
|
|
1059
|
+
const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
|
|
1060
|
+
buttonsMessage.headerType = ButtonHeaderType[type];
|
|
1061
|
+
Object.assign(buttonsMessage, m);
|
|
1062
|
+
}
|
|
1063
|
+
if (hasOptionalProperty(message, 'footer')) {
|
|
1064
|
+
buttonsMessage.footerText = message.footer;
|
|
1065
|
+
}
|
|
1066
|
+
m = { buttonsMessage };
|
|
1067
|
+
}
|
|
1068
|
+
else if (hasNonNullishProperty(message, 'sections')) {
|
|
1069
|
+
const listMessage = {
|
|
1070
|
+
sections: message.sections,
|
|
1071
|
+
buttonText: message.buttonText,
|
|
1072
|
+
title: message.title,
|
|
1073
|
+
footerText: message.footer,
|
|
1074
|
+
description: message.text,
|
|
1075
|
+
listType: ListType.SINGLE_SELECT
|
|
1076
|
+
};
|
|
1077
|
+
m = { listMessage };
|
|
1078
|
+
}
|
|
1079
|
+
// This message type is shown on WhatsApp Web/Desktop and iOS. On Android, it only appears in newsletters (so far)
|
|
1080
|
+
else if (hasNonNullishProperty(message, 'templateButtons')) {
|
|
1081
|
+
const hydratedTemplate = {
|
|
1082
|
+
hydratedButtons: message.templateButtons.map((button, i) => {
|
|
1083
|
+
const buttonText = button.text || button.buttonText;
|
|
1084
|
+
if (hasOptionalProperty(button, 'id')) {
|
|
1085
|
+
return {
|
|
1086
|
+
index: i,
|
|
1087
|
+
quickReplyButton: {
|
|
1088
|
+
displayText: buttonText || '👉🏻 Click',
|
|
1089
|
+
id: button.id
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
else if (hasOptionalProperty(button, 'url')) {
|
|
1094
|
+
return {
|
|
1095
|
+
index: i,
|
|
1096
|
+
urlButton: {
|
|
1097
|
+
displayText: buttonText || '🌐 Visit',
|
|
1098
|
+
url: button.url
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
else if (hasOptionalProperty(button, 'call')) {
|
|
1103
|
+
return {
|
|
1104
|
+
index: i,
|
|
1105
|
+
callButton: {
|
|
1106
|
+
displayText: buttonText || '📞 Call',
|
|
1107
|
+
phoneNumber: button.call
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
button.index = button.index || i;
|
|
1112
|
+
return button;
|
|
1113
|
+
})
|
|
1114
|
+
};
|
|
1115
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1116
|
+
hydratedTemplate.hydratedContentText = message.text;
|
|
1117
|
+
}
|
|
1118
|
+
else {
|
|
1119
|
+
if (hasOptionalProperty(message, 'caption')) {
|
|
1120
|
+
hydratedTemplate.hydratedTitleText = message.title;
|
|
1121
|
+
hydratedTemplate.hydratedContentText = message.caption;
|
|
1122
|
+
}
|
|
1123
|
+
;
|
|
1124
|
+
Object.assign(hydratedTemplate, m);
|
|
1125
|
+
}
|
|
1126
|
+
if (hasOptionalProperty(message, 'footer')) {
|
|
1127
|
+
hydratedTemplate.hydratedFooterText = message.footer;
|
|
1128
|
+
}
|
|
1129
|
+
hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // Minimal templateId to satisfy WhatsApp ( ꈍᴗꈍ)
|
|
1130
|
+
m = {
|
|
1131
|
+
templateMessage: {
|
|
1132
|
+
hydratedFourRowTemplate: hydratedTemplate,
|
|
1133
|
+
hydratedTemplate: hydratedTemplate
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
else if (hasNonNullishProperty(message, 'nativeFlow')) {
|
|
1138
|
+
const interactiveMessage = {
|
|
1139
|
+
nativeFlowMessage: prepareNativeFlowButtons(message)
|
|
1140
|
+
};
|
|
1141
|
+
if (hasOptionalProperty(message, 'bizJid')) {
|
|
1142
|
+
interactiveMessage.collectionMessage = {
|
|
1143
|
+
bizJid: message.bizJid,
|
|
1144
|
+
id: message.id,
|
|
1145
|
+
messageVersion: 1
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
else if (hasOptionalProperty(message, 'shopSurface')) {
|
|
1149
|
+
interactiveMessage.shopStorefrontMessage = {
|
|
1150
|
+
surface: message.shopSurface,
|
|
1151
|
+
id: message.id,
|
|
1152
|
+
messageVersion: 1
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1156
|
+
interactiveMessage.body = { text: message.text };
|
|
1157
|
+
}
|
|
1158
|
+
else {
|
|
1159
|
+
if (hasOptionalProperty(message, 'caption')) {
|
|
1160
|
+
const isValidHeader = hasValidInteractiveHeader(m);
|
|
1161
|
+
if (!isValidHeader) {
|
|
1162
|
+
throw new HttpError('Invalid media type for interactive message header', { statusCode: 400 });
|
|
1163
|
+
}
|
|
1164
|
+
interactiveMessage.header = {
|
|
1165
|
+
title: message.title || '',
|
|
1166
|
+
subtitle: message.subtitle || '',
|
|
1167
|
+
hasMediaAttachment: isValidHeader
|
|
1168
|
+
};
|
|
1169
|
+
interactiveMessage.body = { text: message.caption };
|
|
1170
|
+
}
|
|
1171
|
+
if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
|
|
1172
|
+
interactiveMessage.jpegThumbnail = message.thumbnail;
|
|
1173
|
+
}
|
|
1174
|
+
Object.assign(interactiveMessage.header, m);
|
|
1175
|
+
}
|
|
1176
|
+
if (hasOptionalProperty(message, 'audioFooter')) {
|
|
1177
|
+
const { audioMessage } = await prepareWAMessageMedia({
|
|
1178
|
+
audio: message.audioFooter
|
|
1179
|
+
}, options);
|
|
1180
|
+
interactiveMessage.footer = {
|
|
1181
|
+
audioMessage,
|
|
1182
|
+
hasMediaAttachment: true
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
else if (hasOptionalProperty(message, 'footer')) {
|
|
1186
|
+
interactiveMessage.footer = { text: message.footer };
|
|
1187
|
+
}
|
|
1188
|
+
m = { interactiveMessage };
|
|
1189
|
+
}
|
|
1190
|
+
else if (hasNonNullishProperty(message, 'cards')) {
|
|
1191
|
+
const interactiveMessage = {
|
|
1192
|
+
carouselMessage: {
|
|
1193
|
+
cards: await Promise.all(message.cards.map(async (card) => {
|
|
1194
|
+
let carouselHeader = {};
|
|
1195
|
+
if (hasNonNullishProperty(card, 'product')) {
|
|
1196
|
+
carouselHeader.productMessage = await prepareProductMessage(card, options);
|
|
1197
|
+
}
|
|
1198
|
+
else {
|
|
1199
|
+
carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
|
|
1200
|
+
}
|
|
1201
|
+
const isValidHeader = hasValidCarouselHeader(carouselHeader);
|
|
1202
|
+
if (!isValidHeader) {
|
|
1203
|
+
throw new HttpError('Invalid media type for carousel card', { statusCode: 400 });
|
|
1204
|
+
}
|
|
1205
|
+
const carouselCard = {
|
|
1206
|
+
nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
|
|
1207
|
+
};
|
|
1208
|
+
if (hasOptionalProperty(card, 'text')) {
|
|
1209
|
+
carouselCard.body = { text: card.text };
|
|
1210
|
+
}
|
|
1211
|
+
else {
|
|
1212
|
+
if (hasOptionalProperty(card, 'caption')) {
|
|
1213
|
+
carouselCard.header = {
|
|
1214
|
+
title: card.title || '',
|
|
1215
|
+
subtitle: card.subtitle || '',
|
|
1216
|
+
hasMediaAttachment: isValidHeader
|
|
1217
|
+
};
|
|
1218
|
+
carouselCard.body = { text: card.caption };
|
|
1219
|
+
}
|
|
1220
|
+
if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
|
|
1221
|
+
carouselCard.jpegThumbnail = card.thumbnail;
|
|
1222
|
+
}
|
|
1223
|
+
Object.assign(carouselCard.header, carouselHeader);
|
|
1224
|
+
}
|
|
1225
|
+
if (hasOptionalProperty(card, 'audioFooter')) {
|
|
1226
|
+
const { audioMessage } = await prepareWAMessageMedia({
|
|
1227
|
+
audio: card.audioFooter
|
|
1228
|
+
}, options);
|
|
1229
|
+
carouselCard.footer = {
|
|
1230
|
+
audioMessage,
|
|
1231
|
+
hasMediaAttachment: true
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
else if (hasOptionalProperty(card, 'footer')) {
|
|
1235
|
+
carouselCard.footer = { text: card.footer };
|
|
1236
|
+
}
|
|
1237
|
+
return carouselCard;
|
|
1238
|
+
})),
|
|
1239
|
+
carouselCardType: CarouselCardType.UNKNOWN,
|
|
1240
|
+
messageVersion: 1
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
if (hasOptionalProperty(message, 'text')) {
|
|
1244
|
+
interactiveMessage.body = { text: message.text };
|
|
1245
|
+
}
|
|
1246
|
+
if (hasOptionalProperty(message, 'footer')) {
|
|
1247
|
+
interactiveMessage.footer = { text: message.footer };
|
|
1248
|
+
}
|
|
1249
|
+
m = { interactiveMessage };
|
|
1250
|
+
}
|
|
1251
|
+
// Add request payment message
|
|
1252
|
+
else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
|
|
1253
|
+
const requestPaymentMessage = {
|
|
1254
|
+
amount: {
|
|
1255
|
+
currencyCode: 'IDR',
|
|
1256
|
+
offset: 1000,
|
|
1257
|
+
value: 1000
|
|
1258
|
+
},
|
|
1259
|
+
amount1000: 1000,
|
|
1260
|
+
currencyCodeIso4217: 'IDR',
|
|
1261
|
+
expiryTimestamp: Date.now(),
|
|
1262
|
+
noteMessage: m,
|
|
1263
|
+
requestFrom: message.requestPaymentFrom,
|
|
1264
|
+
...message
|
|
1265
|
+
};
|
|
1266
|
+
delete requestPaymentMessage.requestPaymentFrom;
|
|
1267
|
+
if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
|
|
1268
|
+
Object.assign(requestPaymentMessage.noteMessage, m);
|
|
1269
|
+
}
|
|
1270
|
+
else {
|
|
1271
|
+
throw new HttpError('Invalid message type for request payment note message', { statusCode: 400 });
|
|
1272
|
+
}
|
|
1273
|
+
m = { requestPaymentMessage };
|
|
1274
|
+
}
|
|
1275
|
+
// Add invoice message
|
|
1276
|
+
else if (hasNonNullishProperty(message, 'invoiceNote')) {
|
|
1277
|
+
const attachment = m.imageMessage || m.documentMessage;
|
|
1278
|
+
const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
|
|
1279
|
+
const invoiceMessage = {
|
|
1280
|
+
attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
|
|
1281
|
+
note: message.invoiceNote
|
|
1282
|
+
};
|
|
1283
|
+
if (attachment) {
|
|
1284
|
+
const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
|
|
1285
|
+
Object.assign(invoiceMessage, {
|
|
1286
|
+
attachmentDirectPath: directPath,
|
|
1287
|
+
attachmentFileEncSha256: fileEncSha256,
|
|
1288
|
+
attachmentFileSha256: fileSha256,
|
|
1289
|
+
attachmentJpegThumbnail: jpegThumbnail,
|
|
1290
|
+
attachmentMediaKey: mediaKey,
|
|
1291
|
+
attachmentMediaKeyTimestamp: mediaKeyTimestamp,
|
|
1292
|
+
attachmentMimetype: mimetype,
|
|
1293
|
+
token: generateMessageIDV2
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
else {
|
|
1297
|
+
throw new HttpError('Invalid media type for invoice message', { statusCode: 400 });
|
|
1298
|
+
}
|
|
1299
|
+
m = { invoiceMessage };
|
|
1300
|
+
}
|
|
1301
|
+
// Add direct externalAdReply access (no need to create contextInfo first)
|
|
1302
|
+
if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
|
|
1303
|
+
const messageType = Object.keys(m)[0];
|
|
1304
|
+
const key = m[messageType];
|
|
1305
|
+
const content = message.externalAdReply;
|
|
1306
|
+
if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
|
|
1307
|
+
throw new HttpError('Thumbnail must in buffer type', { statusCode: 400 });
|
|
1308
|
+
}
|
|
1309
|
+
if (!content.url || typeof content.url !== 'string') {
|
|
1310
|
+
content.url = DONATE_URL; // Apologies if this feels cheeky, just a fallback
|
|
1311
|
+
}
|
|
1312
|
+
const externalAdReply = {
|
|
1313
|
+
...content,
|
|
1314
|
+
body: content.body,
|
|
1315
|
+
mediaType: content.mediaType || 1,
|
|
1316
|
+
mediaUrl: content.url,
|
|
1317
|
+
renderLargerThumbnail: content.largeThumbnail,
|
|
1318
|
+
sourceUrl: content.url,
|
|
1319
|
+
thumbnail: content.thumbnail,
|
|
1320
|
+
thumbnailUrl: content.url + '?update=' + Date.now(),
|
|
1321
|
+
title: content.title || LIBRARY_NAME
|
|
1322
|
+
};
|
|
1323
|
+
delete externalAdReply.subTitle;
|
|
1324
|
+
delete externalAdReply.largeThumbnail;
|
|
1325
|
+
delete externalAdReply.url;
|
|
1326
|
+
if ('contextInfo' in key && !!key.contextInfo) {
|
|
1327
|
+
key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
|
|
1328
|
+
}
|
|
1329
|
+
else if (key) {
|
|
1330
|
+
key.contextInfo = { externalAdReply };
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
|
|
1334
|
+
(hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
|
|
1335
|
+
const messageType = Object.keys(m)[0];
|
|
1336
|
+
const key = m[messageType];
|
|
1337
|
+
if (key && 'contextInfo' in key) {
|
|
1338
|
+
key.contextInfo = key.contextInfo || {};
|
|
1339
|
+
if (message.mentions?.length) {
|
|
1340
|
+
key.contextInfo.mentionedJid = message.mentions;
|
|
1341
|
+
}
|
|
1342
|
+
if (message.mentionAll) {
|
|
1343
|
+
key.contextInfo.nonJidMentions = 1;
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
else if (key) {
|
|
1347
|
+
key.contextInfo = {
|
|
1348
|
+
mentionedJid: message.mentions,
|
|
1349
|
+
nonJidMentions: message.mentionAll ? 1 : 0
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
|
|
1354
|
+
const messageType = Object.keys(m)[0];
|
|
1355
|
+
const key = m[messageType];
|
|
1356
|
+
if ('contextInfo' in key && !!key.contextInfo) {
|
|
1357
|
+
key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
|
|
1358
|
+
}
|
|
1359
|
+
else if (key) {
|
|
1360
|
+
key.contextInfo = message.contextInfo;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
// Add "groupStatus" boolean to set contextInfo.isGroupStatus and wrap message into groupStatusMessageV2
|
|
1364
|
+
if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
|
|
1365
|
+
const messageType = Object.keys(m)[0];
|
|
1366
|
+
const key = m[messageType];
|
|
1367
|
+
if ('contextInfo' in key && !!key.contextInfo) {
|
|
1368
|
+
key.contextInfo.isGroupStatus = message.groupStatus;
|
|
1369
|
+
}
|
|
1370
|
+
else if (key) {
|
|
1371
|
+
key.contextInfo = {
|
|
1372
|
+
isGroupStatus: message.groupStatus
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
m = { groupStatusMessageV2: { message: m } };
|
|
1376
|
+
delete message.groupStatus;
|
|
1377
|
+
}
|
|
1378
|
+
// Add "spoiler" boolean to set contextInfo.isSpoiler and wrap message into spoilerMessage
|
|
1379
|
+
if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
|
|
1380
|
+
const messageType = Object.keys(m)[0];
|
|
1381
|
+
const key = m[messageType];
|
|
1382
|
+
if ('contextInfo' in key && !!key.contextInfo) {
|
|
1383
|
+
key.contextInfo.isSpoiler = message.spoiler;
|
|
1384
|
+
}
|
|
1385
|
+
else if (key) {
|
|
1386
|
+
key.contextInfo = {
|
|
1387
|
+
isSpoiler: message.spoiler
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
m = { spoilerMessage: { message: m } };
|
|
1391
|
+
delete message.spoiler;
|
|
1392
|
+
}
|
|
1393
|
+
// Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
|
|
1394
|
+
else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
|
|
1395
|
+
if (!m.interactiveMessage) {
|
|
1396
|
+
throw new HttpError('Invalid message type for template', { statusCode: 400 });
|
|
1397
|
+
}
|
|
1398
|
+
m = {
|
|
1399
|
+
templateMessage: {
|
|
1400
|
+
interactiveMessageTemplate: m.interactiveMessage,
|
|
1401
|
+
templateId: message.id || 'template-' + Date.now() // Minimal templateId to satisfy WhatsApp ( ꈍᴗꈍ)
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
delete message.interactiveAsTemplate;
|
|
1405
|
+
}
|
|
1406
|
+
// Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
|
|
1407
|
+
if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
|
|
1408
|
+
m = { ephemeralMessage: { message: m } };
|
|
1409
|
+
delete message.ephemeral;
|
|
1410
|
+
}
|
|
1411
|
+
// Add wrap message into lottieStickerMessage by isLottie boolean
|
|
1412
|
+
if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
|
|
1413
|
+
m = { lottieStickerMessage: { message: m } };
|
|
1414
|
+
}
|
|
1415
|
+
else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
|
1416
|
+
markViewOnce(m);
|
|
1417
|
+
m = { viewOnceMessage: { message: m } };
|
|
1418
|
+
}
|
|
1419
|
+
// Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
|
|
1420
|
+
else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
|
|
1421
|
+
markViewOnce(m);
|
|
1422
|
+
m = { viewOnceMessageV2: { message: m } };
|
|
1423
|
+
delete message.viewOnceV2;
|
|
1424
|
+
}
|
|
1425
|
+
// Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
|
|
1426
|
+
else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
|
|
1427
|
+
markViewOnce(m);
|
|
1428
|
+
m = { viewOnceMessageV2Extension: { message: m } };
|
|
1429
|
+
delete message.viewOnceV2Extension;
|
|
1430
|
+
}
|
|
1431
|
+
if (hasOptionalProperty(message, 'edit')) {
|
|
1432
|
+
m = {
|
|
1433
|
+
protocolMessage: {
|
|
1434
|
+
key: message.edit,
|
|
1435
|
+
editedMessage: m,
|
|
1436
|
+
timestampMs: Date.now(),
|
|
1437
|
+
type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
if (shouldIncludeReportingToken(m)) {
|
|
1442
|
+
m.messageContextInfo = m.messageContextInfo || {};
|
|
1443
|
+
if (!m.messageContextInfo.messageSecret) {
|
|
1444
|
+
m.messageContextInfo.messageSecret = randomBytes(32);
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
return ensureMessageProto(m);
|
|
1448
|
+
};
|
|
1449
|
+
export const generateWAMessageFromContent = (jid, message, options) => {
|
|
1450
|
+
// set timestamp to now
|
|
1451
|
+
// if not specified
|
|
1452
|
+
if (!options.timestamp) {
|
|
1453
|
+
options.timestamp = new Date();
|
|
1454
|
+
}
|
|
1455
|
+
const innerMessage = normalizeMessageContent(message);
|
|
1456
|
+
const messageContextInfo = message.messageContextInfo;
|
|
1457
|
+
const key = getContentType(innerMessage);
|
|
1458
|
+
const timestamp = unixTimestampSeconds(options.timestamp);
|
|
1459
|
+
const isNewsletter = isJidNewsletter(jid);
|
|
1460
|
+
const { quoted, userJid } = options;
|
|
1461
|
+
if (quoted) {
|
|
1462
|
+
const participant = quoted.key.fromMe
|
|
1463
|
+
? userJid // TODO: Add support for LIDs
|
|
1464
|
+
: quoted.participant || quoted.key.participant || quoted.key.remoteJid;
|
|
1465
|
+
let quotedMsg = normalizeMessageContent(quoted.message);
|
|
1466
|
+
const msgType = getContentType(quotedMsg);
|
|
1467
|
+
// strip any redundant properties
|
|
1468
|
+
quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
|
|
1469
|
+
const quotedContent = quotedMsg[msgType];
|
|
1470
|
+
if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
|
|
1471
|
+
delete quotedContent.contextInfo;
|
|
1472
|
+
}
|
|
1473
|
+
const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
|
|
1474
|
+
contextInfo.participant = jidNormalizedUser(participant);
|
|
1475
|
+
contextInfo.stanzaId = quoted.key.id;
|
|
1476
|
+
contextInfo.quotedMessage = quotedMsg;
|
|
1477
|
+
// if a participant is quoted, then it must be a group
|
|
1478
|
+
// hence, remoteJid of group must also be entered
|
|
1479
|
+
if (!isNewsletter && jid !== quoted.key.remoteJid) {
|
|
1480
|
+
contextInfo.remoteJid = quoted.key.remoteJid;
|
|
1481
|
+
}
|
|
1482
|
+
if (contextInfo && innerMessage[key]) {
|
|
1483
|
+
/* @ts-ignore */
|
|
1484
|
+
innerMessage[key].contextInfo = contextInfo;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
if (
|
|
1488
|
+
// if we want to send a disappearing message
|
|
1489
|
+
!!options?.ephemeralExpiration &&
|
|
1490
|
+
// and it's not a protocol message -- delete, toggle disappear message
|
|
1491
|
+
key !== 'protocolMessage' &&
|
|
1492
|
+
// already not converted to disappearing message
|
|
1493
|
+
key !== 'ephemeralMessage' &&
|
|
1494
|
+
// newsletters don't support ephemeral messages
|
|
1495
|
+
!isNewsletter) {
|
|
1496
|
+
/* @ts-ignore */
|
|
1497
|
+
innerMessage[key].contextInfo = {
|
|
1498
|
+
...(innerMessage[key].contextInfo || {}),
|
|
1499
|
+
expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
|
|
1500
|
+
//ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
// Add deviceListMetadata inside messageContextInfo for private chat
|
|
1504
|
+
if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
|
|
1505
|
+
messageContextInfo.deviceListMetadata = {
|
|
1506
|
+
recipientKeyHash: randomBytes(10),
|
|
1507
|
+
recipientTimestamp: unixTimestampSeconds
|
|
1508
|
+
};
|
|
1509
|
+
messageContextInfo.deviceListMetadataVersion = 2;
|
|
1510
|
+
}
|
|
1511
|
+
return WAProto.WebMessageInfo.create({
|
|
1512
|
+
key: {
|
|
1513
|
+
remoteJid: jid,
|
|
1514
|
+
fromMe: true,
|
|
1515
|
+
id: options?.messageId || generateMessageIDV2
|
|
1516
|
+
},
|
|
1517
|
+
message: ensureMessageProto(message),
|
|
1518
|
+
messageTimestamp: timestamp,
|
|
1519
|
+
messageStubParameters: [],
|
|
1520
|
+
participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
|
|
1521
|
+
status: WAMessageStatus.PENDING
|
|
1522
|
+
});
|
|
1523
|
+
};
|
|
1524
|
+
export const generateWAMessage = async (jid, content, options) => {
|
|
1525
|
+
// ensure msg ID is with every log
|
|
1526
|
+
options.logger = options?.logger?.child({ msgId: options.messageId });
|
|
1527
|
+
// Pass jid in the options to generateWAMessageContent
|
|
1528
|
+
if (jid) {
|
|
1529
|
+
options.jid = jid;
|
|
1530
|
+
}
|
|
1531
|
+
return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
|
|
1532
|
+
};
|
|
1533
|
+
/** Get the key to access the true type of content */
|
|
1534
|
+
export const getContentType = (content) => {
|
|
1535
|
+
if (content) {
|
|
1536
|
+
const keys = Object.keys(content);
|
|
1537
|
+
const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
|
|
1538
|
+
return key;
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
/**
|
|
1542
|
+
* Normalizes ephemeral, view once messages to regular message content
|
|
1543
|
+
* Eg. image messages in ephemeral messages, in view once messages etc.
|
|
1544
|
+
* @param content
|
|
1545
|
+
* @returns
|
|
1546
|
+
*/
|
|
1547
|
+
export const normalizeMessageContent = (content) => {
|
|
1548
|
+
if (!content) {
|
|
1549
|
+
return undefined;
|
|
1550
|
+
}
|
|
1551
|
+
// set max iterations to prevent an infinite loop
|
|
1552
|
+
for (let i = 0; i < 5; i++) {
|
|
1553
|
+
const inner = getFutureProofMessage(content);
|
|
1554
|
+
if (!inner) {
|
|
1555
|
+
break;
|
|
1556
|
+
}
|
|
1557
|
+
content = inner.message;
|
|
1558
|
+
}
|
|
1559
|
+
return content;
|
|
1560
|
+
// Add all futureProofMessage into getFutureProofMessage
|
|
1561
|
+
function getFutureProofMessage(message) {
|
|
1562
|
+
return (message?.acp2SettingMessage ||
|
|
1563
|
+
message?.associatedChildMessage ||
|
|
1564
|
+
message?.audioStickerMessage ||
|
|
1565
|
+
message?.botForwardedMessage ||
|
|
1566
|
+
message?.botGroupParticipantMessage ||
|
|
1567
|
+
message?.botInvokeMessage ||
|
|
1568
|
+
message?.botPlatformRegistrationSuccessMessage ||
|
|
1569
|
+
message?.botTaskMessage ||
|
|
1570
|
+
message?.documentWithCaptionMessage ||
|
|
1571
|
+
message?.editedMessage ||
|
|
1572
|
+
message?.ephemeralMessage ||
|
|
1573
|
+
message?.eventCoverImage ||
|
|
1574
|
+
message?.groupMentionedMessage ||
|
|
1575
|
+
message?.groupStatusMentionMessage ||
|
|
1576
|
+
message?.groupStatusMessage ||
|
|
1577
|
+
message?.groupStatusMessageV2 ||
|
|
1578
|
+
message?.limitSharingMessage ||
|
|
1579
|
+
message?.lottieStickerMessage ||
|
|
1580
|
+
message?.newsletterAdminProfileMessage ||
|
|
1581
|
+
message?.newsletterAdminProfileMessageV2 ||
|
|
1582
|
+
message?.newsletterAdminProfileStatusMessage ||
|
|
1583
|
+
message?.newsletterScheduledMessage ||
|
|
1584
|
+
message?.pollCreationMessageV4 ||
|
|
1585
|
+
message?.pollCreationOptionImageMessage ||
|
|
1586
|
+
message?.questionMessage ||
|
|
1587
|
+
message?.questionReplyMessage ||
|
|
1588
|
+
message?.spoilerMessage ||
|
|
1589
|
+
message?.statusAddYours ||
|
|
1590
|
+
message?.statusMentionMessage ||
|
|
1591
|
+
message?.viewOnceMessage ||
|
|
1592
|
+
message?.viewOnceMessageV2 ||
|
|
1593
|
+
message?.viewOnceMessageV2Extension);
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
/**
|
|
1597
|
+
* Extract the true message content from a message
|
|
1598
|
+
* Eg. extracts the inner message from a disappearing message/view once message
|
|
1599
|
+
*/
|
|
1600
|
+
export const extractMessageContent = (content) => {
|
|
1601
|
+
const extractFromTemplateMessage = (msg) => {
|
|
1602
|
+
if (msg.imageMessage) {
|
|
1603
|
+
return { imageMessage: msg.imageMessage };
|
|
1604
|
+
}
|
|
1605
|
+
else if (msg.documentMessage) {
|
|
1606
|
+
return { documentMessage: msg.documentMessage };
|
|
1607
|
+
}
|
|
1608
|
+
else if (msg.videoMessage) {
|
|
1609
|
+
return { videoMessage: msg.videoMessage };
|
|
1610
|
+
}
|
|
1611
|
+
else if (msg.locationMessage) {
|
|
1612
|
+
return { locationMessage: msg.locationMessage };
|
|
1613
|
+
}
|
|
1614
|
+
else {
|
|
1615
|
+
return {
|
|
1616
|
+
conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
content = normalizeMessageContent(content);
|
|
1621
|
+
if (content?.buttonsMessage) {
|
|
1622
|
+
return extractFromTemplateMessage(content.buttonsMessage);
|
|
1623
|
+
}
|
|
1624
|
+
if (content?.templateMessage?.hydratedFourRowTemplate) {
|
|
1625
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
|
|
1626
|
+
}
|
|
1627
|
+
if (content?.templateMessage?.hydratedTemplate) {
|
|
1628
|
+
return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
|
|
1629
|
+
}
|
|
1630
|
+
if (content?.templateMessage?.fourRowTemplate) {
|
|
1631
|
+
return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
|
|
1632
|
+
}
|
|
1633
|
+
return content;
|
|
1634
|
+
};
|
|
1635
|
+
/**
|
|
1636
|
+
* Returns the device predicted by message ID
|
|
1637
|
+
*/
|
|
1638
|
+
export const getDevice = (id) => /^3A.{18}$/.test(id)
|
|
1639
|
+
? 'ios'
|
|
1640
|
+
: /^3E.{20}$/.test(id)
|
|
1641
|
+
? 'web'
|
|
1642
|
+
: /^(.{21}|.{32})$/.test(id)
|
|
1643
|
+
? 'android'
|
|
1644
|
+
: /^(3F|.{18}$)/.test(id)
|
|
1645
|
+
? 'desktop'
|
|
1646
|
+
: 'unknown';
|
|
1647
|
+
/** Upserts a receipt in the message */
|
|
1648
|
+
export const updateMessageWithReceipt = (msg, receipt) => {
|
|
1649
|
+
msg.userReceipt = msg.userReceipt || [];
|
|
1650
|
+
const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
|
|
1651
|
+
if (recp) {
|
|
1652
|
+
Object.assign(recp, receipt);
|
|
1653
|
+
}
|
|
1654
|
+
else {
|
|
1655
|
+
msg.userReceipt.push(receipt);
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
/** Update the message with a new reaction */
|
|
1659
|
+
export const updateMessageWithReaction = (msg, reaction) => {
|
|
1660
|
+
const authorID = getKeyAuthor(reaction.key);
|
|
1661
|
+
const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
|
|
1662
|
+
reaction.text = reaction.text || '';
|
|
1663
|
+
reactions.push(reaction);
|
|
1664
|
+
msg.reactions = reactions;
|
|
1665
|
+
};
|
|
1666
|
+
/** Update the message with a new poll update */
|
|
1667
|
+
export const updateMessageWithPollUpdate = (msg, update) => {
|
|
1668
|
+
const authorID = getKeyAuthor(update.pollUpdateMessageKey);
|
|
1669
|
+
const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
|
|
1670
|
+
if (update.vote?.selectedOptions?.length) {
|
|
1671
|
+
reactions.push(update);
|
|
1672
|
+
}
|
|
1673
|
+
msg.pollUpdates = reactions;
|
|
1674
|
+
};
|
|
1675
|
+
/** Update the message with a new event response */
|
|
1676
|
+
export const updateMessageWithEventResponse = (msg, update) => {
|
|
1677
|
+
const authorID = getKeyAuthor(update.eventResponseMessageKey);
|
|
1678
|
+
const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
|
|
1679
|
+
responses.push(update);
|
|
1680
|
+
msg.eventResponses = responses;
|
|
1681
|
+
};
|
|
1682
|
+
/**
|
|
1683
|
+
* Aggregates all poll updates in a poll.
|
|
1684
|
+
* @param msg the poll creation message
|
|
1685
|
+
* @param meId your jid
|
|
1686
|
+
* @returns A list of options & their voters
|
|
1687
|
+
*/
|
|
1688
|
+
export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
|
|
1689
|
+
const opts = message?.pollCreationMessage?.options ||
|
|
1690
|
+
message?.pollCreationMessageV2?.options ||
|
|
1691
|
+
message?.pollCreationMessageV3?.options ||
|
|
1692
|
+
[];
|
|
1693
|
+
const voteHashMap = opts.reduce((acc, opt) => {
|
|
1694
|
+
const hash = sha256(Buffer.from(opt.optionName || '')).toString();
|
|
1695
|
+
acc[hash] = {
|
|
1696
|
+
name: opt.optionName || '',
|
|
1697
|
+
voters: []
|
|
1698
|
+
};
|
|
1699
|
+
return acc;
|
|
1700
|
+
}, {});
|
|
1701
|
+
for (const update of pollUpdates || []) {
|
|
1702
|
+
const { vote } = update;
|
|
1703
|
+
if (!vote) {
|
|
1704
|
+
continue;
|
|
1705
|
+
}
|
|
1706
|
+
for (const option of vote.selectedOptions || []) {
|
|
1707
|
+
const hash = option.toString();
|
|
1708
|
+
let data = voteHashMap[hash];
|
|
1709
|
+
if (!data) {
|
|
1710
|
+
voteHashMap[hash] = {
|
|
1711
|
+
name: 'Unknown',
|
|
1712
|
+
voters: []
|
|
1713
|
+
};
|
|
1714
|
+
data = voteHashMap[hash];
|
|
1715
|
+
}
|
|
1716
|
+
voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
return Object.values(voteHashMap);
|
|
1720
|
+
}
|
|
1721
|
+
/**
|
|
1722
|
+
* Aggregates all event responses in an event message.
|
|
1723
|
+
* @param msg the event creation message
|
|
1724
|
+
* @param meId your jid
|
|
1725
|
+
* @returns A list of response types & their responders
|
|
1726
|
+
*/
|
|
1727
|
+
export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
|
|
1728
|
+
const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
|
|
1729
|
+
const responseMap = {};
|
|
1730
|
+
for (const type of responseTypes) {
|
|
1731
|
+
responseMap[type] = {
|
|
1732
|
+
response: type,
|
|
1733
|
+
responders: []
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
for (const update of eventResponses || []) {
|
|
1737
|
+
const responseType = update.eventResponse || 'UNKNOWN';
|
|
1738
|
+
if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
|
|
1739
|
+
responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
return Object.values(responseMap);
|
|
1743
|
+
}
|
|
1744
|
+
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
|
|
1745
|
+
export const aggregateMessageKeysNotFromMe = (keys) => {
|
|
1746
|
+
const keyMap = {};
|
|
1747
|
+
for (const { remoteJid, id, participant, fromMe } of keys) {
|
|
1748
|
+
if (!fromMe) {
|
|
1749
|
+
const uqKey = `${remoteJid}:${participant || ''}`;
|
|
1750
|
+
if (!keyMap[uqKey]) {
|
|
1751
|
+
keyMap[uqKey] = {
|
|
1752
|
+
jid: remoteJid,
|
|
1753
|
+
participant: participant,
|
|
1754
|
+
messageIds: []
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
keyMap[uqKey].messageIds.push(id);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
return Object.values(keyMap);
|
|
1761
|
+
};
|
|
1762
|
+
const REUPLOAD_REQUIRED_STATUS = [410, 404];
|
|
1763
|
+
/**
|
|
1764
|
+
* Downloads the given message. Throws an error if it's not a media message
|
|
1765
|
+
*/
|
|
1766
|
+
export const downloadMediaMessage = async (message, type, options, ctx) => {
|
|
1767
|
+
const result = await downloadMsg().catch(async (error) => {
|
|
1768
|
+
if (ctx &&
|
|
1769
|
+
typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
|
|
1770
|
+
REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
|
|
1771
|
+
ctx.logger.info({ key: message.key }, 'sending reupload media request...');
|
|
1772
|
+
// request reupload
|
|
1773
|
+
message = await ctx.reuploadRequest(message);
|
|
1774
|
+
const result = await downloadMsg();
|
|
1775
|
+
return result;
|
|
1776
|
+
}
|
|
1777
|
+
throw error;
|
|
1778
|
+
});
|
|
1779
|
+
return result;
|
|
1780
|
+
async function downloadMsg() {
|
|
1781
|
+
const mContent = extractMessageContent(message.message);
|
|
1782
|
+
if (!mContent) {
|
|
1783
|
+
throw new HttpError('No message present', { statusCode: 400, data: message });
|
|
1784
|
+
}
|
|
1785
|
+
const contentType = getContentType(mContent);
|
|
1786
|
+
let mediaType = contentType?.replace('Message', '');
|
|
1787
|
+
const media = mContent[contentType];
|
|
1788
|
+
if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
|
|
1789
|
+
throw new HttpError(`"${contentType}" message is not a media message`);
|
|
1790
|
+
}
|
|
1791
|
+
let download;
|
|
1792
|
+
if ('thumbnailDirectPath' in media && !('url' in media)) {
|
|
1793
|
+
download = {
|
|
1794
|
+
directPath: media.thumbnailDirectPath,
|
|
1795
|
+
mediaKey: media.mediaKey
|
|
1796
|
+
};
|
|
1797
|
+
mediaType = 'thumbnail-link';
|
|
1798
|
+
}
|
|
1799
|
+
else {
|
|
1800
|
+
download = media;
|
|
1801
|
+
}
|
|
1802
|
+
const stream = await downloadContentFromMessage(download, mediaType, options);
|
|
1803
|
+
if (type === 'buffer') {
|
|
1804
|
+
const bufferArray = [];
|
|
1805
|
+
for await (const chunk of stream) {
|
|
1806
|
+
bufferArray.push(chunk);
|
|
1807
|
+
}
|
|
1808
|
+
return Buffer.concat(bufferArray);
|
|
1809
|
+
}
|
|
1810
|
+
return stream;
|
|
1811
|
+
}
|
|
1812
|
+
};
|
|
1813
|
+
/** Checks whether the given message is a media message; if it is returns the inner content */
|
|
1814
|
+
export const assertMediaContent = (content) => {
|
|
1815
|
+
content = extractMessageContent(content);
|
|
1816
|
+
const mediaContent = content?.documentMessage ||
|
|
1817
|
+
content?.imageMessage ||
|
|
1818
|
+
content?.videoMessage ||
|
|
1819
|
+
content?.audioMessage ||
|
|
1820
|
+
content?.stickerMessage;
|
|
1821
|
+
if (!mediaContent) {
|
|
1822
|
+
throw new HttpError('given message is not a media message', { statusCode: 400, data: content });
|
|
1823
|
+
}
|
|
1824
|
+
return mediaContent;
|
|
1825
|
+
};
|
|
1826
|
+
/**
|
|
1827
|
+
* Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
|
|
1828
|
+
* or ANIM/ANMF chunks
|
|
1829
|
+
*/
|
|
1830
|
+
const isAnimatedWebP = (buffer) => {
|
|
1831
|
+
// WebP must start with RIFF....WEBP
|
|
1832
|
+
if (buffer.length < 12 ||
|
|
1833
|
+
buffer[0] !== 0x52 ||
|
|
1834
|
+
buffer[1] !== 0x49 ||
|
|
1835
|
+
buffer[2] !== 0x46 ||
|
|
1836
|
+
buffer[3] !== 0x46 ||
|
|
1837
|
+
buffer[8] !== 0x57 ||
|
|
1838
|
+
buffer[9] !== 0x45 ||
|
|
1839
|
+
buffer[10] !== 0x42 ||
|
|
1840
|
+
buffer[11] !== 0x50) {
|
|
1841
|
+
return false;
|
|
1842
|
+
}
|
|
1843
|
+
;
|
|
1844
|
+
// Parse chunks starting after RIFF header (12 bytes)
|
|
1845
|
+
let offset = 12;
|
|
1846
|
+
while (offset < buffer.length - 8) {
|
|
1847
|
+
const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
|
|
1848
|
+
const chunkSize = buffer.readUInt32LE(offset + 4);
|
|
1849
|
+
if (chunkFourCC === 'VP8X') {
|
|
1850
|
+
// VP8X extended header, check animation flag (bit 1 at offset+8)
|
|
1851
|
+
const flagsOffset = offset + 8;
|
|
1852
|
+
if (flagsOffset < buffer.length) {
|
|
1853
|
+
const flags = buffer[flagsOffset];
|
|
1854
|
+
if (flags & 0x02) {
|
|
1855
|
+
return true;
|
|
1856
|
+
}
|
|
1857
|
+
;
|
|
1858
|
+
}
|
|
1859
|
+
;
|
|
1860
|
+
}
|
|
1861
|
+
else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
|
|
1862
|
+
// ANIM or ANMF chunks indicate animation
|
|
1863
|
+
return true;
|
|
1864
|
+
}
|
|
1865
|
+
;
|
|
1866
|
+
// Move to next chunk (chunk size + 8 bytes header, padded to even)
|
|
1867
|
+
offset += 8 + chunkSize + (chunkSize % 2);
|
|
1868
|
+
}
|
|
1869
|
+
;
|
|
1870
|
+
return false;
|
|
1871
|
+
};
|
|
1872
|
+
/**
|
|
1873
|
+
* Checks if a buffer is a WebP file
|
|
1874
|
+
*/
|
|
1875
|
+
const isWebPBuffer = (buffer) => {
|
|
1876
|
+
return (buffer.length >= 12 &&
|
|
1877
|
+
buffer[0] === 0x52 &&
|
|
1878
|
+
buffer[1] === 0x49 &&
|
|
1879
|
+
buffer[2] === 0x46 &&
|
|
1880
|
+
buffer[3] === 0x46 &&
|
|
1881
|
+
buffer[8] === 0x57 &&
|
|
1882
|
+
buffer[9] === 0x45 &&
|
|
1883
|
+
buffer[10] === 0x42 &&
|
|
1884
|
+
buffer[11] === 0x50);
|
|
1885
|
+
};
|
|
1886
|
+
/**
|
|
1887
|
+
* Determines whether a message should include a Biz Binary Node.
|
|
1888
|
+
* A Biz Binary Node is added only for interactive messages
|
|
1889
|
+
* such as buttons or other supported interactive types.
|
|
1890
|
+
*/
|
|
1891
|
+
export const shouldIncludeBizBinaryNode = (message) => !!(message.buttonsMessage ||
|
|
1892
|
+
message.listMessage ||
|
|
1893
|
+
message.templateMessage ||
|
|
1894
|
+
(message.interactiveMessage &&
|
|
1895
|
+
message.interactiveMessage.nativeFlowMessage));
|
|
1896
|
+
export const isViewOnceMessage = (message) => {
|
|
1897
|
+
// Fast path, check viewOnce flags directly
|
|
1898
|
+
if (message?.viewOnce === true ||
|
|
1899
|
+
message?.viewOnceMessage ||
|
|
1900
|
+
message?.viewOnceMessageV2 ||
|
|
1901
|
+
message?.viewOnceMessageV2Extension)
|
|
1902
|
+
return true;
|
|
1903
|
+
const innerMsg = normalizeMessageContent(message);
|
|
1904
|
+
const msgType = getContentType(innerMsg);
|
|
1905
|
+
const msgCtn = innerMsg?.[msgType];
|
|
1906
|
+
return msgCtn?.viewOnce === true;
|
|
1907
|
+
};
|