@kyyinfinite/baileys 1.0.0 → 2.0.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/README.md +408 -64
- package/WAProto/WAProto.proto +360 -916
- package/WAProto/fix-imports.js +22 -18
- package/WAProto/index.d.ts +14015 -0
- package/WAProto/index.js +47122 -81757
- package/engine-requirements.js +10 -0
- package/lib/Defaults/index.d.ts +15 -14
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +99 -107
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Kyyinfinite/AIRich.js +2041 -0
- package/lib/Kyyinfinite/BaseBuilder.js +64 -0
- package/lib/Kyyinfinite/Button.js +341 -0
- package/lib/Kyyinfinite/ButtonV2.js +175 -0
- package/lib/Kyyinfinite/Carousel.js +125 -0
- package/lib/Kyyinfinite/Foad.js +542 -0
- package/lib/Kyyinfinite/Foad2.js +466 -0
- package/lib/Kyyinfinite/Simple/AIBuilder.js +18 -0
- package/lib/Kyyinfinite/Simple/BuilderFactories.js +17 -0
- package/lib/Kyyinfinite/Simple/ButtonBuilder.js +107 -0
- package/lib/Kyyinfinite/Simple/CardBuilder.js +179 -0
- package/lib/Kyyinfinite/Simple/CarouselBuilder.js +97 -0
- package/lib/Kyyinfinite/Simple/FoadBuilder.js +18 -0
- package/lib/Kyyinfinite/Simple/MediaBuilder.js +35 -0
- package/lib/Kyyinfinite/Simple/MessageBuilder.js +41 -0
- package/lib/Kyyinfinite/Simple/MessageTypesBuilder.js +3 -0
- package/lib/Kyyinfinite/Simple/SimpleBuilder.js +28 -0
- package/lib/Kyyinfinite/Simple/SimpleClient.js +83 -0
- package/lib/Kyyinfinite/Simple/TextBuilder.js +22 -0
- package/lib/Kyyinfinite/Simple/index.d.ts +141 -0
- package/lib/Kyyinfinite/Simple/index.js +31 -0
- package/lib/Kyyinfinite/Toolkit.js +453 -0
- package/lib/Kyyinfinite/constants.js +1 -0
- package/lib/Kyyinfinite/errors.js +39 -0
- package/lib/Kyyinfinite/index.d.ts +2 -0
- package/lib/Kyyinfinite/index.js +2 -0
- package/lib/Kyyinfinite/wrapper.d.ts +2 -0
- package/lib/Kyyinfinite/wrapper.js +10 -0
- package/lib/Signal/Group/group_cipher.js.map +1 -1
- package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
- package/lib/Signal/Group/keyhelper.js.map +1 -1
- package/lib/Signal/Group/sender-chain-key.js.map +1 -1
- package/lib/Signal/Group/sender-key-message.js.map +1 -1
- package/lib/Signal/Group/sender-message-key.js.map +1 -1
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +45 -17
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts +4 -0
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js +6 -0
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/business.d.ts +213 -532
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/business.js +358 -401
- package/lib/Socket/chats.d.ts +16 -2
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +247 -40
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +269 -641
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/groups.d.ts +13 -2
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +21 -1
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +255 -631
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/index.js +9 -10
- package/lib/Socket/index.js.map +1 -1
- package/lib/Socket/messages-recv.d.ts +23 -58
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +645 -181
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +195 -575
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +1099 -1549
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/mex.d.ts.map +1 -1
- package/lib/Socket/mex.js +2 -8
- package/lib/Socket/mex.js.map +1 -1
- package/lib/Socket/newsletter.d.ts +11 -18
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +167 -302
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +6 -2
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +59 -25
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Bussines.d.ts +22 -34
- package/lib/Types/Call.d.ts +1 -1
- package/lib/Types/Call.d.ts.map +1 -1
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.d.ts.map +1 -1
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.d.ts.map +1 -1
- package/lib/Types/Events.d.ts +20 -1
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/GroupMetadata.d.ts +4 -1
- package/lib/Types/GroupMetadata.d.ts.map +1 -1
- package/lib/Types/Message.d.ts +239 -341
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +11 -5
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/{Newsletter.js → Mex.js} +9 -3
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Signal.d.ts +12 -1
- package/lib/Types/Signal.d.ts.map +1 -1
- package/lib/Types/Socket.d.ts +126 -148
- package/lib/Types/Socket.d.ts.map +1 -1
- package/lib/Types/State.d.ts +58 -0
- package/lib/Types/State.d.ts.map +1 -1
- package/lib/Types/State.js +43 -0
- package/lib/Types/State.js.map +1 -1
- package/lib/Types/index.d.ts +52 -52
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +23 -30
- package/lib/Types/index.js.map +1 -1
- package/lib/Utils/auth-utils.d.ts +5 -0
- package/lib/Utils/auth-utils.d.ts.map +1 -1
- package/lib/Utils/auth-utils.js +12 -0
- package/lib/Utils/auth-utils.js.map +1 -1
- package/lib/Utils/browser-utils.d.ts.map +1 -1
- package/lib/Utils/browser-utils.js +1 -0
- package/lib/Utils/browser-utils.js.map +1 -1
- package/lib/Utils/chat-utils.d.ts +34 -4
- package/lib/Utils/chat-utils.d.ts.map +1 -1
- package/lib/Utils/chat-utils.js +80 -20
- package/lib/Utils/chat-utils.js.map +1 -1
- package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/crypto.d.ts +12 -12
- package/lib/Utils/crypto.d.ts.map +1 -1
- package/lib/Utils/crypto.js.map +1 -1
- package/lib/Utils/decode-wa-message.d.ts +18 -0
- package/lib/Utils/decode-wa-message.d.ts.map +1 -1
- package/lib/Utils/decode-wa-message.js +34 -0
- package/lib/Utils/decode-wa-message.js.map +1 -1
- package/lib/Utils/event-buffer.d.ts +2 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -1
- package/lib/Utils/event-buffer.js +49 -1
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +3 -2
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +10 -1
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +2 -0
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +12 -9
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +7 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -1
- package/lib/Utils/identity-change-handler.js +1 -0
- package/lib/Utils/identity-change-handler.js.map +1 -1
- package/lib/Utils/index.d.ts +22 -25
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +2 -4
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/link-preview.js +2 -2
- package/lib/Utils/link-preview.js.map +1 -1
- package/lib/Utils/logger.d.ts +1 -2
- package/lib/Utils/logger.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.d.ts +5 -0
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +40 -0
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +16 -13
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +85 -79
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +1 -1
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +751 -1096
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/noise-handler.d.ts +1 -1
- package/lib/Utils/process-message.d.ts.map +1 -1
- package/lib/Utils/process-message.js +103 -1
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/signal.d.ts +13 -0
- package/lib/Utils/signal.d.ts.map +1 -1
- package/lib/Utils/signal.js +42 -0
- package/lib/Utils/signal.js.map +1 -1
- package/lib/Utils/sync-action-utils.d.ts.map +1 -1
- package/lib/Utils/sync-action-utils.js +1 -0
- package/lib/Utils/sync-action-utils.js.map +1 -1
- package/lib/Utils/tc-token-utils.d.ts +26 -1
- package/lib/Utils/tc-token-utils.d.ts.map +1 -1
- package/lib/Utils/tc-token-utils.js +151 -5
- package/lib/Utils/tc-token-utils.js.map +1 -1
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +12 -2
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/decode.d.ts +1 -1
- package/lib/WABinary/decode.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.d.ts +1 -3
- package/lib/WABinary/generic-utils.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.js +0 -78
- package/lib/WABinary/generic-utils.js.map +1 -1
- package/lib/WAM/encode.d.ts +1 -1
- package/lib/WAM/encode.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/index.js +1 -0
- package/lib/WAUSync/Protocols/index.js.map +1 -1
- package/lib/WAUSync/USyncQuery.d.ts +1 -0
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
- package/lib/WAUSync/USyncQuery.js +6 -2
- package/lib/WAUSync/USyncQuery.js.map +1 -1
- package/lib/WAUSync/USyncUser.d.ts +4 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -1
- package/lib/WAUSync/USyncUser.js +8 -0
- package/lib/WAUSync/USyncUser.js.map +1 -1
- package/lib/index.d.ts +3 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +13 -12
- package/lib/index.js.map +1 -1
- package/package.json +93 -23
- package/LICENSE +0 -21
- package/lib/Socket/dugong.d.ts +0 -130
- package/lib/Socket/dugong.d.ts.map +0 -1
- package/lib/Socket/dugong.js +0 -768
- package/lib/Socket/dugong.js.map +0 -1
- package/lib/Types/Newsletter.d.ts.map +0 -1
- package/lib/Types/Newsletter.js.map +0 -1
- package/lib/Utils/kyy-features.d.ts +0 -158
- package/lib/Utils/kyy-features.js +0 -365
- package/lib/Utils/rich-messages.d.ts +0 -277
- package/lib/Utils/rich-messages.d.ts.map +0 -1
- package/lib/Utils/rich-messages.js +0 -1144
- package/lib/Utils/rich-messages.js.map +0 -1
- package/lib/Utils/sticker-pack.d.ts +0 -10
- package/lib/Utils/sticker-pack.js +0 -111
|
@@ -1,1595 +1,1145 @@
|
|
|
1
|
-
import NodeCache from
|
|
2
|
-
import { Boom } from
|
|
3
|
-
import { proto } from
|
|
4
|
-
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
encryptMediaRetryRequest,
|
|
14
|
-
extractDeviceJids,
|
|
15
|
-
generateMessageIDV2,
|
|
16
|
-
generateParticipantHashV2,
|
|
17
|
-
generateWAMessage,
|
|
18
|
-
generateWAMessageFromContent,
|
|
19
|
-
getStatusCodeForMediaRetry,
|
|
20
|
-
getUrlFromDirectPath,
|
|
21
|
-
getWAUploadToServer,
|
|
22
|
-
MessageRetryManager,
|
|
23
|
-
normalizeMessageContent,
|
|
24
|
-
prepareWAMessageMedia,
|
|
25
|
-
parseAndInjectE2ESessions,
|
|
26
|
-
unixTimestampSeconds,
|
|
27
|
-
} from "../Utils/index.js";
|
|
28
|
-
import {
|
|
29
|
-
generateTableContent,
|
|
30
|
-
generateTableContentV2,
|
|
31
|
-
generateListContent,
|
|
32
|
-
generateCodeBlockContent,
|
|
33
|
-
generateCodeBlockContentV2,
|
|
34
|
-
generateLinkContent,
|
|
35
|
-
generateLinkContentV2,
|
|
36
|
-
generateRichMessageContent,
|
|
37
|
-
generateLatexContent,
|
|
38
|
-
generateLatexImageContent,
|
|
39
|
-
generateLatexInlineImageContent,
|
|
40
|
-
generateUnifiedResponseContent,
|
|
41
|
-
captureUnifiedResponse,
|
|
42
|
-
} from "../Utils/rich-messages.js";
|
|
43
|
-
import { getUrlInfo } from "../Utils/link-preview.js";
|
|
44
|
-
import { makeKeyedMutex } from "../Utils/make-mutex.js";
|
|
45
|
-
import {
|
|
46
|
-
getMessageReportingToken,
|
|
47
|
-
shouldIncludeReportingToken,
|
|
48
|
-
} from "../Utils/reporting-utils.js";
|
|
49
|
-
import {
|
|
50
|
-
areJidsSameUser,
|
|
51
|
-
getAdditionalNode,
|
|
52
|
-
getBinaryNodeChild,
|
|
53
|
-
getBinaryNodeChildren,
|
|
54
|
-
isHostedLidUser,
|
|
55
|
-
isHostedPnUser,
|
|
56
|
-
isJidGroup,
|
|
57
|
-
isJidNewsletter,
|
|
58
|
-
isLidUser,
|
|
59
|
-
isPnUser,
|
|
60
|
-
jidDecode,
|
|
61
|
-
jidEncode,
|
|
62
|
-
jidNormalizedUser,
|
|
63
|
-
S_WHATSAPP_NET,
|
|
64
|
-
} from "../WABinary/index.js";
|
|
65
|
-
import { USyncQuery, USyncUser } from "../WAUSync/index.js";
|
|
66
|
-
import { Dugong } from "./dugong.js";
|
|
67
|
-
import { makeNewsletterSocket } from "./newsletter.js";
|
|
68
|
-
const NATIVE_FLOW_BUTTON_MAP = {
|
|
69
|
-
review_and_pay: "order_details",
|
|
70
|
-
review_order: "order_status",
|
|
71
|
-
payment_info: "payment_info",
|
|
72
|
-
payment_status: "payment_status",
|
|
73
|
-
payment_method: "payment_method",
|
|
74
|
-
};
|
|
75
|
-
const getButtonType = (message) => {
|
|
76
|
-
const msg = normalizeMessageContent(message) || message;
|
|
77
|
-
if (msg?.buttonsMessage || msg?.listMessage)
|
|
78
|
-
return msg.listMessage ? "list" : "buttons";
|
|
79
|
-
const vm = msg?.viewOnceMessage?.message || msg?.viewOnceMessageV2?.message;
|
|
80
|
-
const im = vm?.interactiveMessage || msg?.interactiveMessage;
|
|
81
|
-
if (!im?.nativeFlowMessage) return null;
|
|
82
|
-
const btnName = im.nativeFlowMessage?.buttons?.[0]?.name;
|
|
83
|
-
if (btnName && NATIVE_FLOW_BUTTON_MAP[btnName])
|
|
84
|
-
return NATIVE_FLOW_BUTTON_MAP[btnName];
|
|
85
|
-
return "interactive";
|
|
86
|
-
};
|
|
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, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
5
|
+
import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
|
|
6
|
+
import { getUrlInfo } from '../Utils/link-preview.js';
|
|
7
|
+
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
|
|
8
|
+
import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
|
|
9
|
+
import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
|
|
10
|
+
import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
11
|
+
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
|
|
12
|
+
import { makeNewsletterSocket } from './newsletter.js';
|
|
87
13
|
export const makeMessagesSocket = (config) => {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
messageMutex,
|
|
103
|
-
signalRepository,
|
|
104
|
-
upsertMessage,
|
|
105
|
-
query,
|
|
106
|
-
fetchPrivacySettings,
|
|
107
|
-
sendNode,
|
|
108
|
-
groupMetadata,
|
|
109
|
-
groupToggleEphemeral,
|
|
110
|
-
} = sock;
|
|
111
|
-
const userDevicesCache =
|
|
112
|
-
config.userDevicesCache ||
|
|
113
|
-
new NodeCache({
|
|
114
|
-
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
|
115
|
-
useClones: false,
|
|
116
|
-
});
|
|
117
|
-
const peerSessionsCache = new NodeCache({
|
|
118
|
-
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
119
|
-
useClones: false,
|
|
120
|
-
});
|
|
121
|
-
// Initialize message retry manager if enabled
|
|
122
|
-
const messageRetryManager = enableRecentMessageCache
|
|
123
|
-
? new MessageRetryManager(logger, maxMsgRetryCount)
|
|
124
|
-
: null;
|
|
125
|
-
// Prevent race conditions in Signal session encryption by user
|
|
126
|
-
const encryptionMutex = makeKeyedMutex();
|
|
127
|
-
let mediaConn;
|
|
128
|
-
const refreshMediaConn = async (forceGet = false) => {
|
|
129
|
-
const media = await mediaConn;
|
|
130
|
-
if (
|
|
131
|
-
!media ||
|
|
132
|
-
forceGet ||
|
|
133
|
-
new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000
|
|
134
|
-
) {
|
|
135
|
-
mediaConn = (async () => {
|
|
136
|
-
const result = await query({
|
|
137
|
-
tag: "iq",
|
|
138
|
-
attrs: {
|
|
139
|
-
type: "set",
|
|
140
|
-
xmlns: "w:m",
|
|
141
|
-
to: S_WHATSAPP_NET,
|
|
142
|
-
},
|
|
143
|
-
content: [{ tag: "media_conn", attrs: {} }],
|
|
14
|
+
const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
|
|
15
|
+
const sock = makeNewsletterSocket(config);
|
|
16
|
+
const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
|
|
17
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
18
|
+
/**
|
|
19
|
+
* Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
|
|
20
|
+
* Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
|
|
21
|
+
* Entries are always removed in `.finally()`, so the set is bounded by concurrency.
|
|
22
|
+
*/
|
|
23
|
+
const inFlightTcTokenIssuance = new Set();
|
|
24
|
+
const userDevicesCache = config.userDevicesCache ||
|
|
25
|
+
new NodeCache({
|
|
26
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
|
27
|
+
useClones: false
|
|
144
28
|
});
|
|
145
|
-
|
|
146
|
-
|
|
29
|
+
/** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
|
|
30
|
+
const devicesMutex = makeMutex();
|
|
31
|
+
// Initialize message retry manager if enabled
|
|
32
|
+
const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
|
|
33
|
+
// Prevent race conditions in Signal session encryption by user
|
|
34
|
+
const encryptionMutex = makeKeyedMutex();
|
|
35
|
+
let mediaConn;
|
|
36
|
+
/** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
|
|
37
|
+
let mediaHost = DEF_MEDIA_HOST;
|
|
38
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
39
|
+
const media = await mediaConn;
|
|
40
|
+
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
41
|
+
mediaConn = (async () => {
|
|
42
|
+
const result = await query({
|
|
43
|
+
tag: 'iq',
|
|
44
|
+
attrs: {
|
|
45
|
+
type: 'set',
|
|
46
|
+
xmlns: 'w:m',
|
|
47
|
+
to: S_WHATSAPP_NET
|
|
48
|
+
},
|
|
49
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
50
|
+
});
|
|
51
|
+
const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
|
|
52
|
+
// TODO: explore full length of data that whatsapp provides
|
|
53
|
+
const node = {
|
|
54
|
+
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
55
|
+
hostname: attrs.hostname,
|
|
56
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
57
|
+
})),
|
|
58
|
+
auth: mediaConnNode.attrs.auth,
|
|
59
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
60
|
+
fetchDate: new Date()
|
|
61
|
+
};
|
|
62
|
+
logger.debug('fetched media conn');
|
|
63
|
+
if (node.hosts[0]) {
|
|
64
|
+
mediaHost = node.hosts[0].hostname;
|
|
65
|
+
}
|
|
66
|
+
return node;
|
|
67
|
+
})();
|
|
68
|
+
}
|
|
69
|
+
return mediaConn;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* generic send receipt function
|
|
73
|
+
* used for receipts of phone call, read, delivery etc.
|
|
74
|
+
* */
|
|
75
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
76
|
+
if (!messageIds || messageIds.length === 0) {
|
|
77
|
+
throw new Boom('missing ids in receipt');
|
|
78
|
+
}
|
|
147
79
|
const node = {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}),
|
|
153
|
-
),
|
|
154
|
-
auth: mediaConnNode.attrs.auth,
|
|
155
|
-
ttl: +mediaConnNode.attrs.ttl,
|
|
156
|
-
fetchDate: new Date(),
|
|
80
|
+
tag: 'receipt',
|
|
81
|
+
attrs: {
|
|
82
|
+
id: messageIds[0]
|
|
83
|
+
}
|
|
157
84
|
};
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
return mediaConn;
|
|
163
|
-
};
|
|
164
|
-
/**
|
|
165
|
-
* generic send receipt function
|
|
166
|
-
* used for receipts of phone call, read, delivery etc.
|
|
167
|
-
* */
|
|
168
|
-
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
169
|
-
if (!messageIds || messageIds.length === 0) {
|
|
170
|
-
throw new Boom("missing ids in receipt");
|
|
171
|
-
}
|
|
172
|
-
const node = {
|
|
173
|
-
tag: "receipt",
|
|
174
|
-
attrs: {
|
|
175
|
-
id: messageIds[0],
|
|
176
|
-
},
|
|
177
|
-
};
|
|
178
|
-
const isReadReceipt = type === "read" || type === "read-self";
|
|
179
|
-
if (isReadReceipt) {
|
|
180
|
-
node.attrs.t = unixTimestampSeconds().toString();
|
|
181
|
-
}
|
|
182
|
-
if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
|
|
183
|
-
node.attrs.recipient = jid;
|
|
184
|
-
node.attrs.to = participant;
|
|
185
|
-
} else {
|
|
186
|
-
node.attrs.to = jid;
|
|
187
|
-
if (participant) {
|
|
188
|
-
node.attrs.participant = participant;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
if (type) {
|
|
192
|
-
node.attrs.type = type;
|
|
193
|
-
}
|
|
194
|
-
const remainingMessageIds = messageIds.slice(1);
|
|
195
|
-
if (remainingMessageIds.length) {
|
|
196
|
-
node.content = [
|
|
197
|
-
{
|
|
198
|
-
tag: "list",
|
|
199
|
-
attrs: {},
|
|
200
|
-
content: remainingMessageIds.map((id) => ({
|
|
201
|
-
tag: "item",
|
|
202
|
-
attrs: { id },
|
|
203
|
-
})),
|
|
204
|
-
},
|
|
205
|
-
];
|
|
206
|
-
}
|
|
207
|
-
logger.debug(
|
|
208
|
-
{ attrs: node.attrs, messageIds },
|
|
209
|
-
"sending receipt for messages",
|
|
210
|
-
);
|
|
211
|
-
await sendNode(node);
|
|
212
|
-
};
|
|
213
|
-
/** Correctly bulk send receipts to multiple chats, participants */
|
|
214
|
-
const sendReceipts = async (keys, type) => {
|
|
215
|
-
const recps = aggregateMessageKeysNotFromMe(keys);
|
|
216
|
-
for (const { jid, participant, messageIds } of recps) {
|
|
217
|
-
await sendReceipt(jid, participant, messageIds, type);
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
/** Bulk read messages. Keys can be from different chats & participants */
|
|
221
|
-
const readMessages = async (keys) => {
|
|
222
|
-
const privacySettings = await fetchPrivacySettings();
|
|
223
|
-
// based on privacy settings, we have to change the read type
|
|
224
|
-
const readType =
|
|
225
|
-
privacySettings.readreceipts === "all" ? "read" : "read-self";
|
|
226
|
-
await sendReceipts(keys, readType);
|
|
227
|
-
};
|
|
228
|
-
/** Fetch all the devices we've to send a message to */
|
|
229
|
-
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
230
|
-
const deviceResults = [];
|
|
231
|
-
if (!useCache) {
|
|
232
|
-
logger.debug("not using cache for devices");
|
|
233
|
-
}
|
|
234
|
-
const toFetch = [];
|
|
235
|
-
const jidsWithUser = jids
|
|
236
|
-
.map((jid) => {
|
|
237
|
-
const decoded = jidDecode(jid);
|
|
238
|
-
const user = decoded?.user;
|
|
239
|
-
const device = decoded?.device;
|
|
240
|
-
const isExplicitDevice = typeof device === "number" && device >= 0;
|
|
241
|
-
if (isExplicitDevice && user) {
|
|
242
|
-
deviceResults.push({
|
|
243
|
-
user,
|
|
244
|
-
device,
|
|
245
|
-
jid,
|
|
246
|
-
});
|
|
247
|
-
return null;
|
|
85
|
+
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
86
|
+
if (isReadReceipt) {
|
|
87
|
+
node.attrs.t = unixTimestampSeconds().toString();
|
|
248
88
|
}
|
|
249
|
-
jid
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
.filter((jid) => jid !== null);
|
|
253
|
-
let mgetDevices;
|
|
254
|
-
if (useCache && userDevicesCache.mget) {
|
|
255
|
-
const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
|
|
256
|
-
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
257
|
-
}
|
|
258
|
-
for (const { jid, user } of jidsWithUser) {
|
|
259
|
-
if (useCache) {
|
|
260
|
-
const devices =
|
|
261
|
-
mgetDevices?.[user] ||
|
|
262
|
-
(userDevicesCache.mget
|
|
263
|
-
? undefined
|
|
264
|
-
: await userDevicesCache.get(user));
|
|
265
|
-
if (devices) {
|
|
266
|
-
const devicesWithJid = devices.map((d) => ({
|
|
267
|
-
...d,
|
|
268
|
-
jid: jidEncode(d.user, d.server, d.device),
|
|
269
|
-
}));
|
|
270
|
-
deviceResults.push(...devicesWithJid);
|
|
271
|
-
logger.trace({ user }, "using cache for devices");
|
|
272
|
-
} else {
|
|
273
|
-
toFetch.push(jid);
|
|
89
|
+
if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
|
|
90
|
+
node.attrs.recipient = jid;
|
|
91
|
+
node.attrs.to = participant;
|
|
274
92
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
return deviceResults;
|
|
281
|
-
}
|
|
282
|
-
const requestedLidUsers = new Set();
|
|
283
|
-
for (const jid of toFetch) {
|
|
284
|
-
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
285
|
-
const user = jidDecode(jid)?.user;
|
|
286
|
-
if (user) requestedLidUsers.add(user);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
const query = new USyncQuery()
|
|
290
|
-
.withContext("message")
|
|
291
|
-
.withDeviceProtocol()
|
|
292
|
-
.withLIDProtocol();
|
|
293
|
-
for (const jid of toFetch) {
|
|
294
|
-
query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
|
|
295
|
-
}
|
|
296
|
-
const result = await sock.executeUSyncQuery(query);
|
|
297
|
-
if (result) {
|
|
298
|
-
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
299
|
-
const lidResults = result.list.filter((a) => !!a.lid);
|
|
300
|
-
if (lidResults.length > 0) {
|
|
301
|
-
logger.trace("Storing LID maps from device call");
|
|
302
|
-
await signalRepository.lidMapping.storeLIDPNMappings(
|
|
303
|
-
lidResults.map((a) => ({ lid: a.lid, pn: a.id })),
|
|
304
|
-
);
|
|
305
|
-
// Force-refresh sessions for newly mapped LIDs to align identity addressing
|
|
306
|
-
try {
|
|
307
|
-
const lids = lidResults.map((a) => a.lid);
|
|
308
|
-
if (lids.length) {
|
|
309
|
-
await assertSessions(lids, true);
|
|
310
|
-
}
|
|
311
|
-
} catch (e) {
|
|
312
|
-
logger.warn(
|
|
313
|
-
{ e, count: lidResults.length },
|
|
314
|
-
"failed to assert sessions for newly mapped LIDs",
|
|
315
|
-
);
|
|
93
|
+
else {
|
|
94
|
+
node.attrs.to = jid;
|
|
95
|
+
if (participant) {
|
|
96
|
+
node.attrs.participant = participant;
|
|
97
|
+
}
|
|
316
98
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
result?.list,
|
|
320
|
-
authState.creds.me.id,
|
|
321
|
-
authState.creds.me.lid,
|
|
322
|
-
ignoreZeroDevices,
|
|
323
|
-
);
|
|
324
|
-
const deviceMap = {};
|
|
325
|
-
for (const item of extracted) {
|
|
326
|
-
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
327
|
-
deviceMap[item.user]?.push(item);
|
|
328
|
-
}
|
|
329
|
-
// Process each user's devices as a group for bulk LID migration
|
|
330
|
-
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
331
|
-
const isLidUser = requestedLidUsers.has(user);
|
|
332
|
-
// Process all devices for this user
|
|
333
|
-
for (const item of userDevices) {
|
|
334
|
-
const finalJid = isLidUser
|
|
335
|
-
? jidEncode(user, item.server, item.device)
|
|
336
|
-
: jidEncode(item.user, item.server, item.device);
|
|
337
|
-
deviceResults.push({
|
|
338
|
-
...item,
|
|
339
|
-
jid: finalJid,
|
|
340
|
-
});
|
|
341
|
-
logger.debug(
|
|
342
|
-
{
|
|
343
|
-
user: item.user,
|
|
344
|
-
device: item.device,
|
|
345
|
-
finalJid,
|
|
346
|
-
usedLid: isLidUser,
|
|
347
|
-
},
|
|
348
|
-
"Processed device with LID priority",
|
|
349
|
-
);
|
|
99
|
+
if (type) {
|
|
100
|
+
node.attrs.type = type;
|
|
350
101
|
}
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
102
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
103
|
+
if (remainingMessageIds.length) {
|
|
104
|
+
node.content = [
|
|
105
|
+
{
|
|
106
|
+
tag: 'list',
|
|
107
|
+
attrs: {},
|
|
108
|
+
content: remainingMessageIds.map(id => ({
|
|
109
|
+
tag: 'item',
|
|
110
|
+
attrs: { id }
|
|
111
|
+
}))
|
|
112
|
+
}
|
|
113
|
+
];
|
|
360
114
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
115
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
|
|
116
|
+
await sendNode(node);
|
|
117
|
+
};
|
|
118
|
+
/** Correctly bulk send receipts to multiple chats, participants */
|
|
119
|
+
const sendReceipts = async (keys, type) => {
|
|
120
|
+
const recps = aggregateMessageKeysNotFromMe(keys);
|
|
121
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
122
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
368
123
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
124
|
+
};
|
|
125
|
+
/** Bulk read messages. Keys can be from different chats & participants */
|
|
126
|
+
const readMessages = async (keys) => {
|
|
127
|
+
const privacySettings = await fetchPrivacySettings();
|
|
128
|
+
// based on privacy settings, we have to change the read type
|
|
129
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
130
|
+
await sendReceipts(keys, readType);
|
|
131
|
+
};
|
|
132
|
+
/** Fetch all the devices we've to send a message to */
|
|
133
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
134
|
+
const deviceResults = [];
|
|
135
|
+
if (!useCache) {
|
|
136
|
+
logger.debug('not using cache for devices');
|
|
379
137
|
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
attrs: {
|
|
404
|
-
tag_reason: "user_update",
|
|
405
|
-
appdata: "member_tag",
|
|
406
|
-
},
|
|
407
|
-
content: undefined,
|
|
408
|
-
},
|
|
409
|
-
],
|
|
410
|
-
},
|
|
411
|
-
);
|
|
412
|
-
};
|
|
413
|
-
const assertSessions = async (jids, force) => {
|
|
414
|
-
let didFetchNewSession = false;
|
|
415
|
-
const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
|
|
416
|
-
const jidsRequiringFetch = [];
|
|
417
|
-
logger.debug({ jids }, "assertSessions call with jids");
|
|
418
|
-
// Check peerSessionsCache and validate sessions using libsignal loadSession
|
|
419
|
-
for (const jid of uniqueJids) {
|
|
420
|
-
const signalId = signalRepository.jidToSignalProtocolAddress(jid);
|
|
421
|
-
const cachedSession = peerSessionsCache.get(signalId);
|
|
422
|
-
if (cachedSession !== undefined) {
|
|
423
|
-
if (cachedSession && !force) {
|
|
424
|
-
continue; // Session exists in cache
|
|
138
|
+
const toFetch = [];
|
|
139
|
+
const jidsWithUser = jids
|
|
140
|
+
.map(jid => {
|
|
141
|
+
const decoded = jidDecode(jid);
|
|
142
|
+
const user = decoded?.user;
|
|
143
|
+
const device = decoded?.device;
|
|
144
|
+
const isExplicitDevice = typeof device === 'number' && device >= 0;
|
|
145
|
+
if (isExplicitDevice && user) {
|
|
146
|
+
deviceResults.push({
|
|
147
|
+
user,
|
|
148
|
+
device,
|
|
149
|
+
jid
|
|
150
|
+
});
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
jid = jidNormalizedUser(jid);
|
|
154
|
+
return { jid, user };
|
|
155
|
+
})
|
|
156
|
+
.filter(jid => jid !== null);
|
|
157
|
+
let mgetDevices;
|
|
158
|
+
if (useCache && userDevicesCache.mget) {
|
|
159
|
+
const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
|
|
160
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
425
161
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
162
|
+
for (const { jid, user } of jidsWithUser) {
|
|
163
|
+
if (useCache) {
|
|
164
|
+
const devices = mgetDevices?.[user] ||
|
|
165
|
+
(userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
|
|
166
|
+
if (devices) {
|
|
167
|
+
const devicesWithJid = devices.map(d => ({
|
|
168
|
+
...d,
|
|
169
|
+
jid: jidEncode(d.user, d.server, d.device)
|
|
170
|
+
}));
|
|
171
|
+
deviceResults.push(...devicesWithJid);
|
|
172
|
+
logger.trace({ user }, 'using cache for devices');
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
toFetch.push(jid);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
toFetch.push(jid);
|
|
180
|
+
}
|
|
432
181
|
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
...(
|
|
443
|
-
(await signalRepository.lidMapping.getLIDsForPNs(
|
|
444
|
-
jidsRequiringFetch.filter(
|
|
445
|
-
(jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
|
|
446
|
-
),
|
|
447
|
-
)) || []
|
|
448
|
-
).map((a) => a.lid),
|
|
449
|
-
];
|
|
450
|
-
logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
|
|
451
|
-
const result = await query({
|
|
452
|
-
tag: "iq",
|
|
453
|
-
attrs: {
|
|
454
|
-
xmlns: "encrypt",
|
|
455
|
-
type: "get",
|
|
456
|
-
to: S_WHATSAPP_NET,
|
|
457
|
-
},
|
|
458
|
-
content: [
|
|
459
|
-
{
|
|
460
|
-
tag: "key",
|
|
461
|
-
attrs: {},
|
|
462
|
-
content: wireJids.map((jid) => {
|
|
463
|
-
const attrs = { jid };
|
|
464
|
-
if (force) attrs.reason = "identity";
|
|
465
|
-
return { tag: "user", attrs };
|
|
466
|
-
}),
|
|
467
|
-
},
|
|
468
|
-
],
|
|
469
|
-
});
|
|
470
|
-
await parseAndInjectE2ESessions(result, signalRepository);
|
|
471
|
-
didFetchNewSession = true;
|
|
472
|
-
// Cache fetched sessions using wire JIDs
|
|
473
|
-
for (const wireJid of wireJids) {
|
|
474
|
-
const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
|
|
475
|
-
peerSessionsCache.set(signalId, true);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
return didFetchNewSession;
|
|
479
|
-
};
|
|
480
|
-
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
481
|
-
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
|
482
|
-
if (!authState.creds.me?.id) {
|
|
483
|
-
throw new Boom("Not authenticated");
|
|
484
|
-
}
|
|
485
|
-
const protocolMessage = {
|
|
486
|
-
protocolMessage: {
|
|
487
|
-
peerDataOperationRequestMessage: pdoMessage,
|
|
488
|
-
type: proto.Message.ProtocolMessage.Type
|
|
489
|
-
.PEER_DATA_OPERATION_REQUEST_MESSAGE,
|
|
490
|
-
},
|
|
491
|
-
};
|
|
492
|
-
const meJid = jidNormalizedUser(authState.creds.me.id);
|
|
493
|
-
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
494
|
-
additionalAttributes: {
|
|
495
|
-
category: "peer",
|
|
496
|
-
push_priority: "high_force",
|
|
497
|
-
},
|
|
498
|
-
additionalNodes: [
|
|
499
|
-
{
|
|
500
|
-
tag: "meta",
|
|
501
|
-
attrs: { appdata: "default" },
|
|
502
|
-
},
|
|
503
|
-
],
|
|
504
|
-
});
|
|
505
|
-
return msgId;
|
|
506
|
-
};
|
|
507
|
-
const createParticipantNodes = async (
|
|
508
|
-
recipientJids,
|
|
509
|
-
message,
|
|
510
|
-
extraAttrs,
|
|
511
|
-
dsmMessage,
|
|
512
|
-
) => {
|
|
513
|
-
if (!recipientJids.length) {
|
|
514
|
-
return { nodes: [], shouldIncludeDeviceIdentity: false };
|
|
515
|
-
}
|
|
516
|
-
const patched = await patchMessageBeforeSending(message, recipientJids);
|
|
517
|
-
const patchedMessages = Array.isArray(patched)
|
|
518
|
-
? patched
|
|
519
|
-
: recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
|
|
520
|
-
let shouldIncludeDeviceIdentity = false;
|
|
521
|
-
const meId = authState.creds.me.id;
|
|
522
|
-
const meLid = authState.creds.me?.lid;
|
|
523
|
-
const meLidUser = meLid ? jidDecode(meLid)?.user : null;
|
|
524
|
-
const encryptionPromises = patchedMessages.map(
|
|
525
|
-
async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
526
|
-
try {
|
|
527
|
-
if (!jid) return null;
|
|
528
|
-
let msgToEncrypt = patchedMessage;
|
|
529
|
-
if (dsmMessage) {
|
|
530
|
-
const { user: targetUser } = jidDecode(jid);
|
|
531
|
-
const { user: ownPnUser } = jidDecode(meId);
|
|
532
|
-
const ownLidUser = meLidUser;
|
|
533
|
-
const isOwnUser =
|
|
534
|
-
targetUser === ownPnUser ||
|
|
535
|
-
(ownLidUser && targetUser === ownLidUser);
|
|
536
|
-
const isExactSenderDevice =
|
|
537
|
-
jid === meId || (meLid && jid === meLid);
|
|
538
|
-
if (isOwnUser && !isExactSenderDevice) {
|
|
539
|
-
msgToEncrypt = dsmMessage;
|
|
540
|
-
logger.debug({ jid, targetUser }, "Using DSM for own device");
|
|
182
|
+
if (!toFetch.length) {
|
|
183
|
+
return deviceResults;
|
|
184
|
+
}
|
|
185
|
+
const requestedLidUsers = new Set();
|
|
186
|
+
for (const jid of toFetch) {
|
|
187
|
+
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
188
|
+
const user = jidDecode(jid)?.user;
|
|
189
|
+
if (user)
|
|
190
|
+
requestedLidUsers.add(user);
|
|
541
191
|
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
192
|
+
}
|
|
193
|
+
const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
|
|
194
|
+
for (const jid of toFetch) {
|
|
195
|
+
query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
|
|
196
|
+
}
|
|
197
|
+
const result = await sock.executeUSyncQuery(query);
|
|
198
|
+
if (result) {
|
|
199
|
+
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
200
|
+
const lidResults = result.list.filter(a => !!a.lid);
|
|
201
|
+
if (lidResults.length > 0) {
|
|
202
|
+
logger.trace('Storing LID maps from device call');
|
|
203
|
+
await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
|
|
204
|
+
// Force-refresh sessions for newly mapped LIDs to align identity addressing
|
|
205
|
+
try {
|
|
206
|
+
const lids = lidResults.map(a => a.lid);
|
|
207
|
+
if (lids.length) {
|
|
208
|
+
await assertSessions(lids, true);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch (e) {
|
|
212
|
+
logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
|
|
216
|
+
const deviceMap = {};
|
|
217
|
+
for (const item of extracted) {
|
|
218
|
+
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
219
|
+
deviceMap[item.user]?.push(item);
|
|
220
|
+
}
|
|
221
|
+
// Process each user's devices as a group for bulk LID migration
|
|
222
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
223
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
224
|
+
// Process all devices for this user
|
|
225
|
+
for (const item of userDevices) {
|
|
226
|
+
const finalJid = isLidUser
|
|
227
|
+
? jidEncode(user, item.server, item.device)
|
|
228
|
+
: jidEncode(item.user, item.server, item.device);
|
|
229
|
+
deviceResults.push({
|
|
230
|
+
...item,
|
|
231
|
+
jid: finalJid
|
|
232
|
+
});
|
|
233
|
+
logger.debug({
|
|
234
|
+
user: item.user,
|
|
235
|
+
device: item.device,
|
|
236
|
+
finalJid,
|
|
237
|
+
usedLid: isLidUser
|
|
238
|
+
}, 'Processed device with LID priority');
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
await devicesMutex.mutex(async () => {
|
|
242
|
+
if (userDevicesCache.mset) {
|
|
243
|
+
// if the cache supports mset, we can set all devices in one go
|
|
244
|
+
await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
for (const key in deviceMap) {
|
|
248
|
+
if (deviceMap[key])
|
|
249
|
+
await userDevicesCache.set(key, deviceMap[key]);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
549
252
|
});
|
|
550
|
-
|
|
551
|
-
|
|
253
|
+
const userDeviceUpdates = {};
|
|
254
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
255
|
+
if (devices && devices.length > 0) {
|
|
256
|
+
userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
|
|
257
|
+
}
|
|
552
258
|
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
259
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
260
|
+
try {
|
|
261
|
+
await authState.keys.set({ 'device-list': userDeviceUpdates });
|
|
262
|
+
logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
logger.warn({ error }, 'failed to store user device lists');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return deviceResults;
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Update Member Label
|
|
273
|
+
*/
|
|
274
|
+
const updateMemberLabel = (jid, memberLabel) => {
|
|
275
|
+
return relayMessage(jid, {
|
|
276
|
+
protocolMessage: {
|
|
277
|
+
type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
|
|
278
|
+
memberLabel: {
|
|
279
|
+
label: memberLabel?.slice(0, 30),
|
|
280
|
+
labelTimestamp: unixTimestampSeconds()
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}, {
|
|
284
|
+
additionalNodes: [
|
|
557
285
|
{
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
286
|
+
tag: 'meta',
|
|
287
|
+
attrs: {
|
|
288
|
+
tag_reason: 'user_update',
|
|
289
|
+
appdata: 'member_tag'
|
|
290
|
+
},
|
|
291
|
+
content: undefined
|
|
292
|
+
}
|
|
293
|
+
]
|
|
294
|
+
});
|
|
295
|
+
};
|
|
296
|
+
const assertSessions = async (jids, force) => {
|
|
297
|
+
let didFetchNewSession = false;
|
|
298
|
+
const uniqueJids = [...new Set(jids)];
|
|
299
|
+
const jidsRequiringFetch = [];
|
|
300
|
+
logger.debug({ jids }, 'assertSessions call with jids');
|
|
301
|
+
for (const jid of uniqueJids) {
|
|
302
|
+
if (!force) {
|
|
303
|
+
const sessionValidation = await signalRepository.validateSession(jid);
|
|
304
|
+
if (sessionValidation.exists) {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
jidsRequiringFetch.push(jid);
|
|
309
|
+
}
|
|
310
|
+
if (jidsRequiringFetch.length) {
|
|
311
|
+
// LID if mapped, otherwise original
|
|
312
|
+
const wireJids = [
|
|
313
|
+
...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
314
|
+
...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
|
|
315
|
+
];
|
|
316
|
+
logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
|
|
317
|
+
const result = await query({
|
|
318
|
+
tag: 'iq',
|
|
319
|
+
attrs: {
|
|
320
|
+
xmlns: 'encrypt',
|
|
321
|
+
type: 'get',
|
|
322
|
+
to: S_WHATSAPP_NET
|
|
561
323
|
},
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
324
|
+
content: [
|
|
325
|
+
{
|
|
326
|
+
tag: 'key',
|
|
327
|
+
attrs: {},
|
|
328
|
+
content: wireJids.map(jid => {
|
|
329
|
+
const attrs = { jid };
|
|
330
|
+
if (force)
|
|
331
|
+
attrs.reason = 'identity';
|
|
332
|
+
return { tag: 'user', attrs };
|
|
333
|
+
})
|
|
334
|
+
}
|
|
335
|
+
]
|
|
336
|
+
});
|
|
337
|
+
await parseAndInjectE2ESessions(result, signalRepository);
|
|
338
|
+
didFetchNewSession = true;
|
|
569
339
|
}
|
|
570
|
-
|
|
571
|
-
);
|
|
572
|
-
const nodes = (await Promise.all(encryptionPromises)).filter(
|
|
573
|
-
(node) => node !== null,
|
|
574
|
-
);
|
|
575
|
-
if (recipientJids.length > 0 && nodes.length === 0) {
|
|
576
|
-
throw new Boom("All encryptions failed", { statusCode: 500 });
|
|
577
|
-
}
|
|
578
|
-
return { nodes, shouldIncludeDeviceIdentity };
|
|
579
|
-
};
|
|
580
|
-
const relayMessage = async (
|
|
581
|
-
jid,
|
|
582
|
-
message,
|
|
583
|
-
{
|
|
584
|
-
messageId: msgId,
|
|
585
|
-
participant,
|
|
586
|
-
additionalAttributes,
|
|
587
|
-
additionalNodes,
|
|
588
|
-
useUserDevicesCache,
|
|
589
|
-
useCachedGroupMetadata,
|
|
590
|
-
statusJidList,
|
|
591
|
-
},
|
|
592
|
-
) => {
|
|
593
|
-
const meId = authState.creds.me.id;
|
|
594
|
-
const meLid = authState.creds.me?.lid;
|
|
595
|
-
const isRetryResend = Boolean(participant?.jid);
|
|
596
|
-
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
597
|
-
const statusJid = "status@broadcast";
|
|
598
|
-
const { user, server } = jidDecode(jid);
|
|
599
|
-
const isGroup = server === "g.us";
|
|
600
|
-
const isStatus = jid === statusJid;
|
|
601
|
-
const isLid = server === "lid";
|
|
602
|
-
const isNewsletter = server === "newsletter";
|
|
603
|
-
const isGroupOrStatus = isGroup || isStatus;
|
|
604
|
-
const finalJid = jid;
|
|
605
|
-
msgId = msgId || generateMessageIDV2(meId);
|
|
606
|
-
useUserDevicesCache = useUserDevicesCache !== false;
|
|
607
|
-
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
608
|
-
const participants = [];
|
|
609
|
-
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
610
|
-
const binaryNodeContent = [];
|
|
611
|
-
const devices = [];
|
|
612
|
-
let reportingMessage;
|
|
613
|
-
const meMsg = {
|
|
614
|
-
deviceSentMessage: {
|
|
615
|
-
destinationJid,
|
|
616
|
-
message,
|
|
617
|
-
},
|
|
618
|
-
messageContextInfo: message.messageContextInfo,
|
|
340
|
+
return didFetchNewSession;
|
|
619
341
|
};
|
|
620
|
-
const
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
342
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
343
|
+
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
|
344
|
+
if (!authState.creds.me?.id) {
|
|
345
|
+
throw new Boom('Not authenticated');
|
|
346
|
+
}
|
|
347
|
+
const protocolMessage = {
|
|
348
|
+
protocolMessage: {
|
|
349
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
350
|
+
type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
|
|
351
|
+
}
|
|
626
352
|
};
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
if (mediaType) {
|
|
640
|
-
extraAttrs["mediatype"] = mediaType;
|
|
641
|
-
}
|
|
642
|
-
if (isNewsletter) {
|
|
643
|
-
const patched = patchMessageBeforeSending
|
|
644
|
-
? await patchMessageBeforeSending(message, [])
|
|
645
|
-
: message;
|
|
646
|
-
const bytes = encodeNewsletterMessage(patched);
|
|
647
|
-
binaryNodeContent.push({
|
|
648
|
-
tag: "plaintext",
|
|
649
|
-
attrs: extraAttrs || {},
|
|
650
|
-
content: bytes,
|
|
353
|
+
const meJid = jidNormalizedUser(authState.creds.me.id);
|
|
354
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
355
|
+
additionalAttributes: {
|
|
356
|
+
category: 'peer',
|
|
357
|
+
push_priority: 'high_force'
|
|
358
|
+
},
|
|
359
|
+
additionalNodes: [
|
|
360
|
+
{
|
|
361
|
+
tag: 'meta',
|
|
362
|
+
attrs: { appdata: 'default' }
|
|
363
|
+
}
|
|
364
|
+
]
|
|
651
365
|
});
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
366
|
+
return msgId;
|
|
367
|
+
};
|
|
368
|
+
const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
|
|
369
|
+
if (!recipientJids.length) {
|
|
370
|
+
return { nodes: [], shouldIncludeDeviceIdentity: false };
|
|
371
|
+
}
|
|
372
|
+
const patched = await patchMessageBeforeSending(message, recipientJids);
|
|
373
|
+
const patchedMessages = Array.isArray(patched)
|
|
374
|
+
? patched
|
|
375
|
+
: recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
|
|
376
|
+
let shouldIncludeDeviceIdentity = false;
|
|
377
|
+
const meId = authState.creds.me.id;
|
|
378
|
+
const meLid = authState.creds.me?.lid;
|
|
379
|
+
const meLidUser = meLid ? jidDecode(meLid)?.user : null;
|
|
380
|
+
const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
381
|
+
try {
|
|
382
|
+
if (!jid)
|
|
383
|
+
return null;
|
|
384
|
+
let msgToEncrypt = patchedMessage;
|
|
385
|
+
if (dsmMessage) {
|
|
386
|
+
const { user: targetUser } = jidDecode(jid);
|
|
387
|
+
const { user: ownPnUser } = jidDecode(meId);
|
|
388
|
+
const ownLidUser = meLidUser;
|
|
389
|
+
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
|
|
390
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
391
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
392
|
+
msgToEncrypt = dsmMessage;
|
|
393
|
+
logger.debug({ jid, targetUser }, 'Using DSM for own device');
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const bytes = encodeWAMessage(msgToEncrypt);
|
|
397
|
+
const mutexKey = jid;
|
|
398
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
399
|
+
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
|
|
400
|
+
if (type === 'pkmsg') {
|
|
401
|
+
shouldIncludeDeviceIdentity = true;
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
tag: 'to',
|
|
405
|
+
attrs: { jid },
|
|
406
|
+
content: [
|
|
407
|
+
{
|
|
408
|
+
tag: 'enc',
|
|
409
|
+
attrs: { v: '2', type, ...(extraAttrs || {}) },
|
|
410
|
+
content: ciphertext
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
return node;
|
|
416
|
+
}
|
|
417
|
+
catch (err) {
|
|
418
|
+
logger.error({ jid, err }, 'Failed to encrypt for recipient');
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
|
|
423
|
+
if (recipientJids.length > 0 && nodes.length === 0) {
|
|
424
|
+
throw new Boom('All encryptions failed', { statusCode: 500 });
|
|
425
|
+
}
|
|
426
|
+
return { nodes, shouldIncludeDeviceIdentity };
|
|
427
|
+
};
|
|
428
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
|
|
429
|
+
const meId = assertMeId(authState.creds);
|
|
430
|
+
const meLid = authState.creds.me?.lid;
|
|
431
|
+
const isRetryResend = Boolean(participant?.jid);
|
|
432
|
+
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
433
|
+
const statusJid = 'status@broadcast';
|
|
434
|
+
const { user, server } = jidDecode(jid);
|
|
435
|
+
const isGroup = server === 'g.us';
|
|
436
|
+
const isStatus = jid === statusJid;
|
|
437
|
+
const isLid = server === 'lid';
|
|
438
|
+
const isNewsletter = server === 'newsletter';
|
|
439
|
+
const isGroupOrStatus = isGroup || isStatus;
|
|
440
|
+
const finalJid = jid;
|
|
441
|
+
msgId = msgId || generateMessageIDV2(meId);
|
|
442
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
443
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
444
|
+
const participants = [];
|
|
445
|
+
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
446
|
+
const binaryNodeContent = [];
|
|
447
|
+
const devices = [];
|
|
448
|
+
let reportingMessage;
|
|
449
|
+
const meMsg = {
|
|
450
|
+
deviceSentMessage: {
|
|
451
|
+
destinationJid,
|
|
452
|
+
message
|
|
453
|
+
},
|
|
454
|
+
messageContextInfo: message.messageContextInfo
|
|
661
455
|
};
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
if (
|
|
667
|
-
normalizeMessageContent(message)?.pinInChatMessage ||
|
|
668
|
-
normalizeMessageContent(message)?.reactionMessage
|
|
669
|
-
) {
|
|
670
|
-
extraAttrs["decrypt-fail"] = "hide"; // todo: expand for reactions and other types
|
|
671
|
-
}
|
|
672
|
-
if (isGroupOrStatus && !isRetryResend) {
|
|
673
|
-
const [groupData, senderKeyMap] = await Promise.all([
|
|
674
|
-
(async () => {
|
|
675
|
-
let groupData =
|
|
676
|
-
useCachedGroupMetadata && cachedGroupMetadata
|
|
677
|
-
? await cachedGroupMetadata(jid)
|
|
678
|
-
: undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
|
|
679
|
-
if (groupData && Array.isArray(groupData?.participants)) {
|
|
680
|
-
logger.trace(
|
|
681
|
-
{ jid, participants: groupData.participants.length },
|
|
682
|
-
"using cached group metadata",
|
|
683
|
-
);
|
|
684
|
-
} else if (!isStatus) {
|
|
685
|
-
groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
456
|
+
const extraAttrs = {};
|
|
457
|
+
if (participant) {
|
|
458
|
+
if (!isGroup && !isStatus) {
|
|
459
|
+
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
|
|
686
460
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
461
|
+
const { user, device } = jidDecode(participant.jid);
|
|
462
|
+
devices.push({
|
|
463
|
+
user,
|
|
464
|
+
device,
|
|
465
|
+
jid: participant.jid
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
await authState.keys.transaction(async () => {
|
|
469
|
+
const mediaType = getMediaType(message);
|
|
470
|
+
if (mediaType) {
|
|
471
|
+
extraAttrs['mediatype'] = mediaType;
|
|
472
|
+
}
|
|
473
|
+
if (isNewsletter) {
|
|
474
|
+
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
|
|
475
|
+
const bytes = encodeNewsletterMessage(patched);
|
|
476
|
+
binaryNodeContent.push({
|
|
477
|
+
tag: 'plaintext',
|
|
478
|
+
attrs: {},
|
|
479
|
+
content: bytes
|
|
480
|
+
});
|
|
481
|
+
const stanza = {
|
|
482
|
+
tag: 'message',
|
|
483
|
+
attrs: {
|
|
484
|
+
to: jid,
|
|
485
|
+
id: msgId,
|
|
486
|
+
type: getMessageType(message),
|
|
487
|
+
...(additionalAttributes || {})
|
|
488
|
+
},
|
|
489
|
+
content: binaryNodeContent
|
|
490
|
+
};
|
|
491
|
+
logger.debug({ msgId }, `sending newsletter message to ${jid}`);
|
|
492
|
+
await sendNode(stanza);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
|
|
496
|
+
extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
|
|
697
497
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
498
|
+
if (isGroupOrStatus && !isRetryResend) {
|
|
499
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
500
|
+
(async () => {
|
|
501
|
+
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
|
|
502
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
503
|
+
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
|
|
504
|
+
}
|
|
505
|
+
else if (!isStatus) {
|
|
506
|
+
groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
507
|
+
}
|
|
508
|
+
return groupData;
|
|
509
|
+
})(),
|
|
510
|
+
(async () => {
|
|
511
|
+
if (!participant && !isStatus) {
|
|
512
|
+
// what if sender memory is less accurate than the cached metadata
|
|
513
|
+
// on participant change in group, we should do sender memory manipulation
|
|
514
|
+
const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
|
|
515
|
+
return result[jid] || {};
|
|
516
|
+
}
|
|
517
|
+
return {};
|
|
518
|
+
})()
|
|
519
|
+
]);
|
|
520
|
+
const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
|
|
521
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
522
|
+
additionalAttributes = {
|
|
523
|
+
...additionalAttributes,
|
|
524
|
+
expiration: groupData.ephemeralDuration.toString()
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
if (isStatus && statusJidList) {
|
|
528
|
+
participantsList.push(...statusJidList);
|
|
529
|
+
}
|
|
530
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
|
|
531
|
+
devices.push(...additionalDevices);
|
|
532
|
+
if (isGroup) {
|
|
533
|
+
additionalAttributes = {
|
|
534
|
+
...additionalAttributes,
|
|
535
|
+
addressing_mode: groupData?.addressingMode || 'lid'
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
const patched = await patchMessageBeforeSending(message);
|
|
539
|
+
if (Array.isArray(patched)) {
|
|
540
|
+
throw new Boom('Per-jid patching is not supported in groups');
|
|
541
|
+
}
|
|
542
|
+
const bytes = encodeWAMessage(patched);
|
|
543
|
+
reportingMessage = patched;
|
|
544
|
+
const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
|
|
545
|
+
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
|
|
546
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
547
|
+
group: destinationJid,
|
|
548
|
+
data: bytes,
|
|
549
|
+
meId: groupSenderIdentity
|
|
550
|
+
});
|
|
551
|
+
const senderKeyRecipients = [];
|
|
552
|
+
for (const device of devices) {
|
|
553
|
+
const deviceJid = device.jid;
|
|
554
|
+
const hasKey = !!senderKeyMap[deviceJid];
|
|
555
|
+
if ((!hasKey || !!participant) &&
|
|
556
|
+
!isHostedLidUser(deviceJid) &&
|
|
557
|
+
!isHostedPnUser(deviceJid) &&
|
|
558
|
+
device.device !== 99) {
|
|
559
|
+
//todo: revamp all this logic
|
|
560
|
+
// the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
|
|
561
|
+
senderKeyRecipients.push(deviceJid);
|
|
562
|
+
senderKeyMap[deviceJid] = true;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (senderKeyRecipients.length) {
|
|
566
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
|
|
567
|
+
const senderKeyMsg = {
|
|
568
|
+
senderKeyDistributionMessage: {
|
|
569
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
570
|
+
groupId: destinationJid
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
const senderKeySessionTargets = senderKeyRecipients;
|
|
574
|
+
await assertSessions(senderKeySessionTargets);
|
|
575
|
+
const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
|
|
576
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
577
|
+
participants.push(...result.nodes);
|
|
578
|
+
}
|
|
579
|
+
binaryNodeContent.push({
|
|
580
|
+
tag: 'enc',
|
|
581
|
+
attrs: { v: '2', type: 'skmsg', ...extraAttrs },
|
|
582
|
+
content: ciphertext
|
|
583
|
+
});
|
|
584
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
588
|
+
// TODO: investigate if this is true
|
|
589
|
+
let ownId = meId;
|
|
590
|
+
if (isLid && meLid) {
|
|
591
|
+
ownId = meLid;
|
|
592
|
+
logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
|
|
596
|
+
}
|
|
597
|
+
const { user: ownUser } = jidDecode(ownId);
|
|
598
|
+
if (!participant) {
|
|
599
|
+
const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
|
|
600
|
+
reportingMessage = Array.isArray(patchedForReporting)
|
|
601
|
+
? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
|
|
602
|
+
: patchedForReporting;
|
|
603
|
+
}
|
|
604
|
+
if (!isRetryResend) {
|
|
605
|
+
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
606
|
+
devices.push({
|
|
607
|
+
user,
|
|
608
|
+
device: 0,
|
|
609
|
+
jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
|
|
610
|
+
});
|
|
611
|
+
if (user !== ownUser) {
|
|
612
|
+
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
613
|
+
const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
|
|
614
|
+
devices.push({
|
|
615
|
+
user: ownUserForAddressing,
|
|
616
|
+
device: 0,
|
|
617
|
+
jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
621
|
+
// Clear placeholders and enumerate actual devices
|
|
622
|
+
devices.length = 0;
|
|
623
|
+
// Use conversation-appropriate sender identity
|
|
624
|
+
const senderIdentity = isLid && meLid
|
|
625
|
+
? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
|
|
626
|
+
: jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
|
|
627
|
+
// Enumerate devices for sender and target with consistent addressing
|
|
628
|
+
const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
|
|
629
|
+
devices.push(...sessionDevices);
|
|
630
|
+
logger.debug({
|
|
631
|
+
deviceCount: devices.length,
|
|
632
|
+
devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
|
|
633
|
+
}, 'Device enumeration complete with unified addressing');
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const allRecipients = [];
|
|
637
|
+
const meRecipients = [];
|
|
638
|
+
const otherRecipients = [];
|
|
639
|
+
const { user: mePnUser } = jidDecode(meId);
|
|
640
|
+
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
|
|
641
|
+
for (const { user, jid } of devices) {
|
|
642
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
643
|
+
if (isExactSenderDevice) {
|
|
644
|
+
logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
// Check if this is our device (could match either PN or LID user)
|
|
648
|
+
const isMe = user === mePnUser || user === meLidUser;
|
|
649
|
+
if (isMe) {
|
|
650
|
+
meRecipients.push(jid);
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
otherRecipients.push(jid);
|
|
654
|
+
}
|
|
655
|
+
allRecipients.push(jid);
|
|
656
|
+
}
|
|
657
|
+
await assertSessions(allRecipients);
|
|
658
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
659
|
+
// For own devices: use DSM if available (1:1 chats only)
|
|
660
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
661
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
|
|
662
|
+
]);
|
|
663
|
+
participants.push(...meNodes);
|
|
664
|
+
participants.push(...otherNodes);
|
|
665
|
+
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
666
|
+
extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
|
|
667
|
+
}
|
|
668
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
669
|
+
}
|
|
670
|
+
if (isRetryResend) {
|
|
671
|
+
const isParticipantLid = isLidUser(participant.jid);
|
|
672
|
+
const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
|
|
673
|
+
let messageToSend = message;
|
|
674
|
+
if (isGroupOrStatus) {
|
|
675
|
+
let groupSenderIdentity;
|
|
676
|
+
if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
|
|
677
|
+
groupSenderIdentity = meLid;
|
|
678
|
+
}
|
|
679
|
+
else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
|
|
680
|
+
groupSenderIdentity = meId;
|
|
681
|
+
}
|
|
682
|
+
if (groupSenderIdentity) {
|
|
683
|
+
try {
|
|
684
|
+
const skdm = await signalRepository.getSenderKeyDistributionMessage({
|
|
685
|
+
group: destinationJid,
|
|
686
|
+
meId: groupSenderIdentity
|
|
687
|
+
});
|
|
688
|
+
messageToSend = {
|
|
689
|
+
...message,
|
|
690
|
+
senderKeyDistributionMessage: {
|
|
691
|
+
groupId: destinationJid,
|
|
692
|
+
axolotlSenderKeyDistributionMessage: skdm
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
catch (err) {
|
|
697
|
+
logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const encodedMessageToSend = isMe
|
|
702
|
+
? encodeWAMessage({
|
|
703
|
+
deviceSentMessage: {
|
|
704
|
+
destinationJid,
|
|
705
|
+
message: messageToSend
|
|
706
|
+
}
|
|
707
|
+
})
|
|
708
|
+
: encodeWAMessage(messageToSend);
|
|
709
|
+
const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
|
|
710
|
+
data: encodedMessageToSend,
|
|
711
|
+
jid: participant.jid
|
|
712
|
+
});
|
|
713
|
+
binaryNodeContent.push({
|
|
714
|
+
tag: 'enc',
|
|
715
|
+
attrs: {
|
|
716
|
+
v: '2',
|
|
717
|
+
type,
|
|
718
|
+
count: participant.count.toString()
|
|
719
|
+
},
|
|
720
|
+
content: encryptedContent
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (participants.length) {
|
|
724
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
725
|
+
const peerNode = participants[0]?.content?.[0];
|
|
726
|
+
if (peerNode) {
|
|
727
|
+
binaryNodeContent.push(peerNode); // push only enc
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
binaryNodeContent.push({
|
|
732
|
+
tag: 'participants',
|
|
733
|
+
attrs: {},
|
|
734
|
+
content: participants
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
const stanza = {
|
|
739
|
+
tag: 'message',
|
|
740
|
+
attrs: {
|
|
741
|
+
id: msgId,
|
|
742
|
+
to: destinationJid,
|
|
743
|
+
type: getMessageType(message),
|
|
744
|
+
...(additionalAttributes || {})
|
|
745
|
+
},
|
|
746
|
+
content: binaryNodeContent
|
|
747
|
+
};
|
|
748
|
+
// if the participant to send to is explicitly specified (generally retry recp)
|
|
749
|
+
// ensure the message is only sent to that person
|
|
750
|
+
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
751
|
+
if (participant) {
|
|
752
|
+
if (isJidGroup(destinationJid)) {
|
|
753
|
+
stanza.attrs.to = destinationJid;
|
|
754
|
+
stanza.attrs.participant = participant.jid;
|
|
755
|
+
}
|
|
756
|
+
else if (areJidsSameUser(participant.jid, meId)) {
|
|
757
|
+
stanza.attrs.to = participant.jid;
|
|
758
|
+
stanza.attrs.recipient = destinationJid;
|
|
759
|
+
}
|
|
760
|
+
else {
|
|
761
|
+
stanza.attrs.to = participant.jid;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
else {
|
|
765
|
+
stanza.attrs.to = destinationJid;
|
|
766
|
+
}
|
|
767
|
+
if (shouldIncludeDeviceIdentity) {
|
|
768
|
+
;
|
|
769
|
+
stanza.content.push({
|
|
770
|
+
tag: 'device-identity',
|
|
771
|
+
attrs: {},
|
|
772
|
+
content: encodeSignedDeviceIdentity(authState.creds.account, true)
|
|
773
|
+
});
|
|
774
|
+
logger.debug({ jid }, 'adding device identity');
|
|
775
|
+
}
|
|
776
|
+
if (!isNewsletter &&
|
|
777
|
+
!isRetryResend &&
|
|
778
|
+
reportingMessage?.messageContextInfo?.messageSecret &&
|
|
779
|
+
shouldIncludeReportingToken(reportingMessage)) {
|
|
780
|
+
try {
|
|
781
|
+
const encoded = encodeWAMessage(reportingMessage);
|
|
782
|
+
const reportingKey = {
|
|
783
|
+
id: msgId,
|
|
784
|
+
fromMe: true,
|
|
785
|
+
remoteJid: destinationJid,
|
|
786
|
+
participant: participant?.jid
|
|
787
|
+
};
|
|
788
|
+
const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
|
|
789
|
+
if (reportingNode) {
|
|
790
|
+
;
|
|
791
|
+
stanza.content.push(reportingNode);
|
|
792
|
+
logger.trace({ jid }, 'added reporting token to message');
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
catch (error) {
|
|
796
|
+
logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
// WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
|
|
800
|
+
const isPeerMessage = additionalAttributes?.['category'] === 'peer';
|
|
801
|
+
const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
|
|
802
|
+
// Resolve destination to LID for tctoken storage — matches Signal session key pattern
|
|
803
|
+
const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
|
|
804
|
+
const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
|
|
805
|
+
const existingTokenEntry = contactTcTokenData[tcTokenJid];
|
|
806
|
+
let tcTokenBuffer = existingTokenEntry?.token;
|
|
807
|
+
// Treat expired tokens the same as missing — clear from cache
|
|
808
|
+
if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
|
|
809
|
+
logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
|
|
810
|
+
tcTokenBuffer = undefined;
|
|
811
|
+
// Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
|
|
812
|
+
const cleared = existingTokenEntry?.senderTimestamp !== undefined
|
|
813
|
+
? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
|
|
814
|
+
: null;
|
|
815
|
+
try {
|
|
816
|
+
await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
|
|
817
|
+
}
|
|
818
|
+
catch (err) {
|
|
819
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
|
|
823
|
+
;
|
|
824
|
+
stanza.content.push({
|
|
825
|
+
tag: 'tctoken',
|
|
826
|
+
attrs: {},
|
|
827
|
+
content: tcTokenBuffer
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
if (additionalNodes && additionalNodes.length > 0) {
|
|
831
|
+
;
|
|
832
|
+
stanza.content.push(...additionalNodes);
|
|
833
|
+
}
|
|
834
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`);
|
|
835
|
+
await sendNode(stanza);
|
|
836
|
+
// Fire-and-forget: issue our token to the contact AFTER message send.
|
|
837
|
+
// WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
|
|
838
|
+
const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
|
|
839
|
+
const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
|
|
840
|
+
if (is1on1Send &&
|
|
841
|
+
!isProtocolMsg &&
|
|
842
|
+
!isBotOrPSA &&
|
|
843
|
+
shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
|
|
844
|
+
!inFlightTcTokenIssuance.has(tcTokenJid)) {
|
|
845
|
+
inFlightTcTokenIssuance.add(tcTokenJid);
|
|
846
|
+
const issueTimestamp = unixTimestampSeconds();
|
|
847
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
848
|
+
resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
|
|
849
|
+
.then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
|
|
850
|
+
.then(async (result) => {
|
|
851
|
+
await storeTcTokensFromIqResult({
|
|
852
|
+
result,
|
|
853
|
+
fallbackJid: tcTokenJid,
|
|
854
|
+
keys: authState.keys,
|
|
855
|
+
getLIDForPN
|
|
856
|
+
});
|
|
857
|
+
const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
|
|
858
|
+
const currentEntry = currentData[tcTokenJid];
|
|
859
|
+
const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
|
|
860
|
+
await authState.keys.set({
|
|
861
|
+
tctoken: {
|
|
862
|
+
[tcTokenJid]: {
|
|
863
|
+
token: Buffer.alloc(0),
|
|
864
|
+
...currentEntry,
|
|
865
|
+
senderTimestamp: issueTimestamp
|
|
866
|
+
},
|
|
867
|
+
...indexWrite
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
})
|
|
871
|
+
.catch(err => {
|
|
872
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
|
|
873
|
+
})
|
|
874
|
+
.finally(() => {
|
|
875
|
+
inFlightTcTokenIssuance.delete(tcTokenJid);
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
// Add message to retry cache if enabled
|
|
879
|
+
if (messageRetryManager && !participant) {
|
|
880
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
881
|
+
}
|
|
882
|
+
}, meId);
|
|
883
|
+
return msgId;
|
|
884
|
+
};
|
|
885
|
+
const getMessageType = (message) => {
|
|
886
|
+
const normalizedMessage = normalizeMessageContent(message);
|
|
887
|
+
if (!normalizedMessage)
|
|
888
|
+
return 'text';
|
|
889
|
+
if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
|
|
890
|
+
return 'reaction';
|
|
709
891
|
}
|
|
710
|
-
if (
|
|
711
|
-
|
|
892
|
+
if (normalizedMessage.pollCreationMessage ||
|
|
893
|
+
normalizedMessage.pollCreationMessageV2 ||
|
|
894
|
+
normalizedMessage.pollCreationMessageV3 ||
|
|
895
|
+
normalizedMessage.pollUpdateMessage) {
|
|
896
|
+
return 'poll';
|
|
712
897
|
}
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
!!useUserDevicesCache,
|
|
716
|
-
false,
|
|
717
|
-
);
|
|
718
|
-
devices.push(...additionalDevices);
|
|
719
|
-
if (isGroup) {
|
|
720
|
-
additionalAttributes = {
|
|
721
|
-
...additionalAttributes,
|
|
722
|
-
addressing_mode: groupData?.addressingMode || "lid",
|
|
723
|
-
};
|
|
898
|
+
if (normalizedMessage.eventMessage) {
|
|
899
|
+
return 'event';
|
|
724
900
|
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
throw new Boom("Per-jid patching is not supported in groups");
|
|
901
|
+
if (getMediaType(normalizedMessage) !== '') {
|
|
902
|
+
return 'media';
|
|
728
903
|
}
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
"lid";
|
|
735
|
-
const groupSenderIdentity =
|
|
736
|
-
groupAddressingMode === "lid" && meLid ? meLid : meId;
|
|
737
|
-
const { ciphertext, senderKeyDistributionMessage } =
|
|
738
|
-
await signalRepository.encryptGroupMessage({
|
|
739
|
-
group: destinationJid,
|
|
740
|
-
data: bytes,
|
|
741
|
-
meId: groupSenderIdentity,
|
|
742
|
-
});
|
|
743
|
-
const senderKeyRecipients = [];
|
|
744
|
-
for (const device of devices) {
|
|
745
|
-
const deviceJid = device.jid;
|
|
746
|
-
const hasKey = !!senderKeyMap[deviceJid];
|
|
747
|
-
if (
|
|
748
|
-
(!hasKey || !!participant) &&
|
|
749
|
-
!isHostedLidUser(deviceJid) &&
|
|
750
|
-
!isHostedPnUser(deviceJid) &&
|
|
751
|
-
device.device !== 99
|
|
752
|
-
) {
|
|
753
|
-
//todo: revamp all this logic
|
|
754
|
-
// the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
|
|
755
|
-
senderKeyRecipients.push(deviceJid);
|
|
756
|
-
senderKeyMap[deviceJid] = true;
|
|
757
|
-
}
|
|
904
|
+
return 'text';
|
|
905
|
+
};
|
|
906
|
+
const getMediaType = (message) => {
|
|
907
|
+
if (message.imageMessage) {
|
|
908
|
+
return 'image';
|
|
758
909
|
}
|
|
759
|
-
if (
|
|
760
|
-
|
|
761
|
-
{ senderKeyJids: senderKeyRecipients },
|
|
762
|
-
"sending new sender key",
|
|
763
|
-
);
|
|
764
|
-
const senderKeyMsg = {
|
|
765
|
-
senderKeyDistributionMessage: {
|
|
766
|
-
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
767
|
-
groupId: destinationJid,
|
|
768
|
-
},
|
|
769
|
-
};
|
|
770
|
-
const senderKeySessionTargets = senderKeyRecipients;
|
|
771
|
-
await assertSessions(senderKeySessionTargets);
|
|
772
|
-
const result = await createParticipantNodes(
|
|
773
|
-
senderKeyRecipients,
|
|
774
|
-
senderKeyMsg,
|
|
775
|
-
extraAttrs,
|
|
776
|
-
);
|
|
777
|
-
shouldIncludeDeviceIdentity =
|
|
778
|
-
shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
779
|
-
participants.push(...result.nodes);
|
|
910
|
+
else if (message.videoMessage) {
|
|
911
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video';
|
|
780
912
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
attrs: { v: "2", type: "skmsg", ...extraAttrs },
|
|
784
|
-
content: ciphertext,
|
|
785
|
-
});
|
|
786
|
-
await authState.keys.set({
|
|
787
|
-
"sender-key-memory": { [jid]: senderKeyMap },
|
|
788
|
-
});
|
|
789
|
-
} else {
|
|
790
|
-
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
791
|
-
// TODO: investigate if this is true
|
|
792
|
-
let ownId = meId;
|
|
793
|
-
if (isLid && meLid) {
|
|
794
|
-
ownId = meLid;
|
|
795
|
-
logger.debug(
|
|
796
|
-
{ to: jid, ownId },
|
|
797
|
-
"Using LID identity for @lid conversation",
|
|
798
|
-
);
|
|
799
|
-
} else {
|
|
800
|
-
logger.debug(
|
|
801
|
-
{ to: jid, ownId },
|
|
802
|
-
"Using PN identity for @s.whatsapp.net conversation",
|
|
803
|
-
);
|
|
913
|
+
else if (message.audioMessage) {
|
|
914
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio';
|
|
804
915
|
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const patchedForReporting = await patchMessageBeforeSending(message, [
|
|
808
|
-
jid,
|
|
809
|
-
]);
|
|
810
|
-
reportingMessage = Array.isArray(patchedForReporting)
|
|
811
|
-
? patchedForReporting.find((item) => item.recipientJid === jid) ||
|
|
812
|
-
patchedForReporting[0]
|
|
813
|
-
: patchedForReporting;
|
|
916
|
+
else if (message.contactMessage) {
|
|
917
|
+
return 'vcard';
|
|
814
918
|
}
|
|
815
|
-
if (
|
|
816
|
-
|
|
817
|
-
devices.push({
|
|
818
|
-
user,
|
|
819
|
-
device: 0,
|
|
820
|
-
jid: jidEncode(user, targetUserServer, 0), // rajeh, todo: this entire logic is convoluted and weird.
|
|
821
|
-
});
|
|
822
|
-
if (user !== ownUser) {
|
|
823
|
-
const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
|
|
824
|
-
const ownUserForAddressing =
|
|
825
|
-
isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
|
|
826
|
-
devices.push({
|
|
827
|
-
user: ownUserForAddressing,
|
|
828
|
-
device: 0,
|
|
829
|
-
jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
|
|
830
|
-
});
|
|
831
|
-
}
|
|
832
|
-
if (additionalAttributes?.["category"] !== "peer") {
|
|
833
|
-
// Clear placeholders and enumerate actual devices
|
|
834
|
-
devices.length = 0;
|
|
835
|
-
// Use conversation-appropriate sender identity
|
|
836
|
-
const senderIdentity =
|
|
837
|
-
isLid && meLid
|
|
838
|
-
? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
|
|
839
|
-
: jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
|
|
840
|
-
// Enumerate devices for sender and target with consistent addressing
|
|
841
|
-
const sessionDevices = await getUSyncDevices(
|
|
842
|
-
[senderIdentity, jid],
|
|
843
|
-
true,
|
|
844
|
-
false,
|
|
845
|
-
);
|
|
846
|
-
devices.push(...sessionDevices);
|
|
847
|
-
logger.debug(
|
|
848
|
-
{
|
|
849
|
-
deviceCount: devices.length,
|
|
850
|
-
devices: devices.map(
|
|
851
|
-
(d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`,
|
|
852
|
-
),
|
|
853
|
-
},
|
|
854
|
-
"Device enumeration complete with unified addressing",
|
|
855
|
-
);
|
|
856
|
-
}
|
|
919
|
+
else if (message.documentMessage) {
|
|
920
|
+
return 'document';
|
|
857
921
|
}
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
const otherRecipients = [];
|
|
861
|
-
const { user: mePnUser } = jidDecode(meId);
|
|
862
|
-
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
|
|
863
|
-
for (const { user, jid } of devices) {
|
|
864
|
-
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
865
|
-
if (isExactSenderDevice) {
|
|
866
|
-
logger.debug(
|
|
867
|
-
{ jid, meId, meLid },
|
|
868
|
-
"Skipping exact sender device (whatsmeow pattern)",
|
|
869
|
-
);
|
|
870
|
-
continue;
|
|
871
|
-
}
|
|
872
|
-
// Check if this is our device (could match either PN or LID user)
|
|
873
|
-
const isMe = user === mePnUser || user === meLidUser;
|
|
874
|
-
if (isMe) {
|
|
875
|
-
meRecipients.push(jid);
|
|
876
|
-
} else {
|
|
877
|
-
otherRecipients.push(jid);
|
|
878
|
-
}
|
|
879
|
-
allRecipients.push(jid);
|
|
922
|
+
else if (message.contactsArrayMessage) {
|
|
923
|
+
return 'contact_array';
|
|
880
924
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
|
|
884
|
-
{ nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
|
|
885
|
-
] = await Promise.all([
|
|
886
|
-
// For own devices: use DSM if available (1:1 chats only)
|
|
887
|
-
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
888
|
-
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
|
|
889
|
-
]);
|
|
890
|
-
participants.push(...meNodes);
|
|
891
|
-
participants.push(...otherNodes);
|
|
892
|
-
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
893
|
-
extraAttrs["phash"] = generateParticipantHashV2([
|
|
894
|
-
...meRecipients,
|
|
895
|
-
...otherRecipients,
|
|
896
|
-
]);
|
|
925
|
+
else if (message.liveLocationMessage) {
|
|
926
|
+
return 'livelocation';
|
|
897
927
|
}
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
if (isRetryResend) {
|
|
901
|
-
const isParticipantLid = isLidUser(participant.jid);
|
|
902
|
-
const isMe = areJidsSameUser(
|
|
903
|
-
participant.jid,
|
|
904
|
-
isParticipantLid ? meLid : meId,
|
|
905
|
-
);
|
|
906
|
-
const encodedMessageToSend = isMe
|
|
907
|
-
? encodeWAMessage({
|
|
908
|
-
deviceSentMessage: {
|
|
909
|
-
destinationJid,
|
|
910
|
-
message,
|
|
911
|
-
},
|
|
912
|
-
})
|
|
913
|
-
: encodeWAMessage(message);
|
|
914
|
-
const { type, ciphertext: encryptedContent } =
|
|
915
|
-
await signalRepository.encryptMessage({
|
|
916
|
-
data: encodedMessageToSend,
|
|
917
|
-
jid: participant.jid,
|
|
918
|
-
});
|
|
919
|
-
binaryNodeContent.push({
|
|
920
|
-
tag: "enc",
|
|
921
|
-
attrs: {
|
|
922
|
-
v: "2",
|
|
923
|
-
type,
|
|
924
|
-
count: participant.count.toString(),
|
|
925
|
-
},
|
|
926
|
-
content: encryptedContent,
|
|
927
|
-
});
|
|
928
|
-
}
|
|
929
|
-
if (participants.length) {
|
|
930
|
-
if (additionalAttributes?.["category"] === "peer") {
|
|
931
|
-
const peerNode = participants[0]?.content?.[0];
|
|
932
|
-
if (peerNode) {
|
|
933
|
-
binaryNodeContent.push(peerNode); // push only enc
|
|
934
|
-
}
|
|
935
|
-
} else {
|
|
936
|
-
binaryNodeContent.push({
|
|
937
|
-
tag: "participants",
|
|
938
|
-
attrs: {},
|
|
939
|
-
content: participants,
|
|
940
|
-
});
|
|
928
|
+
else if (message.stickerMessage) {
|
|
929
|
+
return 'sticker';
|
|
941
930
|
}
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
tag: "message",
|
|
945
|
-
attrs: {
|
|
946
|
-
id: msgId,
|
|
947
|
-
to: destinationJid,
|
|
948
|
-
type: getMessageType(message),
|
|
949
|
-
...(additionalAttributes || {}),
|
|
950
|
-
},
|
|
951
|
-
content: binaryNodeContent,
|
|
952
|
-
};
|
|
953
|
-
// if the participant to send to is explicitly specified (generally retry recp)
|
|
954
|
-
// ensure the message is only sent to that person
|
|
955
|
-
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
956
|
-
if (participant) {
|
|
957
|
-
if (isJidGroup(destinationJid)) {
|
|
958
|
-
stanza.attrs.to = destinationJid;
|
|
959
|
-
stanza.attrs.participant = participant.jid;
|
|
960
|
-
} else if (areJidsSameUser(participant.jid, meId)) {
|
|
961
|
-
stanza.attrs.to = participant.jid;
|
|
962
|
-
stanza.attrs.recipient = destinationJid;
|
|
963
|
-
} else {
|
|
964
|
-
stanza.attrs.to = participant.jid;
|
|
931
|
+
else if (message.listMessage) {
|
|
932
|
+
return 'list';
|
|
965
933
|
}
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
}
|
|
969
|
-
if (shouldIncludeDeviceIdentity) {
|
|
970
|
-
stanza.content.push({
|
|
971
|
-
tag: "device-identity",
|
|
972
|
-
attrs: {},
|
|
973
|
-
content: encodeSignedDeviceIdentity(authState.creds.account, true),
|
|
974
|
-
});
|
|
975
|
-
logger.debug({ jid }, "adding device identity");
|
|
976
|
-
}
|
|
977
|
-
if (
|
|
978
|
-
!isNewsletter &&
|
|
979
|
-
!isRetryResend &&
|
|
980
|
-
reportingMessage?.messageContextInfo?.messageSecret &&
|
|
981
|
-
shouldIncludeReportingToken(reportingMessage)
|
|
982
|
-
) {
|
|
983
|
-
try {
|
|
984
|
-
const encoded = encodeWAMessage(reportingMessage);
|
|
985
|
-
const reportingKey = {
|
|
986
|
-
id: msgId,
|
|
987
|
-
fromMe: true,
|
|
988
|
-
remoteJid: destinationJid,
|
|
989
|
-
participant: participant?.jid,
|
|
990
|
-
};
|
|
991
|
-
const reportingNode = await getMessageReportingToken(
|
|
992
|
-
encoded,
|
|
993
|
-
reportingMessage,
|
|
994
|
-
reportingKey,
|
|
995
|
-
);
|
|
996
|
-
if (reportingNode) {
|
|
997
|
-
stanza.content.push(reportingNode);
|
|
998
|
-
logger.trace({ jid }, "added reporting token to message");
|
|
999
|
-
}
|
|
1000
|
-
} catch (error) {
|
|
1001
|
-
logger.warn(
|
|
1002
|
-
{ jid, trace: error?.stack },
|
|
1003
|
-
"failed to attach reporting token",
|
|
1004
|
-
);
|
|
934
|
+
else if (message.listResponseMessage) {
|
|
935
|
+
return 'list_response';
|
|
1005
936
|
}
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
!isGroup && !isRetryResend && !isStatus
|
|
1009
|
-
? await authState.keys.get("tctoken", [destinationJid])
|
|
1010
|
-
: {};
|
|
1011
|
-
const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
|
|
1012
|
-
if (tcTokenBuffer) {
|
|
1013
|
-
stanza.content.push({
|
|
1014
|
-
tag: "tctoken",
|
|
1015
|
-
attrs: {},
|
|
1016
|
-
content: tcTokenBuffer,
|
|
1017
|
-
});
|
|
1018
|
-
}
|
|
1019
|
-
if (additionalNodes && additionalNodes.length > 0) {
|
|
1020
|
-
stanza.content.push(...additionalNodes);
|
|
1021
|
-
}
|
|
1022
|
-
const buttonType = getButtonType(message);
|
|
1023
|
-
if (buttonType && !isNewsletter && !isStatus) {
|
|
1024
|
-
const bizNodes = getAdditionalNode(buttonType);
|
|
1025
|
-
stanza.content.push(...bizNodes);
|
|
1026
|
-
}
|
|
1027
|
-
logger.debug(
|
|
1028
|
-
{ msgId },
|
|
1029
|
-
`sending message to ${participants.length} devices`,
|
|
1030
|
-
);
|
|
1031
|
-
await sendNode(stanza);
|
|
1032
|
-
// Add message to retry cache if enabled
|
|
1033
|
-
if (messageRetryManager && !participant) {
|
|
1034
|
-
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
1035
|
-
}
|
|
1036
|
-
}, meId);
|
|
1037
|
-
return msgId;
|
|
1038
|
-
};
|
|
1039
|
-
const getMessageType = (message) => {
|
|
1040
|
-
const normalizedMessage = normalizeMessageContent(message);
|
|
1041
|
-
if (!normalizedMessage) return "text";
|
|
1042
|
-
if (
|
|
1043
|
-
normalizedMessage.reactionMessage ||
|
|
1044
|
-
normalizedMessage.encReactionMessage
|
|
1045
|
-
) {
|
|
1046
|
-
return "reaction";
|
|
1047
|
-
}
|
|
1048
|
-
if (
|
|
1049
|
-
normalizedMessage.pollCreationMessage ||
|
|
1050
|
-
normalizedMessage.pollCreationMessageV2 ||
|
|
1051
|
-
normalizedMessage.pollCreationMessageV3 ||
|
|
1052
|
-
normalizedMessage.pollUpdateMessage
|
|
1053
|
-
) {
|
|
1054
|
-
return "poll";
|
|
1055
|
-
}
|
|
1056
|
-
if (normalizedMessage.eventMessage) {
|
|
1057
|
-
return "event";
|
|
1058
|
-
}
|
|
1059
|
-
if (getMediaType(normalizedMessage) !== "") {
|
|
1060
|
-
return "media";
|
|
1061
|
-
}
|
|
1062
|
-
return "text";
|
|
1063
|
-
};
|
|
1064
|
-
const getMediaType = (message) => {
|
|
1065
|
-
if (message.imageMessage) {
|
|
1066
|
-
return "image";
|
|
1067
|
-
} else if (message.videoMessage) {
|
|
1068
|
-
return message.videoMessage.gifPlayback ? "gif" : "video";
|
|
1069
|
-
} else if (message.audioMessage) {
|
|
1070
|
-
return message.audioMessage.ptt ? "ptt" : "audio";
|
|
1071
|
-
} else if (message.contactMessage) {
|
|
1072
|
-
return "vcard";
|
|
1073
|
-
} else if (message.documentMessage) {
|
|
1074
|
-
return "document";
|
|
1075
|
-
} else if (message.contactsArrayMessage) {
|
|
1076
|
-
return "contact_array";
|
|
1077
|
-
} else if (message.liveLocationMessage) {
|
|
1078
|
-
return "livelocation";
|
|
1079
|
-
} else if (message.stickerMessage) {
|
|
1080
|
-
return message.stickerMessage.isLottie
|
|
1081
|
-
? "1p_sticker"
|
|
1082
|
-
: message.stickerMessage.isAvatar
|
|
1083
|
-
? "avatar_sticker"
|
|
1084
|
-
: "sticker";
|
|
1085
|
-
} else if (message.listMessage) {
|
|
1086
|
-
return "list";
|
|
1087
|
-
} else if (message.listResponseMessage) {
|
|
1088
|
-
return "list_response";
|
|
1089
|
-
} else if (message.buttonsResponseMessage) {
|
|
1090
|
-
return "buttons_response";
|
|
1091
|
-
} else if (message.orderMessage) {
|
|
1092
|
-
return "order";
|
|
1093
|
-
} else if (message.productMessage) {
|
|
1094
|
-
return "product";
|
|
1095
|
-
} else if (message.interactiveResponseMessage) {
|
|
1096
|
-
return "native_flow_response";
|
|
1097
|
-
} else if (message.groupInviteMessage) {
|
|
1098
|
-
return "url";
|
|
1099
|
-
}
|
|
1100
|
-
return "";
|
|
1101
|
-
};
|
|
1102
|
-
const getPrivacyTokens = async (jids) => {
|
|
1103
|
-
const t = unixTimestampSeconds().toString();
|
|
1104
|
-
const result = await query({
|
|
1105
|
-
tag: "iq",
|
|
1106
|
-
attrs: {
|
|
1107
|
-
to: S_WHATSAPP_NET,
|
|
1108
|
-
type: "set",
|
|
1109
|
-
xmlns: "privacy",
|
|
1110
|
-
},
|
|
1111
|
-
content: [
|
|
1112
|
-
{
|
|
1113
|
-
tag: "tokens",
|
|
1114
|
-
attrs: {},
|
|
1115
|
-
content: jids.map((jid) => ({
|
|
1116
|
-
tag: "token",
|
|
1117
|
-
attrs: {
|
|
1118
|
-
jid: jidNormalizedUser(jid),
|
|
1119
|
-
t,
|
|
1120
|
-
type: "trusted_contact",
|
|
1121
|
-
},
|
|
1122
|
-
})),
|
|
1123
|
-
},
|
|
1124
|
-
],
|
|
1125
|
-
});
|
|
1126
|
-
return result;
|
|
1127
|
-
};
|
|
1128
|
-
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
|
|
1129
|
-
const kyyBail = new Dugong(waUploadToServer, relayMessage, config, sock);
|
|
1130
|
-
const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
|
|
1131
|
-
return {
|
|
1132
|
-
...sock,
|
|
1133
|
-
getPrivacyTokens,
|
|
1134
|
-
assertSessions,
|
|
1135
|
-
relayMessage,
|
|
1136
|
-
sendReceipt,
|
|
1137
|
-
sendReceipts,
|
|
1138
|
-
kyyBail,
|
|
1139
|
-
readMessages,
|
|
1140
|
-
refreshMediaConn,
|
|
1141
|
-
waUploadToServer,
|
|
1142
|
-
fetchPrivacySettings,
|
|
1143
|
-
sendPeerDataOperationMessage,
|
|
1144
|
-
createParticipantNodes,
|
|
1145
|
-
getUSyncDevices,
|
|
1146
|
-
messageRetryManager,
|
|
1147
|
-
updateMemberLabel,
|
|
1148
|
-
updateMediaMessage: async (message) => {
|
|
1149
|
-
const content = assertMediaContent(message.message);
|
|
1150
|
-
const mediaKey = content.mediaKey;
|
|
1151
|
-
const meId = authState.creds.me.id;
|
|
1152
|
-
const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
|
|
1153
|
-
let error = undefined;
|
|
1154
|
-
await Promise.all([
|
|
1155
|
-
sendNode(node),
|
|
1156
|
-
waitForMsgMediaUpdate(async (update) => {
|
|
1157
|
-
const result = update.find((c) => c.key.id === message.key.id);
|
|
1158
|
-
if (result) {
|
|
1159
|
-
if (result.error) {
|
|
1160
|
-
error = result.error;
|
|
1161
|
-
} else {
|
|
1162
|
-
try {
|
|
1163
|
-
const media = decryptMediaRetryData(
|
|
1164
|
-
result.media,
|
|
1165
|
-
mediaKey,
|
|
1166
|
-
result.key.id,
|
|
1167
|
-
);
|
|
1168
|
-
if (
|
|
1169
|
-
media.result !==
|
|
1170
|
-
proto.MediaRetryNotification.ResultType.SUCCESS
|
|
1171
|
-
) {
|
|
1172
|
-
const resultStr =
|
|
1173
|
-
proto.MediaRetryNotification.ResultType[media.result];
|
|
1174
|
-
throw new Boom(
|
|
1175
|
-
`Media re-upload failed by device (${resultStr})`,
|
|
1176
|
-
{
|
|
1177
|
-
data: media,
|
|
1178
|
-
statusCode:
|
|
1179
|
-
getStatusCodeForMediaRetry(media.result) || 404,
|
|
1180
|
-
},
|
|
1181
|
-
);
|
|
1182
|
-
}
|
|
1183
|
-
content.directPath = media.directPath;
|
|
1184
|
-
content.url = getUrlFromDirectPath(content.directPath);
|
|
1185
|
-
logger.debug(
|
|
1186
|
-
{ directPath: media.directPath, key: result.key },
|
|
1187
|
-
"media update successful",
|
|
1188
|
-
);
|
|
1189
|
-
} catch (err) {
|
|
1190
|
-
error = err;
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
return true;
|
|
1194
|
-
}
|
|
1195
|
-
}),
|
|
1196
|
-
]);
|
|
1197
|
-
if (error) {
|
|
1198
|
-
throw error;
|
|
1199
|
-
}
|
|
1200
|
-
ev.emit("messages.update", [
|
|
1201
|
-
{ key: message.key, update: { message: message.message } },
|
|
1202
|
-
]);
|
|
1203
|
-
return message;
|
|
1204
|
-
},
|
|
1205
|
-
sendStatusMention: async (content, jids = []) => {
|
|
1206
|
-
return await kyyBail.sendStatusWhatsApp(content, jids);
|
|
1207
|
-
},
|
|
1208
|
-
swgc: async (jid, content, options = {}) => {
|
|
1209
|
-
if (!isJidGroup(jid)) {
|
|
1210
|
-
throw new Boom("JID must be a group", { statusCode: 400 });
|
|
1211
|
-
}
|
|
1212
|
-
const storyContent = { groupStatusMessage: content };
|
|
1213
|
-
return await kyyBail.handleGroupStory(storyContent, jid, null);
|
|
1214
|
-
},
|
|
1215
|
-
sendPreview: async (jid, preview, options = {}) => {
|
|
1216
|
-
const extContent = {
|
|
1217
|
-
text: preview.caption || preview.text || "",
|
|
1218
|
-
matchedText: preview.matchedText || preview.url || "",
|
|
1219
|
-
previewType: preview.previewType ?? 0,
|
|
1220
|
-
};
|
|
1221
|
-
if (preview.title) extContent.title = preview.title;
|
|
1222
|
-
if (preview.description) extContent.description = preview.description;
|
|
1223
|
-
if (preview.inviteLinkGroupTypeV2)
|
|
1224
|
-
extContent.inviteLinkGroupTypeV2 = preview.inviteLinkGroupTypeV2;
|
|
1225
|
-
if (preview.image) {
|
|
1226
|
-
let imgBuf = preview.image;
|
|
1227
|
-
if (typeof imgBuf === "string" && imgBuf.startsWith("http")) {
|
|
1228
|
-
try {
|
|
1229
|
-
const resp = await fetch(imgBuf);
|
|
1230
|
-
imgBuf = Buffer.from(await resp.arrayBuffer());
|
|
1231
|
-
} catch {}
|
|
937
|
+
else if (message.buttonsResponseMessage) {
|
|
938
|
+
return 'buttons_response';
|
|
1232
939
|
}
|
|
1233
|
-
if (
|
|
1234
|
-
|
|
1235
|
-
const { imageMessage } = await prepareWAMessageMedia(
|
|
1236
|
-
{ image: imgBuf },
|
|
1237
|
-
{ upload: waUploadToServer, mediaTypeOverride: "thumbnail-link" },
|
|
1238
|
-
);
|
|
1239
|
-
if (imageMessage) {
|
|
1240
|
-
extContent.jpegThumbnail = imageMessage.jpegThumbnail;
|
|
1241
|
-
if (imageMessage.directPath)
|
|
1242
|
-
extContent.thumbnailDirectPath = imageMessage.directPath;
|
|
1243
|
-
if (imageMessage.mediaKey)
|
|
1244
|
-
extContent.mediaKey = imageMessage.mediaKey;
|
|
1245
|
-
if (imageMessage.mediaKeyTimestamp)
|
|
1246
|
-
extContent.mediaKeyTimestamp = imageMessage.mediaKeyTimestamp;
|
|
1247
|
-
if (imageMessage.fileSha256)
|
|
1248
|
-
extContent.thumbnailSha256 = imageMessage.fileSha256;
|
|
1249
|
-
if (imageMessage.fileEncSha256)
|
|
1250
|
-
extContent.thumbnailEncSha256 = imageMessage.fileEncSha256;
|
|
1251
|
-
if (imageMessage.width)
|
|
1252
|
-
extContent.thumbnailWidth = imageMessage.width;
|
|
1253
|
-
if (imageMessage.height)
|
|
1254
|
-
extContent.thumbnailHeight = imageMessage.height;
|
|
1255
|
-
}
|
|
1256
|
-
} catch {
|
|
1257
|
-
extContent.jpegThumbnail = imgBuf;
|
|
1258
|
-
}
|
|
1259
|
-
} else {
|
|
1260
|
-
extContent.jpegThumbnail = imgBuf;
|
|
940
|
+
else if (message.orderMessage) {
|
|
941
|
+
return 'order';
|
|
1261
942
|
}
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
}
|
|
1265
|
-
if (preview.thumbnailHeight)
|
|
1266
|
-
extContent.thumbnailHeight = preview.thumbnailHeight;
|
|
1267
|
-
if (preview.thumbnailWidth)
|
|
1268
|
-
extContent.thumbnailWidth = preview.thumbnailWidth;
|
|
1269
|
-
if (options.quoted) {
|
|
1270
|
-
const participant = options.quoted.key.fromMe
|
|
1271
|
-
? authState.creds.me.id
|
|
1272
|
-
: options.quoted.participant ||
|
|
1273
|
-
options.quoted.key.participant ||
|
|
1274
|
-
options.quoted.key.remoteJid;
|
|
1275
|
-
extContent.contextInfo = {
|
|
1276
|
-
stanzaId: options.quoted.key.id,
|
|
1277
|
-
participant,
|
|
1278
|
-
quotedMessage: options.quoted.message,
|
|
1279
|
-
};
|
|
1280
|
-
}
|
|
1281
|
-
if (options.contextInfo) {
|
|
1282
|
-
extContent.contextInfo = {
|
|
1283
|
-
...extContent.contextInfo,
|
|
1284
|
-
...options.contextInfo,
|
|
1285
|
-
};
|
|
1286
|
-
}
|
|
1287
|
-
const messageId = generateMessageIDV2(sock.user?.id);
|
|
1288
|
-
await relayMessage(
|
|
1289
|
-
jid,
|
|
1290
|
-
{ extendedTextMessage: extContent },
|
|
1291
|
-
{ messageId },
|
|
1292
|
-
);
|
|
1293
|
-
return messageId;
|
|
1294
|
-
},
|
|
1295
|
-
// Aku tau kamu pasti bakalan nyari ini, tapi gak papa deh
|
|
1296
|
-
// kyyBail — kyyinfinite
|
|
1297
|
-
// @Zann
|
|
1298
|
-
sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
|
|
1299
|
-
const { message, messageId } = generateTableContent(
|
|
1300
|
-
title,
|
|
1301
|
-
headers,
|
|
1302
|
-
rows,
|
|
1303
|
-
quoted,
|
|
1304
|
-
options,
|
|
1305
|
-
);
|
|
1306
|
-
await relayMessage(jid, message, { messageId });
|
|
1307
|
-
return { message, messageId };
|
|
1308
|
-
},
|
|
1309
|
-
sendTableV2: async (jid, table, quoted, options = {}) => {
|
|
1310
|
-
const { message, messageId } = generateTableContentV2(
|
|
1311
|
-
table,
|
|
1312
|
-
quoted,
|
|
1313
|
-
options,
|
|
1314
|
-
);
|
|
1315
|
-
await relayMessage(jid, message, { messageId });
|
|
1316
|
-
return { message, messageId };
|
|
1317
|
-
},
|
|
1318
|
-
sendList: async (jid, title, items, quoted, options = {}) => {
|
|
1319
|
-
const { message, messageId } = generateListContent(
|
|
1320
|
-
title,
|
|
1321
|
-
items,
|
|
1322
|
-
quoted,
|
|
1323
|
-
options,
|
|
1324
|
-
);
|
|
1325
|
-
await relayMessage(jid, message, { messageId });
|
|
1326
|
-
return { message, messageId };
|
|
1327
|
-
},
|
|
1328
|
-
sendCodeBlock: async (jid, code, quoted, options = {}) => {
|
|
1329
|
-
const { message, messageId } = generateCodeBlockContent(
|
|
1330
|
-
code,
|
|
1331
|
-
quoted,
|
|
1332
|
-
options,
|
|
1333
|
-
);
|
|
1334
|
-
await relayMessage(jid, message, { messageId });
|
|
1335
|
-
return { message, messageId };
|
|
1336
|
-
},
|
|
1337
|
-
sendCodeBlockV2: async (jid, code, quoted, options = {}) => {
|
|
1338
|
-
const { message, messageId } = generateCodeBlockContentV2(
|
|
1339
|
-
code,
|
|
1340
|
-
quoted,
|
|
1341
|
-
options,
|
|
1342
|
-
);
|
|
1343
|
-
await relayMessage(jid, message, { messageId });
|
|
1344
|
-
return { message, messageId };
|
|
1345
|
-
},
|
|
1346
|
-
sendLink: async (jid, text, links, quoted, options = {}) => {
|
|
1347
|
-
const { message, messageId } = generateLinkContent(
|
|
1348
|
-
text,
|
|
1349
|
-
links,
|
|
1350
|
-
quoted,
|
|
1351
|
-
options,
|
|
1352
|
-
);
|
|
1353
|
-
await relayMessage(jid, message, { messageId });
|
|
1354
|
-
return { message, messageId };
|
|
1355
|
-
},
|
|
1356
|
-
sendLinkV2: async (jid, text, links, quoted, options = {}) => {
|
|
1357
|
-
const { message, messageId } = generateLinkContentV2(
|
|
1358
|
-
text,
|
|
1359
|
-
links,
|
|
1360
|
-
quoted,
|
|
1361
|
-
options,
|
|
1362
|
-
);
|
|
1363
|
-
await relayMessage(jid, message, { messageId });
|
|
1364
|
-
return { message, messageId };
|
|
1365
|
-
},
|
|
1366
|
-
sendLatex: async (jid, quoted, options) => {
|
|
1367
|
-
const { message, messageId } = generateLatexContent(quoted, options);
|
|
1368
|
-
await relayMessage(jid, message, { messageId });
|
|
1369
|
-
return { message, messageId };
|
|
1370
|
-
},
|
|
1371
|
-
sendLatexImage: async (
|
|
1372
|
-
jid,
|
|
1373
|
-
quoted,
|
|
1374
|
-
options,
|
|
1375
|
-
renderLatexToPng,
|
|
1376
|
-
uploadFn,
|
|
1377
|
-
) => {
|
|
1378
|
-
const { message, messageId } = await generateLatexImageContent(
|
|
1379
|
-
quoted,
|
|
1380
|
-
options,
|
|
1381
|
-
uploadFn,
|
|
1382
|
-
renderLatexToPng,
|
|
1383
|
-
);
|
|
1384
|
-
await relayMessage(jid, message, { messageId });
|
|
1385
|
-
return { message, messageId };
|
|
1386
|
-
},
|
|
1387
|
-
sendLatexInlineImage: async (
|
|
1388
|
-
jid,
|
|
1389
|
-
quoted,
|
|
1390
|
-
options,
|
|
1391
|
-
renderLatexToPng,
|
|
1392
|
-
uploadFn,
|
|
1393
|
-
) => {
|
|
1394
|
-
const { message, messageId } = await generateLatexInlineImageContent(
|
|
1395
|
-
quoted,
|
|
1396
|
-
options,
|
|
1397
|
-
uploadFn,
|
|
1398
|
-
renderLatexToPng,
|
|
1399
|
-
);
|
|
1400
|
-
await relayMessage(jid, message, { messageId });
|
|
1401
|
-
return { message, messageId };
|
|
1402
|
-
},
|
|
1403
|
-
captureUnifiedResponse,
|
|
1404
|
-
sendUnifiedResponse: async (jid, quoted, captured) => {
|
|
1405
|
-
const { message, messageId } = generateUnifiedResponseContent(
|
|
1406
|
-
quoted,
|
|
1407
|
-
captured,
|
|
1408
|
-
);
|
|
1409
|
-
await relayMessage(jid, message, { messageId });
|
|
1410
|
-
return { message, messageId };
|
|
1411
|
-
},
|
|
1412
|
-
sendRichMessage: async (jid, submessages, quoted, options = {}) => {
|
|
1413
|
-
const { message, messageId } = generateRichMessageContent(
|
|
1414
|
-
submessages,
|
|
1415
|
-
quoted,
|
|
1416
|
-
);
|
|
1417
|
-
await relayMessage(jid, message, { messageId });
|
|
1418
|
-
return { message, messageId };
|
|
1419
|
-
},
|
|
1420
|
-
sendMessage: async (jid, content, options = {}) => {
|
|
1421
|
-
const userJid = authState.creds.me.id;
|
|
1422
|
-
const { quoted } = options;
|
|
1423
|
-
const messageType = kyyBail.detectType(content);
|
|
1424
|
-
if (
|
|
1425
|
-
typeof content === "object" &&
|
|
1426
|
-
"disappearingMessagesInChat" in content &&
|
|
1427
|
-
typeof content["disappearingMessagesInChat"] !== "undefined" &&
|
|
1428
|
-
isJidGroup(jid)
|
|
1429
|
-
) {
|
|
1430
|
-
const { disappearingMessagesInChat } = content;
|
|
1431
|
-
const value =
|
|
1432
|
-
typeof disappearingMessagesInChat === "boolean"
|
|
1433
|
-
? disappearingMessagesInChat
|
|
1434
|
-
? WA_DEFAULT_EPHEMERAL
|
|
1435
|
-
: 0
|
|
1436
|
-
: disappearingMessagesInChat;
|
|
1437
|
-
await groupToggleEphemeral(jid, value);
|
|
1438
|
-
} else if (messageType) {
|
|
1439
|
-
switch (messageType) {
|
|
1440
|
-
case "PAYMENT": {
|
|
1441
|
-
const paymentContent = await kyyBail.handlePayment(content, quoted);
|
|
1442
|
-
return await relayMessage(jid, paymentContent, {
|
|
1443
|
-
messageId: generateMessageIDV2(userJid),
|
|
1444
|
-
});
|
|
1445
|
-
}
|
|
1446
|
-
case "PRODUCT": {
|
|
1447
|
-
const productContent = await kyyBail.handleProduct(
|
|
1448
|
-
content,
|
|
1449
|
-
jid,
|
|
1450
|
-
quoted,
|
|
1451
|
-
);
|
|
1452
|
-
const productMsg = await generateWAMessageFromContent(
|
|
1453
|
-
jid,
|
|
1454
|
-
productContent,
|
|
1455
|
-
{ quoted, userJid },
|
|
1456
|
-
);
|
|
1457
|
-
return await relayMessage(jid, productMsg.message, {
|
|
1458
|
-
messageId: productMsg.key.id,
|
|
1459
|
-
});
|
|
1460
|
-
}
|
|
1461
|
-
case "CAROUSEL": {
|
|
1462
|
-
const carouselContent = await kyyBail.handleCarousel(
|
|
1463
|
-
content,
|
|
1464
|
-
jid,
|
|
1465
|
-
quoted,
|
|
1466
|
-
);
|
|
1467
|
-
const carouselMsg = await generateWAMessageFromContent(
|
|
1468
|
-
jid,
|
|
1469
|
-
carouselContent,
|
|
1470
|
-
{ quoted, userJid },
|
|
1471
|
-
);
|
|
1472
|
-
return await relayMessage(jid, carouselMsg.message, {
|
|
1473
|
-
messageId: carouselMsg.key.id,
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
1476
|
-
case "INTERACTIVE": {
|
|
1477
|
-
const interactiveContent = await kyyBail.handleInteractive(
|
|
1478
|
-
content,
|
|
1479
|
-
jid,
|
|
1480
|
-
quoted,
|
|
1481
|
-
);
|
|
1482
|
-
const interactiveMsg = await generateWAMessageFromContent(
|
|
1483
|
-
jid,
|
|
1484
|
-
interactiveContent,
|
|
1485
|
-
{ quoted, userJid },
|
|
1486
|
-
);
|
|
1487
|
-
return await relayMessage(jid, interactiveMsg.message, {
|
|
1488
|
-
messageId: interactiveMsg.key.id,
|
|
1489
|
-
});
|
|
1490
|
-
}
|
|
1491
|
-
case "INTERACTIVE_BUTTONS": {
|
|
1492
|
-
const ibContent = await kyyBail.handleInteractiveButtons(
|
|
1493
|
-
content,
|
|
1494
|
-
jid,
|
|
1495
|
-
quoted,
|
|
1496
|
-
);
|
|
1497
|
-
const ibMsg = await generateWAMessageFromContent(jid, ibContent, {
|
|
1498
|
-
quoted,
|
|
1499
|
-
userJid,
|
|
1500
|
-
});
|
|
1501
|
-
return await relayMessage(jid, ibMsg.message, {
|
|
1502
|
-
messageId: ibMsg.key.id,
|
|
1503
|
-
});
|
|
1504
|
-
}
|
|
1505
|
-
case "ALBUM":
|
|
1506
|
-
return await kyyBail.handleAlbum(content, jid, quoted);
|
|
1507
|
-
case "EVENT":
|
|
1508
|
-
return await kyyBail.handleEvent(content, jid, quoted);
|
|
1509
|
-
case "POLL_RESULT":
|
|
1510
|
-
return await kyyBail.handlePollResult(content, jid, quoted);
|
|
1511
|
-
case "GROUP_STORY":
|
|
1512
|
-
return await kyyBail.handleGroupStory(content, jid, quoted, options);
|
|
943
|
+
else if (message.productMessage) {
|
|
944
|
+
return 'product';
|
|
1513
945
|
}
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
getUrlInfo: (text) =>
|
|
1520
|
-
getUrlInfo(text, {
|
|
1521
|
-
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1522
|
-
fetchOpts: {
|
|
1523
|
-
timeout: 3000,
|
|
1524
|
-
...(httpRequestOptions || {}),
|
|
1525
|
-
},
|
|
1526
|
-
logger,
|
|
1527
|
-
uploadImage: generateHighQualityLinkPreview
|
|
1528
|
-
? waUploadToServer
|
|
1529
|
-
: undefined,
|
|
1530
|
-
}),
|
|
1531
|
-
getProfilePicUrl: sock.profilePictureUrl,
|
|
1532
|
-
getCallLink: sock.createCallLink,
|
|
1533
|
-
upload: async (readStream, opts) => {
|
|
1534
|
-
const up = await waUploadToServer(readStream, {
|
|
1535
|
-
...opts,
|
|
1536
|
-
newsletter: isJidNewsletter(jid),
|
|
1537
|
-
});
|
|
1538
|
-
return up;
|
|
1539
|
-
},
|
|
1540
|
-
mediaCache: config.mediaCache,
|
|
1541
|
-
options: config.options,
|
|
1542
|
-
messageId: generateMessageIDV2(sock.user?.id),
|
|
1543
|
-
...options,
|
|
1544
|
-
});
|
|
1545
|
-
const isEventMsg = "event" in content && !!content.event;
|
|
1546
|
-
const isDeleteMsg = "delete" in content && !!content.delete;
|
|
1547
|
-
const isEditMsg = "edit" in content && !!content.edit;
|
|
1548
|
-
const isPinMsg = "pin" in content && !!content.pin;
|
|
1549
|
-
const isPollMessage = "poll" in content && !!content.poll;
|
|
1550
|
-
const isAiMsg = "ai" in content && !!content.ai;
|
|
1551
|
-
const additionalAttributes = {};
|
|
1552
|
-
const additionalNodes = [];
|
|
1553
|
-
if (isDeleteMsg) {
|
|
1554
|
-
const fromMe = content.delete?.fromMe;
|
|
1555
|
-
const isGroup = isJidGroup(content.delete?.remoteJid);
|
|
1556
|
-
additionalAttributes.edit =
|
|
1557
|
-
(isGroup && !fromMe) || isJidNewsletter(jid) ? "8" : "7";
|
|
1558
|
-
} else if (isEditMsg) {
|
|
1559
|
-
additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
|
|
1560
|
-
} else if (isPinMsg) {
|
|
1561
|
-
additionalAttributes.edit = "2";
|
|
1562
|
-
} else if (isPollMessage) {
|
|
1563
|
-
additionalNodes.push({
|
|
1564
|
-
tag: "meta",
|
|
1565
|
-
attrs: { polltype: "creation" },
|
|
1566
|
-
});
|
|
1567
|
-
} else if (isEventMsg) {
|
|
1568
|
-
additionalNodes.push({
|
|
1569
|
-
tag: "meta",
|
|
1570
|
-
attrs: { event_type: "creation" },
|
|
1571
|
-
});
|
|
1572
|
-
} else if (isAiMsg) {
|
|
1573
|
-
additionalNodes.push({
|
|
1574
|
-
tag: "bot",
|
|
1575
|
-
attrs: { biz_bot: "1" },
|
|
1576
|
-
});
|
|
946
|
+
else if (message.interactiveResponseMessage) {
|
|
947
|
+
return 'native_flow_response';
|
|
948
|
+
}
|
|
949
|
+
else if (message.groupInviteMessage) {
|
|
950
|
+
return 'url';
|
|
1577
951
|
}
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
952
|
+
return '';
|
|
953
|
+
};
|
|
954
|
+
const issuePrivacyTokens = async (jids, timestamp) => {
|
|
955
|
+
const t = (timestamp ?? unixTimestampSeconds()).toString();
|
|
956
|
+
const result = await query({
|
|
957
|
+
tag: 'iq',
|
|
958
|
+
attrs: {
|
|
959
|
+
to: S_WHATSAPP_NET,
|
|
960
|
+
type: 'set',
|
|
961
|
+
xmlns: 'privacy'
|
|
962
|
+
},
|
|
963
|
+
content: [
|
|
964
|
+
{
|
|
965
|
+
tag: 'tokens',
|
|
966
|
+
attrs: {},
|
|
967
|
+
content: jids.map(jid => ({
|
|
968
|
+
tag: 'token',
|
|
969
|
+
attrs: {
|
|
970
|
+
jid: jidNormalizedUser(jid),
|
|
971
|
+
t,
|
|
972
|
+
type: 'trusted_contact'
|
|
973
|
+
}
|
|
974
|
+
}))
|
|
975
|
+
}
|
|
976
|
+
]
|
|
1584
977
|
});
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
978
|
+
return result;
|
|
979
|
+
};
|
|
980
|
+
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
|
|
981
|
+
const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
|
|
982
|
+
registerSocketEndHandler(() => {
|
|
983
|
+
if (!config.userDevicesCache && userDevicesCache.close) {
|
|
984
|
+
userDevicesCache.close();
|
|
985
|
+
}
|
|
986
|
+
mediaConn = undefined;
|
|
987
|
+
if (messageRetryManager) {
|
|
988
|
+
messageRetryManager.clear();
|
|
1589
989
|
}
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
990
|
+
});
|
|
991
|
+
return {
|
|
992
|
+
...sock,
|
|
993
|
+
userDevicesCache,
|
|
994
|
+
devicesMutex,
|
|
995
|
+
issuePrivacyTokens,
|
|
996
|
+
assertSessions,
|
|
997
|
+
relayMessage,
|
|
998
|
+
sendReceipt,
|
|
999
|
+
sendReceipts,
|
|
1000
|
+
readMessages,
|
|
1001
|
+
refreshMediaConn,
|
|
1002
|
+
// Function (not getter) so the spread in chats.ts preserves the live closure binding.
|
|
1003
|
+
getMediaHost: () => mediaHost,
|
|
1004
|
+
waUploadToServer,
|
|
1005
|
+
fetchPrivacySettings,
|
|
1006
|
+
sendPeerDataOperationMessage,
|
|
1007
|
+
createParticipantNodes,
|
|
1008
|
+
getUSyncDevices,
|
|
1009
|
+
messageRetryManager,
|
|
1010
|
+
updateMemberLabel,
|
|
1011
|
+
updateMediaMessage: async (message) => {
|
|
1012
|
+
const content = assertMediaContent(message.message);
|
|
1013
|
+
const mediaKey = content.mediaKey;
|
|
1014
|
+
const meId = authState.creds.me.id;
|
|
1015
|
+
const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
|
|
1016
|
+
let error = undefined;
|
|
1017
|
+
await Promise.all([
|
|
1018
|
+
sendNode(node),
|
|
1019
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
1020
|
+
const result = update.find(c => c.key.id === message.key.id);
|
|
1021
|
+
if (result) {
|
|
1022
|
+
if (result.error) {
|
|
1023
|
+
error = result.error;
|
|
1024
|
+
}
|
|
1025
|
+
else {
|
|
1026
|
+
try {
|
|
1027
|
+
const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
|
|
1028
|
+
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
1029
|
+
const resultStr = proto.MediaRetryNotification.ResultType[media.result];
|
|
1030
|
+
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
|
1031
|
+
data: media,
|
|
1032
|
+
statusCode: getStatusCodeForMediaRetry(media.result) || 404
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
content.directPath = media.directPath;
|
|
1036
|
+
content.url = getUrlFromDirectPath(content.directPath, mediaHost);
|
|
1037
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
|
|
1038
|
+
}
|
|
1039
|
+
catch (err) {
|
|
1040
|
+
error = err;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
return true;
|
|
1044
|
+
}
|
|
1045
|
+
})
|
|
1046
|
+
]);
|
|
1047
|
+
if (error) {
|
|
1048
|
+
throw error;
|
|
1049
|
+
}
|
|
1050
|
+
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
|
|
1051
|
+
return message;
|
|
1052
|
+
},
|
|
1053
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
1054
|
+
const userJid = authState.creds.me.id;
|
|
1055
|
+
if (typeof content === 'object' &&
|
|
1056
|
+
'disappearingMessagesInChat' in content &&
|
|
1057
|
+
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
|
1058
|
+
isJidGroup(jid)) {
|
|
1059
|
+
const { disappearingMessagesInChat } = content;
|
|
1060
|
+
const value = typeof disappearingMessagesInChat === 'boolean'
|
|
1061
|
+
? disappearingMessagesInChat
|
|
1062
|
+
? WA_DEFAULT_EPHEMERAL
|
|
1063
|
+
: 0
|
|
1064
|
+
: disappearingMessagesInChat;
|
|
1065
|
+
await groupToggleEphemeral(jid, value);
|
|
1066
|
+
}
|
|
1067
|
+
else {
|
|
1068
|
+
const fullMsg = await generateWAMessage(jid, content, {
|
|
1069
|
+
logger,
|
|
1070
|
+
userJid,
|
|
1071
|
+
getUrlInfo: text => getUrlInfo(text, {
|
|
1072
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1073
|
+
fetchOpts: {
|
|
1074
|
+
timeout: 3000,
|
|
1075
|
+
...(httpRequestOptions || {})
|
|
1076
|
+
},
|
|
1077
|
+
logger,
|
|
1078
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
1079
|
+
}),
|
|
1080
|
+
//TODO: CACHE
|
|
1081
|
+
getProfilePicUrl: sock.profilePictureUrl,
|
|
1082
|
+
getCallLink: sock.createCallLink,
|
|
1083
|
+
upload: waUploadToServer,
|
|
1084
|
+
mediaCache: config.mediaCache,
|
|
1085
|
+
options: config.options,
|
|
1086
|
+
messageId: generateMessageIDV2(sock.user?.id),
|
|
1087
|
+
...options
|
|
1088
|
+
});
|
|
1089
|
+
const isEventMsg = 'event' in content && !!content.event;
|
|
1090
|
+
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
1091
|
+
const isEditMsg = 'edit' in content && !!content.edit;
|
|
1092
|
+
const isPinMsg = 'pin' in content && !!content.pin;
|
|
1093
|
+
const isPollMessage = 'poll' in content && !!content.poll;
|
|
1094
|
+
const additionalAttributes = {};
|
|
1095
|
+
const additionalNodes = [];
|
|
1096
|
+
// required for delete
|
|
1097
|
+
if (isDeleteMsg) {
|
|
1098
|
+
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
1099
|
+
if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
|
|
1100
|
+
additionalAttributes.edit = '8';
|
|
1101
|
+
}
|
|
1102
|
+
else {
|
|
1103
|
+
additionalAttributes.edit = '7';
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
else if (isEditMsg) {
|
|
1107
|
+
additionalAttributes.edit = '1';
|
|
1108
|
+
}
|
|
1109
|
+
else if (isPinMsg) {
|
|
1110
|
+
additionalAttributes.edit = '2';
|
|
1111
|
+
}
|
|
1112
|
+
else if (isPollMessage) {
|
|
1113
|
+
additionalNodes.push({
|
|
1114
|
+
tag: 'meta',
|
|
1115
|
+
attrs: {
|
|
1116
|
+
polltype: 'creation'
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
else if (isEventMsg) {
|
|
1121
|
+
additionalNodes.push({
|
|
1122
|
+
tag: 'meta',
|
|
1123
|
+
attrs: {
|
|
1124
|
+
event_type: 'creation'
|
|
1125
|
+
}
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
await relayMessage(jid, fullMsg.message, {
|
|
1129
|
+
messageId: fullMsg.key.id,
|
|
1130
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1131
|
+
additionalAttributes,
|
|
1132
|
+
statusJidList: options.statusJidList,
|
|
1133
|
+
additionalNodes
|
|
1134
|
+
});
|
|
1135
|
+
if (config.emitOwnEvents) {
|
|
1136
|
+
process.nextTick(async () => {
|
|
1137
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
return fullMsg;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1594
1144
|
};
|
|
1595
|
-
//# sourceMappingURL=messages-send.js.map
|
|
1145
|
+
//# sourceMappingURL=messages-send.js.map
|