@japofc/baileys 2.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/NOTICE.md +111 -0
- package/README.md +1254 -0
- package/WAProto/index.d.ts +9 -0
- package/WAProto/index.js +142276 -0
- package/engine-requirements.js +13 -0
- package/lib/Builders/A2UI.d.ts +242 -0
- package/lib/Builders/A2UI.js +308 -0
- package/lib/Builders/AIRich.d.ts +105 -0
- package/lib/Builders/AIRich.js +2286 -0
- package/lib/Builders/Button.d.ts +103 -0
- package/lib/Builders/Button.js +883 -0
- package/lib/Builders/ButtonV2.d.ts +28 -0
- package/lib/Builders/ButtonV2.js +144 -0
- package/lib/Builders/ButtonV3.d.ts +25 -0
- package/lib/Builders/ButtonV3.js +184 -0
- package/lib/Builders/Carousel.d.ts +22 -0
- package/lib/Builders/Carousel.js +111 -0
- package/lib/Builders/JapBaileys.d.ts +34 -0
- package/lib/Builders/JapBaileys.js +108 -0
- package/lib/Builders/Poll.d.ts +25 -0
- package/lib/Builders/Poll.js +128 -0
- package/lib/Builders/index.d.ts +17 -0
- package/lib/Builders/index.js +11 -0
- package/lib/Builders/shared.d.ts +67 -0
- package/lib/Builders/shared.js +652 -0
- package/lib/Defaults/index.d.ts +154 -0
- package/lib/Defaults/index.js +178 -0
- package/lib/Framework/Bot.d.ts +61 -0
- package/lib/Framework/Bot.js +248 -0
- package/lib/Framework/Context.d.ts +21 -0
- package/lib/Framework/Context.js +89 -0
- package/lib/Framework/MediaManager.d.ts +17 -0
- package/lib/Framework/MediaManager.js +151 -0
- package/lib/Framework/SessionManager.d.ts +13 -0
- package/lib/Framework/SessionManager.js +33 -0
- package/lib/Framework/StatsManager.d.ts +26 -0
- package/lib/Framework/StatsManager.js +119 -0
- package/lib/Framework/Store/SQLiteStore.d.ts +11 -0
- package/lib/Framework/Store/SQLiteStore.js +73 -0
- package/lib/Framework/index.d.ts +9 -0
- package/lib/Framework/index.js +10 -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-session-builder.d.ts +7 -0
- package/lib/Signal/Group/group-session-builder.js +29 -0
- package/lib/Signal/Group/group_cipher.d.ts +10 -0
- package/lib/Signal/Group/group_cipher.js +81 -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 +430 -0
- package/lib/Signal/lid-mapping.d.ts +20 -0
- package/lib/Signal/lid-mapping.js +276 -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 +53 -0
- package/lib/Socket/business.d.ts +395 -0
- package/lib/Socket/business.js +379 -0
- package/lib/Socket/chats.d.ts +136 -0
- package/lib/Socket/chats.js +1327 -0
- package/lib/Socket/communities.d.ts +562 -0
- package/lib/Socket/communities.js +439 -0
- package/lib/Socket/dugong.d.ts +117 -0
- package/lib/Socket/dugong.js +798 -0
- package/lib/Socket/groups.d.ts +285 -0
- package/lib/Socket/groups.js +354 -0
- package/lib/Socket/index.d.ts +585 -0
- package/lib/Socket/index.js +52 -0
- package/lib/Socket/messages-recv.d.ts +333 -0
- package/lib/Socket/messages-recv.js +1781 -0
- package/lib/Socket/messages-send.d.ts +353 -0
- package/lib/Socket/messages-send.js +1524 -0
- package/lib/Socket/mex.d.ts +1 -0
- package/lib/Socket/mex.js +41 -0
- package/lib/Socket/newsletter.d.ts +286 -0
- package/lib/Socket/newsletter.js +364 -0
- package/lib/Socket/socket.d.ts +60 -0
- package/lib/Socket/socket.js +1012 -0
- package/lib/Socket/username.d.ts +82 -0
- package/lib/Socket/username.js +159 -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 +62 -0
- package/lib/Store/make-in-memory-store.js +428 -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/Types/Auth.d.ts +117 -0
- package/lib/Types/Auth.js +1 -0
- package/lib/Types/Bussines.d.ts +25 -0
- package/lib/Types/Call.d.ts +15 -0
- package/lib/Types/Call.js +1 -0
- package/lib/Types/Chat.d.ts +124 -0
- package/lib/Types/Chat.js +7 -0
- package/lib/Types/Contact.d.ts +26 -0
- package/lib/Types/Contact.js +1 -0
- package/lib/Types/Events.d.ts +256 -0
- package/lib/Types/Events.js +1 -0
- package/lib/Types/GroupMetadata.d.ts +71 -0
- package/lib/Types/GroupMetadata.js +1 -0
- package/lib/Types/Label.d.ts +5 -0
- package/lib/Types/Label.js +24 -0
- package/lib/Types/LabelAssociation.d.ts +6 -0
- package/lib/Types/LabelAssociation.js +6 -0
- package/lib/Types/Message.d.ts +62 -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 +79 -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 +87 -0
- package/lib/Types/Signal.js +1 -0
- package/lib/Types/Socket.d.ts +138 -0
- package/lib/Types/Socket.js +1 -0
- package/lib/Types/State.d.ts +8 -0
- package/lib/Types/State.js +55 -0
- package/lib/Types/USync.d.ts +26 -0
- package/lib/Types/index.d.ts +68 -0
- package/lib/Types/index.js +27 -0
- package/lib/Utils/MessageBuilder.d.ts +2 -0
- package/lib/Utils/MessageBuilder.js +2 -0
- package/lib/Utils/PersistentStore.d.ts +60 -0
- package/lib/Utils/PersistentStore.js +592 -0
- package/lib/Utils/anti-delete.d.ts +74 -0
- package/lib/Utils/anti-delete.js +221 -0
- package/lib/Utils/auth-secure.d.ts +86 -0
- package/lib/Utils/auth-secure.js +764 -0
- package/lib/Utils/auth-utils.d.ts +57 -0
- package/lib/Utils/auth-utils.js +306 -0
- package/lib/Utils/auto-reply.d.ts +47 -0
- package/lib/Utils/auto-reply.js +157 -0
- package/lib/Utils/baileys-event-stream.d.ts +8 -0
- package/lib/Utils/baileys-event-stream.js +62 -0
- package/lib/Utils/browser-utils.d.ts +8 -0
- package/lib/Utils/browser-utils.js +27 -0
- package/lib/Utils/business.d.ts +49 -0
- package/lib/Utils/business.js +239 -0
- package/lib/Utils/button-helper-utils.d.ts +53 -0
- package/lib/Utils/button-helper-utils.js +312 -0
- package/lib/Utils/button-sender.d.ts +54 -0
- package/lib/Utils/button-sender.js +822 -0
- package/lib/Utils/chat-control.d.ts +159 -0
- package/lib/Utils/chat-control.js +230 -0
- package/lib/Utils/chat-history-helpers.d.ts +21 -0
- package/lib/Utils/chat-history-helpers.js +70 -0
- package/lib/Utils/chat-utils.d.ts +407 -0
- package/lib/Utils/chat-utils.js +885 -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 +41 -0
- package/lib/Utils/crypto.js +147 -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 +635 -0
- package/lib/Utils/generics.d.ts +69 -0
- package/lib/Utils/generics.js +438 -0
- package/lib/Utils/history-share.d.ts +11 -0
- package/lib/Utils/history-share.js +70 -0
- package/lib/Utils/history.d.ts +90 -0
- package/lib/Utils/history.js +146 -0
- package/lib/Utils/humanizer.d.ts +12 -0
- package/lib/Utils/humanizer.js +73 -0
- package/lib/Utils/identity-change-handler.d.ts +13 -0
- package/lib/Utils/identity-change-handler.js +49 -0
- package/lib/Utils/index.d.ts +57 -0
- package/lib/Utils/index.js +56 -0
- package/lib/Utils/jid-tools.d.ts +6 -0
- package/lib/Utils/jid-tools.js +77 -0
- package/lib/Utils/link-preview.d.ts +12 -0
- package/lib/Utils/link-preview.js +84 -0
- package/lib/Utils/logger.d.ts +4 -0
- package/lib/Utils/logger.js +2 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +26 -0
- package/lib/Utils/make-mutex.d.ts +6 -0
- package/lib/Utils/make-mutex.js +32 -0
- package/lib/Utils/media-messages.d.ts +18 -0
- package/lib/Utils/media-messages.js +70 -0
- package/lib/Utils/media-set.d.ts +13 -0
- package/lib/Utils/media-set.js +171 -0
- package/lib/Utils/message-kind.d.ts +32 -0
- package/lib/Utils/message-kind.js +136 -0
- package/lib/Utils/message-retry-manager.d.ts +79 -0
- package/lib/Utils/message-retry-manager.js +264 -0
- package/lib/Utils/message-search.d.ts +44 -0
- package/lib/Utils/message-search.js +188 -0
- package/lib/Utils/messages-media.d.ts +135 -0
- package/lib/Utils/messages-media.js +868 -0
- package/lib/Utils/messages.d.ts +44 -0
- package/lib/Utils/messages.js +2326 -0
- package/lib/Utils/meta-ai.d.ts +13 -0
- package/lib/Utils/meta-ai.js +74 -0
- package/lib/Utils/mini-app.d.ts +35 -0
- package/lib/Utils/mini-app.js +213 -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 +9 -0
- package/lib/Utils/offline-node-processor.js +39 -0
- package/lib/Utils/past-participants.d.ts +14 -0
- package/lib/Utils/past-participants.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 +82 -0
- package/lib/Utils/process-message.js +808 -0
- package/lib/Utils/qr-render.d.ts +59 -0
- package/lib/Utils/qr-render.js +179 -0
- package/lib/Utils/qrcodegen.d.ts +79 -0
- package/lib/Utils/qrcodegen.js +848 -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 +444 -0
- package/lib/Utils/router.d.ts +37 -0
- package/lib/Utils/router.js +165 -0
- package/lib/Utils/scheduled-posts.d.ts +30 -0
- package/lib/Utils/scheduled-posts.js +110 -0
- package/lib/Utils/scheduling.d.ts +42 -0
- package/lib/Utils/scheduling.js +139 -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/status.d.ts +50 -0
- package/lib/Utils/status.js +107 -0
- package/lib/Utils/stickerpack.d.ts +51 -0
- package/lib/Utils/stickerpack.js +274 -0
- package/lib/Utils/sync-action-utils.d.ts +2 -0
- package/lib/Utils/sync-action-utils.js +48 -0
- package/lib/Utils/tag.d.ts +12 -0
- package/lib/Utils/tag.js +44 -0
- package/lib/Utils/tc-token-utils.d.ts +29 -0
- package/lib/Utils/tc-token-utils.js +162 -0
- package/lib/Utils/templates.d.ts +76 -0
- package/lib/Utils/templates.js +150 -0
- package/lib/Utils/transcribe.d.ts +12 -0
- package/lib/Utils/transcribe.js +107 -0
- package/lib/Utils/use-cache-manager-auth-state.d.ts +13 -0
- package/lib/Utils/use-cache-manager-auth-state.js +81 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
- package/lib/Utils/use-multi-file-auth-state.js +166 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
- package/lib/Utils/use-single-file-auth-state.js +113 -0
- package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
- package/lib/Utils/use-sqlite-auth-state.js +169 -0
- package/lib/Utils/validate-connection.d.ts +42 -0
- package/lib/Utils/validate-connection.js +198 -0
- package/lib/Utils/vcard.d.ts +58 -0
- package/lib/Utils/vcard.js +104 -0
- package/lib/Utils/voice-note.d.ts +15 -0
- package/lib/Utils/voice-note.js +63 -0
- package/lib/VoIP/audio-feeder.d.ts +18 -0
- package/lib/VoIP/audio-feeder.js +160 -0
- package/lib/VoIP/call-recorder.d.ts +13 -0
- package/lib/VoIP/call-recorder.js +73 -0
- package/lib/VoIP/index.d.ts +86 -0
- package/lib/VoIP/index.js +611 -0
- package/lib/VoIP/relay-transport.d.ts +43 -0
- package/lib/VoIP/relay-transport.js +563 -0
- package/lib/VoIP/signaling.d.ts +26 -0
- package/lib/VoIP/signaling.js +662 -0
- package/lib/VoIP/types.d.ts +69 -0
- package/lib/VoIP/types.js +17 -0
- package/lib/VoIP/wasm-engine.d.ts +120 -0
- package/lib/VoIP/wasm-engine.js +1358 -0
- package/lib/VoIP/worker-bootstrap.d.ts +4 -0
- package/lib/VoIP/worker-bootstrap.js +1046 -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 +74 -0
- package/lib/WABinary/generic-utils.js +276 -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 +19 -0
- package/lib/WABinary/types.js +1 -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 +29 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -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 +7 -0
- package/lib/WAUSync/Protocols/index.js +7 -0
- package/lib/WAUSync/USyncQuery.d.ts +20 -0
- package/lib/WAUSync/USyncQuery.js +121 -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/assets/wasm/loader.d.ts +5 -0
- package/lib/assets/wasm/loader.js +5 -0
- package/lib/assets/wasm/whatsapp.wasm +0 -0
- package/lib/assets/wasm/worker-modules.d.ts +5 -0
- package/lib/assets/wasm/worker-modules.js +273 -0
- package/lib/index.d.ts +18 -0
- package/lib/index.js +23 -0
- package/package.json +180 -0
- package/postinstall-banner.js +82 -0
|
@@ -0,0 +1,1327 @@
|
|
|
1
|
+
import NodeCache from '@cacheable/node-cache';
|
|
2
|
+
import { Boom } from '@hapi/boom';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
|
|
5
|
+
import { ALL_WA_PATCH_NAMES, WAMessageStubType } from '../Types/index.js';
|
|
6
|
+
import { SyncState } from '../Types/State.js';
|
|
7
|
+
import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
|
|
8
|
+
import { makeMutex } from '../Utils/make-mutex.js';
|
|
9
|
+
import processMessage from '../Utils/process-message.js';
|
|
10
|
+
import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
|
|
11
|
+
import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
12
|
+
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
|
|
13
|
+
import { makeSocket } from './socket.js';
|
|
14
|
+
export const makeChatsSocket = (config) => {
|
|
15
|
+
const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
|
|
16
|
+
const sock = makeSocket(config);
|
|
17
|
+
const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
|
|
18
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
19
|
+
let privacySettings;
|
|
20
|
+
/** Server-assigned AB props for protocol behavior. */
|
|
21
|
+
const serverProps = {
|
|
22
|
+
/** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
|
|
23
|
+
privacyTokenOn1to1: true,
|
|
24
|
+
/** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
|
|
25
|
+
profilePicPrivacyToken: true,
|
|
26
|
+
/** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
|
|
27
|
+
lidTrustedTokenIssueToLid: false
|
|
28
|
+
};
|
|
29
|
+
let syncState = SyncState.Connecting;
|
|
30
|
+
/** this mutex ensures that messages are processed in order */
|
|
31
|
+
const messageMutex = makeMutex();
|
|
32
|
+
/** this mutex ensures that receipts are processed in order */
|
|
33
|
+
const receiptMutex = makeMutex();
|
|
34
|
+
/** this mutex ensures that app state patches are processed in order */
|
|
35
|
+
const appStatePatchMutex = makeMutex();
|
|
36
|
+
/** this mutex ensures that notifications are processed in order */
|
|
37
|
+
const notificationMutex = makeMutex();
|
|
38
|
+
// Timeout for AwaitingInitialSync state
|
|
39
|
+
let awaitingSyncTimeout;
|
|
40
|
+
// In-memory history sync completion tracking (resets on reconnection)
|
|
41
|
+
const historySyncStatus = {
|
|
42
|
+
initialBootstrapComplete: false,
|
|
43
|
+
recentSyncComplete: false
|
|
44
|
+
};
|
|
45
|
+
let historySyncPausedTimeout;
|
|
46
|
+
// Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
|
|
47
|
+
// When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
|
|
48
|
+
const blockedCollections = new Set();
|
|
49
|
+
const placeholderResendCache = config.placeholderResendCache ||
|
|
50
|
+
new NodeCache({
|
|
51
|
+
stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
|
|
52
|
+
useClones: false
|
|
53
|
+
});
|
|
54
|
+
/** helper function to fetch the given app state sync key */
|
|
55
|
+
const getAppStateSyncKey = async (keyId) => {
|
|
56
|
+
const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
|
|
57
|
+
return key;
|
|
58
|
+
};
|
|
59
|
+
const fetchPrivacySettings = async (force = false) => {
|
|
60
|
+
if (!privacySettings || force) {
|
|
61
|
+
const { content } = await query({
|
|
62
|
+
tag: 'iq',
|
|
63
|
+
attrs: {
|
|
64
|
+
xmlns: 'privacy',
|
|
65
|
+
to: S_WHATSAPP_NET,
|
|
66
|
+
type: 'get'
|
|
67
|
+
},
|
|
68
|
+
content: [{ tag: 'privacy', attrs: {} }]
|
|
69
|
+
});
|
|
70
|
+
privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
|
|
71
|
+
}
|
|
72
|
+
return privacySettings;
|
|
73
|
+
};
|
|
74
|
+
/** helper function to run a privacy IQ query */
|
|
75
|
+
const privacyQuery = async (name, value) => {
|
|
76
|
+
await query({
|
|
77
|
+
tag: 'iq',
|
|
78
|
+
attrs: {
|
|
79
|
+
xmlns: 'privacy',
|
|
80
|
+
to: S_WHATSAPP_NET,
|
|
81
|
+
type: 'set'
|
|
82
|
+
},
|
|
83
|
+
content: [
|
|
84
|
+
{
|
|
85
|
+
tag: 'privacy',
|
|
86
|
+
attrs: {},
|
|
87
|
+
content: [
|
|
88
|
+
{
|
|
89
|
+
tag: 'category',
|
|
90
|
+
attrs: { name, value }
|
|
91
|
+
}
|
|
92
|
+
]
|
|
93
|
+
}
|
|
94
|
+
]
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
const updateMessagesPrivacy = async (value) => {
|
|
98
|
+
await privacyQuery('messages', value);
|
|
99
|
+
};
|
|
100
|
+
const updateCallPrivacy = async (value) => {
|
|
101
|
+
await privacyQuery('calladd', value);
|
|
102
|
+
};
|
|
103
|
+
const updateLastSeenPrivacy = async (value) => {
|
|
104
|
+
await privacyQuery('last', value);
|
|
105
|
+
};
|
|
106
|
+
const updateOnlinePrivacy = async (value) => {
|
|
107
|
+
await privacyQuery('online', value);
|
|
108
|
+
};
|
|
109
|
+
const updateProfilePicturePrivacy = async (value) => {
|
|
110
|
+
await privacyQuery('profile', value);
|
|
111
|
+
};
|
|
112
|
+
const updateStatusPrivacy = async (value) => {
|
|
113
|
+
await privacyQuery('status', value);
|
|
114
|
+
};
|
|
115
|
+
const updateReadReceiptsPrivacy = async (value) => {
|
|
116
|
+
await privacyQuery('readreceipts', value);
|
|
117
|
+
};
|
|
118
|
+
const updateGroupsAddPrivacy = async (value) => {
|
|
119
|
+
await privacyQuery('groupadd', value);
|
|
120
|
+
};
|
|
121
|
+
const updateDefaultDisappearingMode = async (duration) => {
|
|
122
|
+
await query({
|
|
123
|
+
tag: 'iq',
|
|
124
|
+
attrs: {
|
|
125
|
+
xmlns: 'disappearing_mode',
|
|
126
|
+
to: S_WHATSAPP_NET,
|
|
127
|
+
type: 'set'
|
|
128
|
+
},
|
|
129
|
+
content: [
|
|
130
|
+
{
|
|
131
|
+
tag: 'disappearing_mode',
|
|
132
|
+
attrs: {
|
|
133
|
+
duration: duration.toString()
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
]
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
const getBotListV2 = async () => {
|
|
140
|
+
const resp = await query({
|
|
141
|
+
tag: 'iq',
|
|
142
|
+
attrs: {
|
|
143
|
+
xmlns: 'bot',
|
|
144
|
+
to: S_WHATSAPP_NET,
|
|
145
|
+
type: 'get'
|
|
146
|
+
},
|
|
147
|
+
content: [
|
|
148
|
+
{
|
|
149
|
+
tag: 'bot',
|
|
150
|
+
attrs: {
|
|
151
|
+
v: '2'
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
]
|
|
155
|
+
});
|
|
156
|
+
const botNode = getBinaryNodeChild(resp, 'bot');
|
|
157
|
+
const botList = [];
|
|
158
|
+
for (const section of getBinaryNodeChildren(botNode, 'section')) {
|
|
159
|
+
if (section.attrs.type === 'all') {
|
|
160
|
+
for (const bot of getBinaryNodeChildren(section, 'bot')) {
|
|
161
|
+
botList.push({
|
|
162
|
+
jid: bot.attrs.jid,
|
|
163
|
+
personaId: bot.attrs['persona_id']
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return botList;
|
|
169
|
+
};
|
|
170
|
+
const fetchStatus = async (...jids) => {
|
|
171
|
+
const usyncQuery = new USyncQuery().withStatusProtocol();
|
|
172
|
+
for (const jid of jids) {
|
|
173
|
+
usyncQuery.withUser(new USyncUser().withId(jid));
|
|
174
|
+
}
|
|
175
|
+
const result = await sock.executeUSyncQuery(usyncQuery);
|
|
176
|
+
if (result) {
|
|
177
|
+
return result.list;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
const fetchDisappearingDuration = async (...jids) => {
|
|
181
|
+
const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
|
|
182
|
+
for (const jid of jids) {
|
|
183
|
+
usyncQuery.withUser(new USyncUser().withId(jid));
|
|
184
|
+
}
|
|
185
|
+
const result = await sock.executeUSyncQuery(usyncQuery);
|
|
186
|
+
if (result) {
|
|
187
|
+
return result.list;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
// JAP@Note 06-02-26 --- Quick helper only. This function exists solely for faster lookup with caching.
|
|
191
|
+
const findUserId = async (pnLid) => {
|
|
192
|
+
const normalizedJid = jidNormalizedUser(pnLid);
|
|
193
|
+
const userId = {
|
|
194
|
+
lid: undefined,
|
|
195
|
+
phoneNumber: undefined
|
|
196
|
+
};
|
|
197
|
+
if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
|
|
198
|
+
userId.phoneNumber = normalizedJid;
|
|
199
|
+
userId.lid = jidNormalizedUser((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid);
|
|
200
|
+
}
|
|
201
|
+
else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
|
|
202
|
+
userId.lid = normalizedJid;
|
|
203
|
+
userId.phoneNumber = jidNormalizedUser((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn);
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
throw new Boom('Invalid id input to find user ids', { statusCode: 400 });
|
|
207
|
+
}
|
|
208
|
+
return userId;
|
|
209
|
+
};
|
|
210
|
+
/** update the profile picture for yourself or a group */
|
|
211
|
+
const updateProfilePicture = async (jid, content, dimensions) => {
|
|
212
|
+
let targetJid;
|
|
213
|
+
if (!jid) {
|
|
214
|
+
throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
|
|
215
|
+
}
|
|
216
|
+
if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
|
|
217
|
+
targetJid = jidNormalizedUser(jid); // in case it is someone other than us
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
targetJid = undefined;
|
|
221
|
+
}
|
|
222
|
+
const { img } = await generateProfilePicture(content, dimensions);
|
|
223
|
+
await query({
|
|
224
|
+
tag: 'iq',
|
|
225
|
+
attrs: {
|
|
226
|
+
to: S_WHATSAPP_NET,
|
|
227
|
+
type: 'set',
|
|
228
|
+
xmlns: 'w:profile:picture',
|
|
229
|
+
...(targetJid ? { target: targetJid } : {})
|
|
230
|
+
},
|
|
231
|
+
content: [
|
|
232
|
+
{
|
|
233
|
+
tag: 'picture',
|
|
234
|
+
attrs: { type: 'image' },
|
|
235
|
+
content: img
|
|
236
|
+
}
|
|
237
|
+
]
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
/** remove the profile picture for yourself or a group */
|
|
241
|
+
const removeProfilePicture = async (jid) => {
|
|
242
|
+
let targetJid;
|
|
243
|
+
if (!jid) {
|
|
244
|
+
throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
|
|
245
|
+
}
|
|
246
|
+
if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
|
|
247
|
+
targetJid = jidNormalizedUser(jid); // in case it is someone other than us
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
targetJid = undefined;
|
|
251
|
+
}
|
|
252
|
+
await query({
|
|
253
|
+
tag: 'iq',
|
|
254
|
+
attrs: {
|
|
255
|
+
to: S_WHATSAPP_NET,
|
|
256
|
+
type: 'set',
|
|
257
|
+
xmlns: 'w:profile:picture',
|
|
258
|
+
...(targetJid ? { target: targetJid } : {})
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
/** update the profile status for yourself */
|
|
263
|
+
const updateProfileStatus = async (status) => {
|
|
264
|
+
await query({
|
|
265
|
+
tag: 'iq',
|
|
266
|
+
attrs: {
|
|
267
|
+
to: S_WHATSAPP_NET,
|
|
268
|
+
type: 'set',
|
|
269
|
+
xmlns: 'status'
|
|
270
|
+
},
|
|
271
|
+
content: [
|
|
272
|
+
{
|
|
273
|
+
tag: 'status',
|
|
274
|
+
attrs: {},
|
|
275
|
+
content: Buffer.from(status, 'utf-8')
|
|
276
|
+
}
|
|
277
|
+
]
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
const updateProfileName = async (name) => {
|
|
281
|
+
await chatModify({ pushNameSetting: name }, '');
|
|
282
|
+
};
|
|
283
|
+
const fetchBlocklist = async () => {
|
|
284
|
+
const result = await query({
|
|
285
|
+
tag: 'iq',
|
|
286
|
+
attrs: {
|
|
287
|
+
xmlns: 'blocklist',
|
|
288
|
+
to: S_WHATSAPP_NET,
|
|
289
|
+
type: 'get'
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
const listNode = getBinaryNodeChild(result, 'list');
|
|
293
|
+
return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
|
|
294
|
+
};
|
|
295
|
+
const updateBlockStatus = async (jid, action) => {
|
|
296
|
+
const normalizedJid = jidNormalizedUser(jid);
|
|
297
|
+
let lid;
|
|
298
|
+
let pn_jid;
|
|
299
|
+
if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
|
|
300
|
+
lid = normalizedJid;
|
|
301
|
+
if (action === 'block') {
|
|
302
|
+
const pn = (await findUserId(normalizedJid)).phoneNumber;
|
|
303
|
+
if (!pn) {
|
|
304
|
+
throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
|
|
305
|
+
}
|
|
306
|
+
pn_jid = jidNormalizedUser(pn);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
|
|
310
|
+
const mapped = (await findUserId(normalizedJid)).lid;
|
|
311
|
+
if (!mapped) {
|
|
312
|
+
throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
|
|
313
|
+
}
|
|
314
|
+
lid = mapped;
|
|
315
|
+
if (action === 'block') {
|
|
316
|
+
pn_jid = jidNormalizedUser(normalizedJid);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
|
|
321
|
+
}
|
|
322
|
+
const itemAttrs = {
|
|
323
|
+
action,
|
|
324
|
+
jid: lid
|
|
325
|
+
};
|
|
326
|
+
if (action === 'block') {
|
|
327
|
+
if (!pn_jid) {
|
|
328
|
+
throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
|
|
329
|
+
}
|
|
330
|
+
itemAttrs.pn_jid = pn_jid;
|
|
331
|
+
}
|
|
332
|
+
await query({
|
|
333
|
+
tag: 'iq',
|
|
334
|
+
attrs: {
|
|
335
|
+
xmlns: 'blocklist',
|
|
336
|
+
to: S_WHATSAPP_NET,
|
|
337
|
+
type: 'set'
|
|
338
|
+
},
|
|
339
|
+
content: [
|
|
340
|
+
{
|
|
341
|
+
tag: 'item',
|
|
342
|
+
attrs: itemAttrs
|
|
343
|
+
}
|
|
344
|
+
]
|
|
345
|
+
});
|
|
346
|
+
};
|
|
347
|
+
const getBusinessProfile = async (jid) => {
|
|
348
|
+
const results = await query({
|
|
349
|
+
tag: 'iq',
|
|
350
|
+
attrs: {
|
|
351
|
+
to: 's.whatsapp.net',
|
|
352
|
+
xmlns: 'w:biz',
|
|
353
|
+
type: 'get'
|
|
354
|
+
},
|
|
355
|
+
content: [
|
|
356
|
+
{
|
|
357
|
+
tag: 'business_profile',
|
|
358
|
+
attrs: { v: '244' },
|
|
359
|
+
content: [
|
|
360
|
+
{
|
|
361
|
+
tag: 'profile',
|
|
362
|
+
attrs: { jid }
|
|
363
|
+
}
|
|
364
|
+
]
|
|
365
|
+
}
|
|
366
|
+
]
|
|
367
|
+
});
|
|
368
|
+
const profileNode = getBinaryNodeChild(results, 'business_profile');
|
|
369
|
+
const profiles = getBinaryNodeChild(profileNode, 'profile');
|
|
370
|
+
if (profiles) {
|
|
371
|
+
const address = getBinaryNodeChild(profiles, 'address');
|
|
372
|
+
const description = getBinaryNodeChild(profiles, 'description');
|
|
373
|
+
const website = getBinaryNodeChild(profiles, 'website');
|
|
374
|
+
const email = getBinaryNodeChild(profiles, 'email');
|
|
375
|
+
const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
|
|
376
|
+
const businessHours = getBinaryNodeChild(profiles, 'business_hours');
|
|
377
|
+
const businessHoursConfig = businessHours
|
|
378
|
+
? getBinaryNodeChildren(businessHours, 'business_hours_config')
|
|
379
|
+
: undefined;
|
|
380
|
+
const websiteStr = website?.content?.toString();
|
|
381
|
+
return {
|
|
382
|
+
wid: profiles.attrs?.jid,
|
|
383
|
+
address: address?.content?.toString(),
|
|
384
|
+
description: description?.content?.toString() || '',
|
|
385
|
+
website: websiteStr ? [websiteStr] : [],
|
|
386
|
+
email: email?.content?.toString(),
|
|
387
|
+
category: category?.content?.toString(),
|
|
388
|
+
business_hours: {
|
|
389
|
+
timezone: businessHours?.attrs?.timezone,
|
|
390
|
+
business_config: businessHoursConfig?.map(({ attrs }) => attrs)
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
const cleanDirtyBits = async (type, fromTimestamp) => {
|
|
396
|
+
logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
|
|
397
|
+
await sendNode({
|
|
398
|
+
tag: 'iq',
|
|
399
|
+
attrs: {
|
|
400
|
+
to: S_WHATSAPP_NET,
|
|
401
|
+
type: 'set',
|
|
402
|
+
xmlns: 'urn:xmpp:whatsapp:dirty',
|
|
403
|
+
id: generateMessageTag()
|
|
404
|
+
},
|
|
405
|
+
content: [
|
|
406
|
+
{
|
|
407
|
+
tag: 'clean',
|
|
408
|
+
attrs: {
|
|
409
|
+
type,
|
|
410
|
+
...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
]
|
|
414
|
+
});
|
|
415
|
+
};
|
|
416
|
+
const newAppStateChunkHandler = (isInitialSync) => {
|
|
417
|
+
return {
|
|
418
|
+
onMutation(mutation) {
|
|
419
|
+
processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
};
|
|
423
|
+
const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
|
|
424
|
+
const appStateSyncKeyCache = new Map();
|
|
425
|
+
const getCachedAppStateSyncKey = async (keyId) => {
|
|
426
|
+
if (appStateSyncKeyCache.has(keyId)) {
|
|
427
|
+
return appStateSyncKeyCache.get(keyId) ?? undefined;
|
|
428
|
+
}
|
|
429
|
+
const key = await getAppStateSyncKey(keyId);
|
|
430
|
+
appStateSyncKeyCache.set(keyId, key ?? null);
|
|
431
|
+
return key;
|
|
432
|
+
};
|
|
433
|
+
// we use this to determine which events to fire
|
|
434
|
+
// otherwise when we resync from scratch -- all notifications will fire
|
|
435
|
+
const initialVersionMap = {};
|
|
436
|
+
const globalMutationMap = {};
|
|
437
|
+
await authState.keys.transaction(async () => {
|
|
438
|
+
const collectionsToHandle = new Set(collections);
|
|
439
|
+
// in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
|
|
440
|
+
const attemptsMap = {};
|
|
441
|
+
// collections that failed and need a full snapshot on retry
|
|
442
|
+
// mirrors WA Web's ErrorFatal -> force snapshot behavior
|
|
443
|
+
const forceSnapshotCollections = new Set();
|
|
444
|
+
// keep executing till all collections are done
|
|
445
|
+
// sometimes a single patch request will not return all the patches (God knows why)
|
|
446
|
+
// so we fetch till they're all done (this is determined by the "has_more_patches" flag)
|
|
447
|
+
while (collectionsToHandle.size) {
|
|
448
|
+
const states = {};
|
|
449
|
+
const nodes = [];
|
|
450
|
+
for (const name of collectionsToHandle) {
|
|
451
|
+
const result = await authState.keys.get('app-state-sync-version', [name]);
|
|
452
|
+
let state = result[name];
|
|
453
|
+
if (state) {
|
|
454
|
+
state = ensureLTHashStateVersion(state);
|
|
455
|
+
if (typeof initialVersionMap[name] === 'undefined') {
|
|
456
|
+
initialVersionMap[name] = state.version;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
state = newLTHashState();
|
|
461
|
+
}
|
|
462
|
+
states[name] = state;
|
|
463
|
+
const shouldForceSnapshot = forceSnapshotCollections.has(name);
|
|
464
|
+
if (shouldForceSnapshot) {
|
|
465
|
+
forceSnapshotCollections.delete(name);
|
|
466
|
+
}
|
|
467
|
+
logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
|
|
468
|
+
nodes.push({
|
|
469
|
+
tag: 'collection',
|
|
470
|
+
attrs: {
|
|
471
|
+
name,
|
|
472
|
+
version: state.version.toString(),
|
|
473
|
+
// return snapshot if syncing from scratch or forcing after a failed attempt
|
|
474
|
+
return_snapshot: (shouldForceSnapshot || !state.version).toString()
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
const result = await query({
|
|
479
|
+
tag: 'iq',
|
|
480
|
+
attrs: {
|
|
481
|
+
to: S_WHATSAPP_NET,
|
|
482
|
+
xmlns: 'w:sync:app:state',
|
|
483
|
+
type: 'set'
|
|
484
|
+
},
|
|
485
|
+
content: [
|
|
486
|
+
{
|
|
487
|
+
tag: 'sync',
|
|
488
|
+
attrs: {},
|
|
489
|
+
content: nodes
|
|
490
|
+
}
|
|
491
|
+
]
|
|
492
|
+
});
|
|
493
|
+
// extract from binary node
|
|
494
|
+
const decoded = await extractSyncdPatches(result, config?.options);
|
|
495
|
+
for (const key in decoded) {
|
|
496
|
+
const name = key;
|
|
497
|
+
const { patches, hasMorePatches, snapshot } = decoded[name];
|
|
498
|
+
try {
|
|
499
|
+
if (snapshot) {
|
|
500
|
+
const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
|
|
501
|
+
states[name] = newState;
|
|
502
|
+
Object.assign(globalMutationMap, mutationMap);
|
|
503
|
+
logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
|
|
504
|
+
await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
|
|
505
|
+
}
|
|
506
|
+
// only process if there are syncd patches
|
|
507
|
+
if (patches.length) {
|
|
508
|
+
const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
|
|
509
|
+
await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
|
|
510
|
+
logger.info(`synced ${name} to v${newState.version}`);
|
|
511
|
+
initialVersionMap[name] = newState.version;
|
|
512
|
+
Object.assign(globalMutationMap, mutationMap);
|
|
513
|
+
}
|
|
514
|
+
if (hasMorePatches) {
|
|
515
|
+
logger.info(`${name} has more patches...`);
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
// collection is done with sync
|
|
519
|
+
collectionsToHandle.delete(name);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
catch (error) {
|
|
523
|
+
attemptsMap[name] = (attemptsMap[name] || 0) + 1;
|
|
524
|
+
const logData = {
|
|
525
|
+
name,
|
|
526
|
+
attempt: attemptsMap[name],
|
|
527
|
+
version: states[name].version,
|
|
528
|
+
statusCode: error.output?.statusCode,
|
|
529
|
+
errorType: error.name,
|
|
530
|
+
error: error.stack
|
|
531
|
+
};
|
|
532
|
+
if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
|
|
533
|
+
// WA Web treats missing keys as "Blocked" — park the collection
|
|
534
|
+
// until the key arrives via APP_STATE_SYNC_KEY_SHARE.
|
|
535
|
+
logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
|
|
536
|
+
blockedCollections.add(name);
|
|
537
|
+
collectionsToHandle.delete(name);
|
|
538
|
+
}
|
|
539
|
+
else if (isMissingKeyError(error)) {
|
|
540
|
+
// Retry with a snapshot which may use a different key.
|
|
541
|
+
logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
|
|
542
|
+
forceSnapshotCollections.add(name);
|
|
543
|
+
}
|
|
544
|
+
else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
|
|
545
|
+
logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
|
|
546
|
+
collectionsToHandle.delete(name);
|
|
547
|
+
}
|
|
548
|
+
else {
|
|
549
|
+
logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
|
|
550
|
+
// force a full snapshot on retry to recover from
|
|
551
|
+
// corrupted local state (e.g. LTHash MAC mismatch)
|
|
552
|
+
forceSnapshotCollections.add(name);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}, authState?.creds?.me?.id || 'resync-app-state');
|
|
558
|
+
const { onMutation } = newAppStateChunkHandler(isInitialSync);
|
|
559
|
+
for (const key in globalMutationMap) {
|
|
560
|
+
onMutation(globalMutationMap[key]);
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
/**
|
|
564
|
+
* fetch the profile picture of a user/group
|
|
565
|
+
* type = "preview" for a low res picture
|
|
566
|
+
* type = "image for the high res picture"
|
|
567
|
+
*/
|
|
568
|
+
const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = false) => {
|
|
569
|
+
const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
|
|
570
|
+
// WA Web only includes tctoken for user JIDs (not groups/newsletters)
|
|
571
|
+
// and never for own profile pic (Chat model for self has no tcToken).
|
|
572
|
+
// Including tctoken for own JID causes the server to never respond.
|
|
573
|
+
const normalizedJid = jidNormalizedUser(jid);
|
|
574
|
+
const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
|
|
575
|
+
const me = authState.creds.me;
|
|
576
|
+
const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
|
|
577
|
+
let content = baseContent;
|
|
578
|
+
if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
|
|
579
|
+
content = await buildTcTokenFromJid({
|
|
580
|
+
authState,
|
|
581
|
+
jid: normalizedJid,
|
|
582
|
+
baseContent,
|
|
583
|
+
getLIDForPN
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
jid = jidNormalizedUser(jid);
|
|
587
|
+
const result = await query({
|
|
588
|
+
tag: 'iq',
|
|
589
|
+
attrs: {
|
|
590
|
+
target: jid,
|
|
591
|
+
to: S_WHATSAPP_NET,
|
|
592
|
+
type: 'get',
|
|
593
|
+
xmlns: 'w:profile:picture'
|
|
594
|
+
},
|
|
595
|
+
content
|
|
596
|
+
}, timeoutMs);
|
|
597
|
+
const child = getBinaryNodeChild(result, 'picture');
|
|
598
|
+
return child?.attrs?.url;
|
|
599
|
+
};
|
|
600
|
+
const createCallLink = async (type, event, timeoutMs) => {
|
|
601
|
+
const result = await query({
|
|
602
|
+
tag: 'call',
|
|
603
|
+
attrs: {
|
|
604
|
+
id: generateMessageTag(),
|
|
605
|
+
to: '@call'
|
|
606
|
+
},
|
|
607
|
+
content: [
|
|
608
|
+
{
|
|
609
|
+
tag: 'link_create',
|
|
610
|
+
attrs: { media: type },
|
|
611
|
+
content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
|
|
612
|
+
}
|
|
613
|
+
]
|
|
614
|
+
}, timeoutMs);
|
|
615
|
+
const child = getBinaryNodeChild(result, 'link_create');
|
|
616
|
+
return child?.attrs?.token;
|
|
617
|
+
};
|
|
618
|
+
const sendPresenceUpdate = async (type, toJid) => {
|
|
619
|
+
const me = authState.creds.me;
|
|
620
|
+
const isAvailableType = type === 'available';
|
|
621
|
+
if (isAvailableType || type === 'unavailable') {
|
|
622
|
+
if (!me.name) {
|
|
623
|
+
logger.warn('no name present, ignoring presence update request...');
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
ev.emit('connection.update', { isOnline: isAvailableType });
|
|
627
|
+
if (isAvailableType) {
|
|
628
|
+
void sendUnifiedSession();
|
|
629
|
+
}
|
|
630
|
+
await sendNode({
|
|
631
|
+
tag: 'presence',
|
|
632
|
+
attrs: {
|
|
633
|
+
name: me.name.replace(/@/g, ''),
|
|
634
|
+
type
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
const { server } = jidDecode(toJid);
|
|
640
|
+
const isLid = server === 'lid';
|
|
641
|
+
await sendNode({
|
|
642
|
+
tag: 'chatstate',
|
|
643
|
+
attrs: {
|
|
644
|
+
from: isLid ? me.lid : me.id,
|
|
645
|
+
to: toJid
|
|
646
|
+
},
|
|
647
|
+
content: [
|
|
648
|
+
{
|
|
649
|
+
tag: type === 'recording' ? 'composing' : type,
|
|
650
|
+
attrs: type === 'recording' ? { media: 'audio' } : {}
|
|
651
|
+
}
|
|
652
|
+
]
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
/**
|
|
657
|
+
* @param toJid the jid to subscribe to
|
|
658
|
+
* @param tcToken token for subscription, use if present
|
|
659
|
+
*/
|
|
660
|
+
const presenceSubscribe = async (toJid) => {
|
|
661
|
+
// Only include tctoken for user JIDs — groups/newsletters don't use tctokens
|
|
662
|
+
const normalizedToJid = jidNormalizedUser(toJid);
|
|
663
|
+
const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
|
|
664
|
+
const tcTokenContent = isUserJid
|
|
665
|
+
? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
|
|
666
|
+
: undefined;
|
|
667
|
+
return sendNode({
|
|
668
|
+
tag: 'presence',
|
|
669
|
+
attrs: {
|
|
670
|
+
to: toJid,
|
|
671
|
+
id: generateMessageTag(),
|
|
672
|
+
type: 'subscribe'
|
|
673
|
+
},
|
|
674
|
+
content: tcTokenContent
|
|
675
|
+
});
|
|
676
|
+
};
|
|
677
|
+
const handlePresenceUpdate = ({ tag, attrs, content }) => {
|
|
678
|
+
let presence;
|
|
679
|
+
const jid = attrs.from;
|
|
680
|
+
const participant = attrs.participant || attrs.from;
|
|
681
|
+
if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
if (tag === 'presence') {
|
|
685
|
+
presence = {
|
|
686
|
+
lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
|
|
687
|
+
lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
|
|
688
|
+
groupOnlineCount: attrs.count ? +attrs.count : undefined
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
else if (Array.isArray(content)) {
|
|
692
|
+
const [firstChild] = content;
|
|
693
|
+
let type = firstChild.tag;
|
|
694
|
+
if (type === 'paused') {
|
|
695
|
+
type = 'available';
|
|
696
|
+
}
|
|
697
|
+
if (firstChild.attrs?.media === 'audio') {
|
|
698
|
+
type = 'recording';
|
|
699
|
+
}
|
|
700
|
+
presence = { lastKnownPresence: type };
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
logger.error({ tag, attrs, content }, 'recv invalid presence node');
|
|
704
|
+
}
|
|
705
|
+
if (presence) {
|
|
706
|
+
ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
// JAP@Fix 24-08-26 --- appPatch() (used by updateProfileName/archive/mute/pin/etc — anything
|
|
710
|
+
// going through the app-state WRITE path) threw "App state key not present!" immediately if
|
|
711
|
+
// myAppStateKeyId wasn't set yet, with zero retry. The READ path (resyncAppState, above) already
|
|
712
|
+
// has a courtesy retry via blockedCollections + the creds.update listener below — the key
|
|
713
|
+
// arrives async after connect (APP_STATE_SYNC_KEY_SHARE), so calling e.g. updateProfileName()
|
|
714
|
+
// right after connection.update === 'open' would reliably fail on a fresh/early connection.
|
|
715
|
+
// Now appPatch() waits (bounded, 20s default) for the same creds.update event before giving up,
|
|
716
|
+
// instead of failing hard on what's usually just a timing race.
|
|
717
|
+
//
|
|
718
|
+
// JAP@Fix 25-08-26 --- the event-only wait had a blind spot: if `creds.update` never actually
|
|
719
|
+
// reaches this listener (swallowed/filtered by a wrapper around `ev`, a custom auth-state
|
|
720
|
+
// adapter that patches `authState.creds` directly without re-emitting the event, etc.) this
|
|
721
|
+
// would sit for the full timeout and fail even though `authState.creds.myAppStateKeyId` was
|
|
722
|
+
// genuinely set the whole time. Added a belt-and-suspenders poll of the creds object itself
|
|
723
|
+
// alongside the event listener — whichever one notices the key first wins, and both are torn
|
|
724
|
+
// down together so there's no leaked timer/listener either way.
|
|
725
|
+
const waitForAppStateKeyId = (timeoutMs = 20_000, pollMs = 500) => {
|
|
726
|
+
if (authState.creds.myAppStateKeyId) {
|
|
727
|
+
return Promise.resolve(authState.creds.myAppStateKeyId);
|
|
728
|
+
}
|
|
729
|
+
return new Promise((resolve, reject) => {
|
|
730
|
+
let settled = false;
|
|
731
|
+
const cleanup = () => {
|
|
732
|
+
settled = true;
|
|
733
|
+
clearTimeout(timeout);
|
|
734
|
+
clearInterval(poller);
|
|
735
|
+
ev.off('creds.update', onUpdate);
|
|
736
|
+
};
|
|
737
|
+
const timeout = setTimeout(() => {
|
|
738
|
+
if (settled) return;
|
|
739
|
+
cleanup();
|
|
740
|
+
logger.warn(
|
|
741
|
+
{ hasMyAppStateKeyId: !!authState.creds.myAppStateKeyId, registered: authState.creds.registered },
|
|
742
|
+
'waitForAppStateKeyId timed out — APP_STATE_SYNC_KEY_SHARE was never received/applied for this session'
|
|
743
|
+
);
|
|
744
|
+
reject(new Boom('App state key not present!', { statusCode: 400 }));
|
|
745
|
+
}, timeoutMs);
|
|
746
|
+
const poller = setInterval(() => {
|
|
747
|
+
if (settled || !authState.creds.myAppStateKeyId) return;
|
|
748
|
+
const id = authState.creds.myAppStateKeyId;
|
|
749
|
+
cleanup();
|
|
750
|
+
resolve(id);
|
|
751
|
+
}, pollMs);
|
|
752
|
+
const onUpdate = ({ myAppStateKeyId }) => {
|
|
753
|
+
if (settled || !myAppStateKeyId) return;
|
|
754
|
+
cleanup();
|
|
755
|
+
resolve(myAppStateKeyId);
|
|
756
|
+
};
|
|
757
|
+
ev.on('creds.update', onUpdate);
|
|
758
|
+
});
|
|
759
|
+
};
|
|
760
|
+
// JAP@Fix (perf) --- appPatch() unconditionally round-tripped resyncAppState() to the WA
|
|
761
|
+
// server on EVERY single call, even for back-to-back patches (e.g. updateProfileName then
|
|
762
|
+
// immediately archiving/muting a chat) where the local version was already fresh from the
|
|
763
|
+
// resync a few hundred ms ago. That round trip is the main source of the multi-second delay
|
|
764
|
+
// people notice on things like "ganti nama". Cache the last-synced timestamp per collection
|
|
765
|
+
// name and skip the resync if it happened within RESYNC_TTL_MS — WA's own client does the
|
|
766
|
+
// same kind of short-lived debouncing. Set RESYNC_TTL_MS to 0 to restore the old always-resync
|
|
767
|
+
// behavior if this ever causes a stale-version conflict in practice.
|
|
768
|
+
const RESYNC_TTL_MS = 4000;
|
|
769
|
+
const lastResyncAt = new Map();
|
|
770
|
+
const appPatch = async (patchCreate) => {
|
|
771
|
+
const name = patchCreate.type;
|
|
772
|
+
const t0 = Date.now();
|
|
773
|
+
const myAppStateKeyId = await waitForAppStateKeyId();
|
|
774
|
+
const tKey = Date.now();
|
|
775
|
+
let initial;
|
|
776
|
+
let encodeResult;
|
|
777
|
+
await appStatePatchMutex.mutex(async () => {
|
|
778
|
+
await authState.keys.transaction(async () => {
|
|
779
|
+
logger.debug({ patch: patchCreate }, 'applying app patch');
|
|
780
|
+
const lastSync = lastResyncAt.get(name) ?? 0;
|
|
781
|
+
const freshEnough = RESYNC_TTL_MS > 0 && Date.now() - lastSync < RESYNC_TTL_MS;
|
|
782
|
+
if (!freshEnough) {
|
|
783
|
+
await resyncAppState([name], false);
|
|
784
|
+
lastResyncAt.set(name, Date.now());
|
|
785
|
+
}
|
|
786
|
+
const tResync = Date.now();
|
|
787
|
+
logger.debug(
|
|
788
|
+
{ patch: name, waitedForKeyMs: tKey - t0, resyncMs: freshEnough ? 0 : tResync - tKey, skippedResync: freshEnough },
|
|
789
|
+
'appPatch timing'
|
|
790
|
+
);
|
|
791
|
+
const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
|
|
792
|
+
initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
|
|
793
|
+
encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
|
|
794
|
+
const { patch, state } = encodeResult;
|
|
795
|
+
const node = {
|
|
796
|
+
tag: 'iq',
|
|
797
|
+
attrs: {
|
|
798
|
+
to: S_WHATSAPP_NET,
|
|
799
|
+
type: 'set',
|
|
800
|
+
xmlns: 'w:sync:app:state'
|
|
801
|
+
},
|
|
802
|
+
content: [
|
|
803
|
+
{
|
|
804
|
+
tag: 'sync',
|
|
805
|
+
attrs: {},
|
|
806
|
+
content: [
|
|
807
|
+
{
|
|
808
|
+
tag: 'collection',
|
|
809
|
+
attrs: {
|
|
810
|
+
name,
|
|
811
|
+
version: (state.version - 1).toString(),
|
|
812
|
+
return_snapshot: 'false'
|
|
813
|
+
},
|
|
814
|
+
content: [
|
|
815
|
+
{
|
|
816
|
+
tag: 'patch',
|
|
817
|
+
attrs: {},
|
|
818
|
+
content: proto.SyncdPatch.encode(patch).finish()
|
|
819
|
+
}
|
|
820
|
+
]
|
|
821
|
+
}
|
|
822
|
+
]
|
|
823
|
+
}
|
|
824
|
+
]
|
|
825
|
+
};
|
|
826
|
+
await query(node);
|
|
827
|
+
await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
|
|
828
|
+
}, authState?.creds?.me?.id || 'app-patch');
|
|
829
|
+
});
|
|
830
|
+
if (config.emitOwnEvents) {
|
|
831
|
+
const { onMutation } = newAppStateChunkHandler(false);
|
|
832
|
+
const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
|
|
833
|
+
for (const key in mutationMap) {
|
|
834
|
+
onMutation(mutationMap[key]);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
/** fetch AB props */
|
|
839
|
+
const fetchProps = async () => {
|
|
840
|
+
const resultNode = await query({
|
|
841
|
+
tag: 'iq',
|
|
842
|
+
attrs: {
|
|
843
|
+
to: S_WHATSAPP_NET,
|
|
844
|
+
xmlns: 'abt',
|
|
845
|
+
type: 'get'
|
|
846
|
+
},
|
|
847
|
+
content: [
|
|
848
|
+
{
|
|
849
|
+
tag: 'props',
|
|
850
|
+
attrs: {
|
|
851
|
+
protocol: '1',
|
|
852
|
+
...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
]
|
|
856
|
+
});
|
|
857
|
+
const propsNode = getBinaryNodeChild(resultNode, 'props');
|
|
858
|
+
let props = {};
|
|
859
|
+
if (propsNode) {
|
|
860
|
+
if (propsNode.attrs?.hash) {
|
|
861
|
+
// on some clients, the hash is returning as undefined
|
|
862
|
+
authState.creds.lastPropHash = propsNode?.attrs?.hash;
|
|
863
|
+
ev.emit('creds.update', authState.creds);
|
|
864
|
+
}
|
|
865
|
+
props = reduceBinaryNodeToDictionary(propsNode, 'prop');
|
|
866
|
+
}
|
|
867
|
+
// Extract protocol-relevant AB props (only the ones we need)
|
|
868
|
+
const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
|
|
869
|
+
if (privacyTokenProp !== undefined) {
|
|
870
|
+
serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
|
|
871
|
+
}
|
|
872
|
+
const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
|
|
873
|
+
if (profilePicProp !== undefined) {
|
|
874
|
+
serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
|
|
875
|
+
}
|
|
876
|
+
const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
|
|
877
|
+
if (lidIssueProp !== undefined) {
|
|
878
|
+
serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
|
|
879
|
+
}
|
|
880
|
+
logger.debug({ serverProps }, 'fetched props');
|
|
881
|
+
return props;
|
|
882
|
+
};
|
|
883
|
+
/**
|
|
884
|
+
* modify a chat -- mark unread, read etc.
|
|
885
|
+
* lastMessages must be sorted in reverse chronologically
|
|
886
|
+
* requires the last messages till the last message received; required for archive & unread
|
|
887
|
+
*/
|
|
888
|
+
const chatModify = (mod, jid) => {
|
|
889
|
+
const patch = chatModificationToAppPatch(mod, jid);
|
|
890
|
+
return appPatch(patch);
|
|
891
|
+
};
|
|
892
|
+
/**
|
|
893
|
+
* Enable/Disable link preview privacy, not related to baileys link preview generation
|
|
894
|
+
*/
|
|
895
|
+
const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
|
|
896
|
+
return chatModify({
|
|
897
|
+
disableLinkPreviews: { isPreviewsDisabled }
|
|
898
|
+
}, '');
|
|
899
|
+
};
|
|
900
|
+
/**
|
|
901
|
+
* Star or Unstar a message
|
|
902
|
+
*/
|
|
903
|
+
const star = (jid, messages, star) => {
|
|
904
|
+
return chatModify({
|
|
905
|
+
star: {
|
|
906
|
+
messages,
|
|
907
|
+
star
|
|
908
|
+
}
|
|
909
|
+
}, jid);
|
|
910
|
+
};
|
|
911
|
+
/**
|
|
912
|
+
* Add or Edit Contact
|
|
913
|
+
*/
|
|
914
|
+
const addOrEditContact = (jid, contact) => {
|
|
915
|
+
return chatModify({
|
|
916
|
+
contact
|
|
917
|
+
}, jid);
|
|
918
|
+
};
|
|
919
|
+
/**
|
|
920
|
+
* Remove Contact
|
|
921
|
+
*/
|
|
922
|
+
const removeContact = (jid) => {
|
|
923
|
+
return chatModify({
|
|
924
|
+
contact: null
|
|
925
|
+
}, jid);
|
|
926
|
+
};
|
|
927
|
+
/**
|
|
928
|
+
* Adds label
|
|
929
|
+
*/
|
|
930
|
+
const addLabel = (jid, labels) => {
|
|
931
|
+
return chatModify({
|
|
932
|
+
addLabel: {
|
|
933
|
+
...labels
|
|
934
|
+
}
|
|
935
|
+
}, jid);
|
|
936
|
+
};
|
|
937
|
+
/**
|
|
938
|
+
* Adds label for the chats
|
|
939
|
+
*/
|
|
940
|
+
const addChatLabel = (jid, labelId) => {
|
|
941
|
+
return chatModify({
|
|
942
|
+
addChatLabel: {
|
|
943
|
+
labelId
|
|
944
|
+
}
|
|
945
|
+
}, jid);
|
|
946
|
+
};
|
|
947
|
+
/**
|
|
948
|
+
* Removes label for the chat
|
|
949
|
+
*/
|
|
950
|
+
const removeChatLabel = (jid, labelId) => {
|
|
951
|
+
return chatModify({
|
|
952
|
+
removeChatLabel: {
|
|
953
|
+
labelId
|
|
954
|
+
}
|
|
955
|
+
}, jid);
|
|
956
|
+
};
|
|
957
|
+
/**
|
|
958
|
+
* Adds label for the message
|
|
959
|
+
*/
|
|
960
|
+
const addMessageLabel = (jid, messageId, labelId) => {
|
|
961
|
+
return chatModify({
|
|
962
|
+
addMessageLabel: {
|
|
963
|
+
messageId,
|
|
964
|
+
labelId
|
|
965
|
+
}
|
|
966
|
+
}, jid);
|
|
967
|
+
};
|
|
968
|
+
/**
|
|
969
|
+
* Removes label for the message
|
|
970
|
+
*/
|
|
971
|
+
const removeMessageLabel = (jid, messageId, labelId) => {
|
|
972
|
+
return chatModify({
|
|
973
|
+
removeMessageLabel: {
|
|
974
|
+
messageId,
|
|
975
|
+
labelId
|
|
976
|
+
}
|
|
977
|
+
}, jid);
|
|
978
|
+
};
|
|
979
|
+
/**
|
|
980
|
+
* Add or Edit Quick Reply
|
|
981
|
+
*/
|
|
982
|
+
const addOrEditQuickReply = (quickReply) => {
|
|
983
|
+
return chatModify({
|
|
984
|
+
quickReply
|
|
985
|
+
}, '');
|
|
986
|
+
};
|
|
987
|
+
/**
|
|
988
|
+
* Remove Quick Reply
|
|
989
|
+
*/
|
|
990
|
+
const removeQuickReply = (timestamp) => {
|
|
991
|
+
return chatModify({
|
|
992
|
+
quickReply: { timestamp, deleted: true }
|
|
993
|
+
}, '');
|
|
994
|
+
};
|
|
995
|
+
/**
|
|
996
|
+
* queries need to be fired on connection open
|
|
997
|
+
* help ensure parity with WA Web
|
|
998
|
+
* */
|
|
999
|
+
const executeInitQueries = async () => {
|
|
1000
|
+
await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
|
|
1001
|
+
};
|
|
1002
|
+
// JAP@Changes --- Detect WhatsApp system/security notification messages
|
|
1003
|
+
// (e.g. "Messages are end-to-end encrypted", "This business now uses a secure
|
|
1004
|
+
// service from Meta") so consumers can filter them out without affecting any
|
|
1005
|
+
// existing message types or behavior. This ONLY adds a flag, nothing is dropped.
|
|
1006
|
+
const isWASystemNotification = (msg) => {
|
|
1007
|
+
const content = msg?.message;
|
|
1008
|
+
if (!content)
|
|
1009
|
+
return false;
|
|
1010
|
+
// E2E / business-encryption notices arrive as protocolMessage with these types
|
|
1011
|
+
const protoType = content.protocolMessage?.type;
|
|
1012
|
+
if (protoType === proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION ||
|
|
1013
|
+
protoType === proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE ||
|
|
1014
|
+
protoType === proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE ||
|
|
1015
|
+
protoType === proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC) {
|
|
1016
|
+
return true;
|
|
1017
|
+
}
|
|
1018
|
+
// Generic stub-type system notices (no real content, just a stub event)
|
|
1019
|
+
if (msg.messageStubType && !content.conversation && !content.extendedTextMessage) {
|
|
1020
|
+
const stub = msg.messageStubType;
|
|
1021
|
+
const SYSTEM_STUB_TYPES = new Set([
|
|
1022
|
+
WAMessageStubType.E2E_DEVICE_CHANGED,
|
|
1023
|
+
WAMessageStubType.E2E_ENCRYPTED,
|
|
1024
|
+
WAMessageStubType.E2E_IDENTITY_CHANGED,
|
|
1025
|
+
WAMessageStubType.CIPHERTEXT,
|
|
1026
|
+
WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP,
|
|
1027
|
+
WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
|
|
1028
|
+
]);
|
|
1029
|
+
if (SYSTEM_STUB_TYPES.has(stub))
|
|
1030
|
+
return true;
|
|
1031
|
+
}
|
|
1032
|
+
return false;
|
|
1033
|
+
};
|
|
1034
|
+
const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
|
|
1035
|
+
// JAP@Changes --- Annotate msg with isSystemNotification flag (additive only)
|
|
1036
|
+
if (isWASystemNotification(msg)) {
|
|
1037
|
+
msg.isSystemNotification = true;
|
|
1038
|
+
}
|
|
1039
|
+
ev.emit('messages.upsert', { messages: [msg], type });
|
|
1040
|
+
if (!!msg.pushName) {
|
|
1041
|
+
let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
|
|
1042
|
+
jid = jidNormalizedUser(jid);
|
|
1043
|
+
if (!msg.key.fromMe) {
|
|
1044
|
+
ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
|
|
1045
|
+
}
|
|
1046
|
+
// update our pushname too
|
|
1047
|
+
if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
|
|
1048
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
const historyMsg = getHistoryMsg(msg.message);
|
|
1052
|
+
const shouldProcessHistoryMsg = historyMsg
|
|
1053
|
+
? shouldSyncHistoryMessage(historyMsg) &&
|
|
1054
|
+
PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
|
|
1055
|
+
: false;
|
|
1056
|
+
if (historyMsg && shouldProcessHistoryMsg) {
|
|
1057
|
+
const syncType = historyMsg.syncType;
|
|
1058
|
+
// INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
|
|
1059
|
+
if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
|
|
1060
|
+
!historySyncStatus.initialBootstrapComplete) {
|
|
1061
|
+
historySyncStatus.initialBootstrapComplete = true;
|
|
1062
|
+
ev.emit('messaging-history.status', {
|
|
1063
|
+
syncType,
|
|
1064
|
+
status: 'complete',
|
|
1065
|
+
explicit: true
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
// RECENT with progress === 100 — explicit completion
|
|
1069
|
+
if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
|
|
1070
|
+
historyMsg.progress === 100 &&
|
|
1071
|
+
!historySyncStatus.recentSyncComplete) {
|
|
1072
|
+
historySyncStatus.recentSyncComplete = true;
|
|
1073
|
+
clearTimeout(historySyncPausedTimeout);
|
|
1074
|
+
historySyncPausedTimeout = undefined;
|
|
1075
|
+
ev.emit('messaging-history.status', {
|
|
1076
|
+
syncType,
|
|
1077
|
+
status: 'complete',
|
|
1078
|
+
explicit: true
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
// Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
|
|
1082
|
+
if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
|
|
1083
|
+
clearTimeout(historySyncPausedTimeout);
|
|
1084
|
+
historySyncPausedTimeout = setTimeout(() => {
|
|
1085
|
+
if (!historySyncStatus.recentSyncComplete) {
|
|
1086
|
+
historySyncStatus.recentSyncComplete = true;
|
|
1087
|
+
ev.emit('messaging-history.status', {
|
|
1088
|
+
syncType: proto.HistorySync.HistorySyncType.RECENT,
|
|
1089
|
+
status: 'paused',
|
|
1090
|
+
explicit: false
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
historySyncPausedTimeout = undefined;
|
|
1094
|
+
}, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
// State machine: decide on sync and flush
|
|
1098
|
+
if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
|
|
1099
|
+
if (awaitingSyncTimeout) {
|
|
1100
|
+
clearTimeout(awaitingSyncTimeout);
|
|
1101
|
+
awaitingSyncTimeout = undefined;
|
|
1102
|
+
}
|
|
1103
|
+
if (shouldProcessHistoryMsg) {
|
|
1104
|
+
syncState = SyncState.Syncing;
|
|
1105
|
+
logger.info('Transitioned to Syncing state');
|
|
1106
|
+
// Let doAppStateSync handle the final flush after it's done
|
|
1107
|
+
}
|
|
1108
|
+
else {
|
|
1109
|
+
syncState = SyncState.Online;
|
|
1110
|
+
logger.info('History sync skipped, transitioning to Online state and flushing buffer');
|
|
1111
|
+
ev.flush();
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
const doAppStateSync = async () => {
|
|
1115
|
+
if (syncState === SyncState.Syncing) {
|
|
1116
|
+
// All collections will be synced, so clear any blocked ones
|
|
1117
|
+
blockedCollections.clear();
|
|
1118
|
+
// JAP@Fix (perf cache invalidation) --- a full sync is about to run for every
|
|
1119
|
+
// collection, so any per-collection "recently resynced" cache from appPatch()
|
|
1120
|
+
// is now stale by definition; drop it so the next appPatch() call resyncs fresh
|
|
1121
|
+
// instead of trusting a pre-full-sync timestamp.
|
|
1122
|
+
lastResyncAt.clear();
|
|
1123
|
+
logger.info('Doing app state sync');
|
|
1124
|
+
await resyncAppState(ALL_WA_PATCH_NAMES, true);
|
|
1125
|
+
// Sync is complete, go online and flush everything
|
|
1126
|
+
syncState = SyncState.Online;
|
|
1127
|
+
logger.info('App state sync complete, transitioning to Online state and flushing buffer');
|
|
1128
|
+
ev.flush();
|
|
1129
|
+
const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
|
|
1130
|
+
ev.emit('creds.update', { accountSyncCounter });
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
await Promise.all([
|
|
1134
|
+
(async () => {
|
|
1135
|
+
if (shouldProcessHistoryMsg) {
|
|
1136
|
+
await doAppStateSync();
|
|
1137
|
+
}
|
|
1138
|
+
})(),
|
|
1139
|
+
processMessage(msg, {
|
|
1140
|
+
signalRepository,
|
|
1141
|
+
shouldProcessHistoryMsg,
|
|
1142
|
+
placeholderResendCache,
|
|
1143
|
+
ev,
|
|
1144
|
+
creds: authState.creds,
|
|
1145
|
+
keyStore: authState.keys,
|
|
1146
|
+
logger,
|
|
1147
|
+
options: config.options,
|
|
1148
|
+
getMessage
|
|
1149
|
+
})
|
|
1150
|
+
]);
|
|
1151
|
+
// If the app state key arrives and we are waiting to sync, trigger the sync now.
|
|
1152
|
+
if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
|
|
1153
|
+
logger.info('App state sync key arrived, triggering app state sync');
|
|
1154
|
+
await doAppStateSync();
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
ws.on('CB:presence', handlePresenceUpdate);
|
|
1158
|
+
ws.on('CB:chatstate', handlePresenceUpdate);
|
|
1159
|
+
ws.on('CB:ib,,dirty', async (node) => {
|
|
1160
|
+
const { attrs } = getBinaryNodeChild(node, 'dirty');
|
|
1161
|
+
const type = attrs.type;
|
|
1162
|
+
switch (type) {
|
|
1163
|
+
case 'account_sync':
|
|
1164
|
+
if (attrs.timestamp) {
|
|
1165
|
+
let { lastAccountSyncTimestamp } = authState.creds;
|
|
1166
|
+
if (lastAccountSyncTimestamp) {
|
|
1167
|
+
await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
|
|
1168
|
+
}
|
|
1169
|
+
lastAccountSyncTimestamp = +attrs.timestamp;
|
|
1170
|
+
ev.emit('creds.update', { lastAccountSyncTimestamp });
|
|
1171
|
+
}
|
|
1172
|
+
break;
|
|
1173
|
+
case 'groups':
|
|
1174
|
+
// handled in groups.ts
|
|
1175
|
+
break;
|
|
1176
|
+
default:
|
|
1177
|
+
logger.info({ node }, 'received unknown sync');
|
|
1178
|
+
break;
|
|
1179
|
+
}
|
|
1180
|
+
});
|
|
1181
|
+
ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
|
|
1182
|
+
if (connection === 'close') {
|
|
1183
|
+
blockedCollections.clear();
|
|
1184
|
+
// JAP@Fix (perf cache invalidation) --- connection dropped, so any "recently
|
|
1185
|
+
// resynced" timestamps are no longer trustworthy once we reconnect.
|
|
1186
|
+
lastResyncAt.clear();
|
|
1187
|
+
clearTimeout(historySyncPausedTimeout);
|
|
1188
|
+
historySyncPausedTimeout = undefined;
|
|
1189
|
+
}
|
|
1190
|
+
if (connection === 'open') {
|
|
1191
|
+
if (fireInitQueries) {
|
|
1192
|
+
executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
|
|
1193
|
+
}
|
|
1194
|
+
sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
|
|
1195
|
+
}
|
|
1196
|
+
if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
historySyncStatus.initialBootstrapComplete = false;
|
|
1200
|
+
historySyncStatus.recentSyncComplete = false;
|
|
1201
|
+
clearTimeout(historySyncPausedTimeout);
|
|
1202
|
+
historySyncPausedTimeout = undefined;
|
|
1203
|
+
syncState = SyncState.AwaitingInitialSync;
|
|
1204
|
+
logger.info('Connection is now AwaitingInitialSync, buffering events');
|
|
1205
|
+
ev.buffer();
|
|
1206
|
+
const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
|
|
1207
|
+
syncType: proto.HistorySync.HistorySyncType.RECENT
|
|
1208
|
+
}));
|
|
1209
|
+
if (!willSyncHistory) {
|
|
1210
|
+
logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
|
|
1211
|
+
syncState = SyncState.Online;
|
|
1212
|
+
setTimeout(() => ev.flush(), 0);
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
// On reconnection (accountSyncCounter > 0), the server does not push
|
|
1216
|
+
// history sync notifications — the device already has its data.
|
|
1217
|
+
// Skip the 20s wait and go online immediately.
|
|
1218
|
+
if (authState.creds.accountSyncCounter > 0) {
|
|
1219
|
+
logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
|
|
1220
|
+
syncState = SyncState.Online;
|
|
1221
|
+
setTimeout(() => ev.flush(), 0);
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
logger.info('First connection, awaiting history sync notification with a 20s timeout.');
|
|
1225
|
+
if (awaitingSyncTimeout) {
|
|
1226
|
+
clearTimeout(awaitingSyncTimeout);
|
|
1227
|
+
}
|
|
1228
|
+
awaitingSyncTimeout = setTimeout(() => {
|
|
1229
|
+
if (syncState === SyncState.AwaitingInitialSync) {
|
|
1230
|
+
logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
|
|
1231
|
+
syncState = SyncState.Online;
|
|
1232
|
+
ev.flush();
|
|
1233
|
+
// Increment so subsequent reconnections skip the 20s wait.
|
|
1234
|
+
// Late-arriving history is still processed via processMessage
|
|
1235
|
+
// regardless of the state machine phase.
|
|
1236
|
+
const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
|
|
1237
|
+
ev.emit('creds.update', { accountSyncCounter });
|
|
1238
|
+
}
|
|
1239
|
+
}, 20000);
|
|
1240
|
+
});
|
|
1241
|
+
// When an app state sync key arrives (myAppStateKeyId is set) and there are
|
|
1242
|
+
// collections blocked on a missing key, trigger a re-sync for just those collections.
|
|
1243
|
+
// This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
|
|
1244
|
+
ev.on('creds.update', ({ myAppStateKeyId }) => {
|
|
1245
|
+
if (!myAppStateKeyId || blockedCollections.size === 0) {
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
// If we're in the middle of a full sync, doAppStateSync handles all collections
|
|
1249
|
+
if (syncState === SyncState.Syncing) {
|
|
1250
|
+
blockedCollections.clear();
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
const collections = [...blockedCollections];
|
|
1254
|
+
blockedCollections.clear();
|
|
1255
|
+
logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
|
|
1256
|
+
resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
|
|
1257
|
+
});
|
|
1258
|
+
ev.on('lid-mapping.update', async ({ lid, pn }) => {
|
|
1259
|
+
try {
|
|
1260
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
|
|
1261
|
+
}
|
|
1262
|
+
catch (error) {
|
|
1263
|
+
logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
|
|
1264
|
+
}
|
|
1265
|
+
});
|
|
1266
|
+
registerSocketEndHandler(() => {
|
|
1267
|
+
if (awaitingSyncTimeout) {
|
|
1268
|
+
clearTimeout(awaitingSyncTimeout);
|
|
1269
|
+
awaitingSyncTimeout = undefined;
|
|
1270
|
+
}
|
|
1271
|
+
if (!config.placeholderResendCache && placeholderResendCache.close) {
|
|
1272
|
+
placeholderResendCache.close();
|
|
1273
|
+
}
|
|
1274
|
+
syncState = SyncState.Connecting;
|
|
1275
|
+
privacySettings = undefined;
|
|
1276
|
+
});
|
|
1277
|
+
return {
|
|
1278
|
+
...sock,
|
|
1279
|
+
findUserId,
|
|
1280
|
+
serverProps,
|
|
1281
|
+
createCallLink,
|
|
1282
|
+
getBotListV2,
|
|
1283
|
+
messageMutex,
|
|
1284
|
+
receiptMutex,
|
|
1285
|
+
appStatePatchMutex,
|
|
1286
|
+
notificationMutex,
|
|
1287
|
+
fetchPrivacySettings,
|
|
1288
|
+
upsertMessage,
|
|
1289
|
+
appPatch,
|
|
1290
|
+
sendPresenceUpdate,
|
|
1291
|
+
presenceSubscribe,
|
|
1292
|
+
profilePictureUrl,
|
|
1293
|
+
fetchBlocklist,
|
|
1294
|
+
fetchStatus,
|
|
1295
|
+
fetchDisappearingDuration,
|
|
1296
|
+
updateProfilePicture,
|
|
1297
|
+
removeProfilePicture,
|
|
1298
|
+
updateProfileStatus,
|
|
1299
|
+
updateProfileName,
|
|
1300
|
+
updateBlockStatus,
|
|
1301
|
+
updateDisableLinkPreviewsPrivacy,
|
|
1302
|
+
updateCallPrivacy,
|
|
1303
|
+
updateMessagesPrivacy,
|
|
1304
|
+
updateLastSeenPrivacy,
|
|
1305
|
+
updateOnlinePrivacy,
|
|
1306
|
+
updateProfilePicturePrivacy,
|
|
1307
|
+
updateStatusPrivacy,
|
|
1308
|
+
updateReadReceiptsPrivacy,
|
|
1309
|
+
updateGroupsAddPrivacy,
|
|
1310
|
+
updateDefaultDisappearingMode,
|
|
1311
|
+
getBusinessProfile,
|
|
1312
|
+
resyncAppState,
|
|
1313
|
+
chatModify,
|
|
1314
|
+
cleanDirtyBits,
|
|
1315
|
+
addOrEditContact,
|
|
1316
|
+
removeContact,
|
|
1317
|
+
placeholderResendCache,
|
|
1318
|
+
addLabel,
|
|
1319
|
+
addChatLabel,
|
|
1320
|
+
removeChatLabel,
|
|
1321
|
+
addMessageLabel,
|
|
1322
|
+
removeMessageLabel,
|
|
1323
|
+
star,
|
|
1324
|
+
addOrEditQuickReply,
|
|
1325
|
+
removeQuickReply
|
|
1326
|
+
};
|
|
1327
|
+
};
|