kage-baileys 3.0.6 → 3.2.3
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/Example/connection.cjs +4 -0
- package/README.MD +4726 -48
- package/WAProto/WAProto.proto +3395 -415
- package/WAProto/compat.cjs +12 -0
- package/WAProto/index.d.ts +47104 -19888
- package/WAProto/index.js +131979 -57361
- package/lib/Addon/http-error.js +43 -0
- package/lib/Addon/index.js +32 -0
- package/lib/Addon/keyed-db.js +250 -0
- package/lib/Addon/link-preview.js +82 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/connection.js +110 -0
- package/lib/Defaults/constants.js +156 -0
- package/lib/Defaults/history.js +46 -0
- package/lib/Defaults/index.js +230 -0
- package/lib/Defaults/media.js +104 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Defaults/prefix.js +44 -0
- package/lib/Extensions/business-advanced.js +382 -0
- package/lib/Extensions/business.js +159 -0
- package/lib/Extensions/chats-advanced.js +1106 -0
- package/lib/Extensions/chats.js +349 -0
- package/lib/Extensions/communities-advanced.js +430 -0
- package/lib/Extensions/community.js +94 -0
- package/lib/Extensions/groups-advanced.js +343 -0
- package/lib/Extensions/index.js +30 -0
- package/lib/Extensions/messages-recv-advanced.js +1690 -0
- package/lib/Extensions/messages-send-advanced.js +622 -0
- package/lib/Extensions/messages-send.js +1380 -0
- package/lib/Extensions/newsletter-advanced.js +228 -0
- package/lib/Extensions/newsletter.js +72 -0
- package/lib/Extensions/socket.js +389 -0
- package/lib/Modded/message_builder.js +2084 -4
- package/lib/Signal/Group/ciphertext-message.js +54 -0
- package/lib/Signal/Group/group-session-builder.js +124 -0
- package/lib/Signal/Group/group_cipher.js +216 -0
- package/lib/Signal/Group/index.js +124 -0
- package/lib/Signal/Group/keyhelper.js +108 -0
- package/lib/Signal/Group/sender-chain-key.js +83 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
- package/lib/Signal/Group/sender-key-message.js +166 -0
- package/lib/Signal/Group/sender-key-name.js +130 -0
- package/lib/Signal/Group/sender-key-record.js +113 -0
- package/lib/Signal/Group/sender-key-state.js +208 -0
- package/lib/Signal/Group/sender-message-key.js +82 -0
- package/lib/Signal/libsignal.js +935 -0
- package/lib/Signal/lid-mapping.js +545 -1
- package/lib/Socket/Client/index.js +60 -0
- package/lib/Socket/Client/types.js +51 -0
- package/lib/Socket/Client/websocket.js +152 -0
- package/lib/Socket/business.js +831 -0
- package/lib/Socket/chats.js +2535 -49
- package/lib/Socket/communities.js +450 -1
- package/lib/Socket/community.js +1022 -0
- package/lib/Socket/dugong.js +1 -1
- package/lib/Socket/groups.js +747 -0
- package/lib/Socket/index.js +60 -2
- package/lib/Socket/messages-recv.js +3450 -5
- package/lib/Socket/messages-send.js +3123 -0
- package/lib/Socket/mex.js +126 -1
- package/lib/Socket/newsletter.js +465 -0
- package/lib/Socket/socket.js +2217 -1
- package/lib/Store/index.js +79 -0
- package/lib/Store/make-cache-manager-store.js +186 -0
- package/lib/Store/make-in-memory-store.js +878 -0
- package/lib/Store/make-ordered-dictionary.js +187 -0
- package/lib/Store/object-repository.js +78 -0
- package/lib/Types/Auth.js +25 -0
- package/lib/Types/Bussines.js +25 -1
- package/lib/Types/Call.js +25 -0
- package/lib/Types/Chat.js +39 -0
- package/lib/Types/Contact.js +25 -0
- package/lib/Types/Events.js +25 -0
- package/lib/Types/GroupMetadata.js +25 -0
- package/lib/Types/Label.js +76 -0
- package/lib/Types/LabelAssociation.js +40 -0
- package/lib/Types/Message.js +57 -0
- package/lib/Types/Mex.js +56 -1
- package/lib/Types/MexUpdates.js +46 -0
- package/lib/Types/Newsletter.js +56 -0
- package/lib/Types/Product.js +25 -0
- package/lib/Types/RichType.js +23 -0
- package/lib/Types/Signal.js +25 -0
- package/lib/Types/Socket.js +25 -0
- package/lib/Types/State.js +92 -0
- package/lib/Types/USync.js +25 -0
- package/lib/Types/index.js +133 -0
- package/lib/Utils/auth-utils.js +703 -0
- package/lib/Utils/automation-tools.js +51 -16
- package/lib/Utils/baileys-event-stream.js +146 -0
- package/lib/Utils/browser-utils.js +95 -0
- package/lib/Utils/business.js +525 -0
- package/lib/Utils/chat-utils.js +1861 -0
- package/lib/Utils/companion-reg-client-utils.js +55 -1
- package/lib/Utils/crypto.js +355 -0
- package/lib/Utils/decode-wa-message.js +709 -0
- package/lib/Utils/event-buffer.js +1323 -8
- package/lib/Utils/generics.js +945 -1
- package/lib/Utils/history.js +266 -0
- package/lib/Utils/identity-change-handler.js +62 -1
- package/lib/Utils/index.js +114 -0
- package/lib/Utils/link-preview.js +179 -0
- package/lib/Utils/logger.js +42 -0
- package/lib/Utils/lt-hash.js +73 -0
- package/lib/Utils/make-mutex.js +104 -0
- package/lib/Utils/message-inspector.js +110 -0
- package/lib/Utils/message-retry-manager.js +507 -2
- package/lib/Utils/messages-media.js +1931 -1
- package/lib/Utils/messages.js +3748 -0
- package/lib/Utils/noise-handler.js +423 -0
- package/lib/Utils/offline-node-processor.js +53 -1
- package/lib/Utils/pre-key-manager.js +255 -1
- package/lib/Utils/process-message.js +1592 -0
- package/lib/Utils/reporting-utils.js +272 -1
- package/lib/Utils/rich-message-utils.js +377 -0
- package/lib/Utils/rich-messages.js +1 -1
- package/lib/Utils/signal.js +437 -0
- package/lib/Utils/stanza-ack.js +51 -1
- package/lib/Utils/status-refresh.js +37 -0
- package/lib/Utils/status-tools.js +4 -2
- package/lib/Utils/sync-action-utils.js +63 -1
- package/lib/Utils/tc-token-utils.js +185 -1
- package/lib/Utils/terminal-banner.js +31 -0
- package/lib/Utils/use-multi-file-auth-state.js +271 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +142 -0
- package/lib/Utils/validate-connection.js +497 -1
- package/lib/Utils/view-once-compat.js +13 -5
- package/lib/VoIP/audio-feeder.js +150 -0
- package/lib/VoIP/index.js +289 -0
- package/lib/VoIP/relay-transport.js +608 -0
- package/lib/VoIP/signaling.js +583 -0
- package/lib/VoIP/types.js +30 -0
- package/lib/VoIP/wasm-engine.js +1261 -2
- package/lib/VoIP/worker-bootstrap.js +1090 -2
- package/lib/WABinary/constants.js +2805 -0
- package/lib/WABinary/decode.js +649 -2
- package/lib/WABinary/encode.js +564 -2
- package/lib/WABinary/generic-utils.js +401 -0
- package/lib/WABinary/index.js +82 -0
- package/lib/WABinary/jid-utils.js +290 -0
- package/lib/WABinary/types.js +25 -0
- package/lib/WAM/BinaryInfo.js +50 -0
- package/lib/WAM/constants.js +45747 -0
- package/lib/WAM/encode.js +393 -0
- package/lib/WAM/index.js +78 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
- package/lib/WAUSync/Protocols/index.js +83 -0
- package/lib/WAUSync/USyncQuery.js +241 -2
- package/lib/WAUSync/USyncUser.js +86 -0
- package/lib/WAUSync/index.js +78 -0
- package/lib/assets/wasm/loader.js +1875 -1
- package/lib/assets/wasm/worker-modules.js +11047 -1
- package/lib/index.d.ts +126 -0
- package/lib/index.js +53 -21
- package/lib/index.mjs +437 -0
- package/licenses/upstream-MIT.txt +22 -0
- package/maintenance/api-coverage.json +1642 -0
- package/maintenance/archivos-sha256.json +207 -0
- package/maintenance/consumer-validation.log +3 -0
- package/maintenance/dependency-audit.json +4 -4
- package/maintenance/extension-inventory.json +57 -0
- package/maintenance/protocol-update.json +1101 -0
- package/maintenance/protocol-wire-audit.json +4 -0
- package/maintenance/reference-socket-surface.json +209 -0
- package/maintenance/resumen-validacion.json +50 -0
- package/maintenance/validation.log +2725 -0
- package/maintenance/verification.json +566 -0
- package/package.json +107 -9
- package/scripts/check-imports.cjs +10 -0
- package/scripts/check-package.cjs +40 -0
- package/scripts/check-syntax.cjs +1 -1
- package/scripts/generate-protobuf.cjs +6 -1
- package/scripts/generate-public-types.cjs +9 -0
- package/scripts/kage-base64-fix.cjs +45 -0
- package/scripts/maintenance.cjs +10 -0
- package/test/advanced.test.cjs +24 -0
- package/test/base64-fix.test.cjs +49 -0
- package/test/maintenance.test.cjs +1 -1
- package/test/npm-publication.test.cjs +141 -0
- package/test/recepcion-reparada.test.cjs +98 -0
- package/test/resilience-binary.test.cjs +69 -0
- package/test/resilience-transport.test.cjs +34 -0
- package/test/types.test.ts +5 -0
- package/test/upgrade.test.cjs +104 -0
- package/tsconfig.json +20 -0
- package/WAProto/p.html +0 -1
- package/lib/KageExtra/Modded/message_builder.js +0 -2330
- package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
- package/lib/KageExtra/VoIP/index.js +0 -282
- package/lib/KageExtra/VoIP/relay-transport.js +0 -559
- package/lib/KageExtra/VoIP/signaling.js +0 -603
- package/lib/KageExtra/VoIP/types.js +0 -17
- package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
- package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
- package/lib/KageExtra/assets/wasm/loader.js +0 -5
- package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
- package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
- package/lib/KageExtra/index.js +0 -3
- package/lib/KageExtra/package.json +0 -1
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
- package/maintenance/revision-full-check.txt +0 -1097
- package/maintenance/revision-library-tests.tap +0 -1088
- package/maintenance/revision-protobuf.txt +0 -5
- package/maintenance/revision-syntax.txt +0 -5
- package/maintenance/schema-coverage.json +0 -23
- package/maintenance/schema-merge.json +0 -30
- package/maintenance/validation-node20.txt +0 -191
- package/maintenance/validation-node22.txt +0 -237
|
@@ -877,3 +877,3126 @@ const makeMessagesSocket = (config) => {
|
|
|
877
877
|
};
|
|
878
878
|
};
|
|
879
879
|
exports.makeMessagesSocket = makeMessagesSocket;
|
|
880
|
+
|
|
881
|
+
// Kage: compatibilidad de API.
|
|
882
|
+
const __kageModule30 = (() => {
|
|
883
|
+
const module = { exports: {} }; const exports = module.exports;
|
|
884
|
+
"use strict"
|
|
885
|
+
|
|
886
|
+
Object.defineProperty(exports, "__esModule", { value: true })
|
|
887
|
+
|
|
888
|
+
const { default: NodeCache } = require("@cacheable/node-cache")
|
|
889
|
+
const { Boom } = require("@hapi/boom")
|
|
890
|
+
const { randomBytes } = require("crypto")
|
|
891
|
+
const { proto } = require("../../WAProto")
|
|
892
|
+
const {
|
|
893
|
+
DEFAULT_CACHE_TTLS,
|
|
894
|
+
WA_DEFAULT_EPHEMERAL
|
|
895
|
+
} = require("../Defaults/constants")
|
|
896
|
+
const {
|
|
897
|
+
delay,
|
|
898
|
+
assertMediaContent,
|
|
899
|
+
bindWaitForEvent,
|
|
900
|
+
decryptMediaRetryData,
|
|
901
|
+
encodeNewsletterMessage,
|
|
902
|
+
encodeSignedDeviceIdentity,
|
|
903
|
+
encodeWAMessage,
|
|
904
|
+
encryptMediaRetryRequest,
|
|
905
|
+
extractDeviceJids,
|
|
906
|
+
generateMessageID,
|
|
907
|
+
generateParticipantHashV2,
|
|
908
|
+
generateWAMessage,
|
|
909
|
+
generateWAMessageFromContent,
|
|
910
|
+
getStatusCodeForMediaRetry,
|
|
911
|
+
getUrlFromDirectPath,
|
|
912
|
+
getWAUploadToServer,
|
|
913
|
+
MessageRetryManager,
|
|
914
|
+
normalizeMessageContent,
|
|
915
|
+
parseAndInjectE2ESessions,
|
|
916
|
+
unixTimestampSeconds,
|
|
917
|
+
prepareAlbumMessageContent,
|
|
918
|
+
aggregateMessageKeysNotFromMe
|
|
919
|
+
} = require("../Utils")
|
|
920
|
+
const { WAMessageAddressingMode } = require("../Types")
|
|
921
|
+
const {
|
|
922
|
+
areJidsSameUser,
|
|
923
|
+
getBinaryNodeChild,
|
|
924
|
+
getBinaryNodeChildren,
|
|
925
|
+
getBinaryFilteredBizBot,
|
|
926
|
+
getBinaryFilteredButtons,
|
|
927
|
+
isHostedLidUser,
|
|
928
|
+
isHostedPnUser,
|
|
929
|
+
isJidNewsletter,
|
|
930
|
+
isJidGroup,
|
|
931
|
+
isLidUser,
|
|
932
|
+
isPnUser,
|
|
933
|
+
jidDecode,
|
|
934
|
+
jidEncode,
|
|
935
|
+
jidNormalizedUser,
|
|
936
|
+
STORIES_JID,
|
|
937
|
+
S_WHATSAPP_NET
|
|
938
|
+
} = require("../WABinary")
|
|
939
|
+
const {
|
|
940
|
+
USyncUser,
|
|
941
|
+
USyncQuery
|
|
942
|
+
} = require("../WAUSync")
|
|
943
|
+
const { makeNewsletterSocket } = require("./newsletter")
|
|
944
|
+
const { getUrlInfo } = require("../Utils/link-preview")
|
|
945
|
+
const { makeKeyedMutex } = require("../Utils/make-mutex")
|
|
946
|
+
|
|
947
|
+
const makeMessagesSocket = (config) => {
|
|
948
|
+
const {
|
|
949
|
+
logger,
|
|
950
|
+
linkPreviewImageThumbnailWidth,
|
|
951
|
+
generateHighQualityLinkPreview,
|
|
952
|
+
options: httpRequestOptions,
|
|
953
|
+
patchMessageBeforeSending,
|
|
954
|
+
cachedGroupMetadata,
|
|
955
|
+
enableRecentMessageCache,
|
|
956
|
+
maxMsgRetryCount
|
|
957
|
+
} = config
|
|
958
|
+
|
|
959
|
+
const suki = makeNewsletterSocket(config)
|
|
960
|
+
|
|
961
|
+
const {
|
|
962
|
+
ev,
|
|
963
|
+
authState,
|
|
964
|
+
messageMutex,
|
|
965
|
+
signalRepository,
|
|
966
|
+
upsertMessage,
|
|
967
|
+
createCallLink,
|
|
968
|
+
query,
|
|
969
|
+
fetchPrivacySettings,
|
|
970
|
+
sendNode,
|
|
971
|
+
groupQuery,
|
|
972
|
+
groupMetadata,
|
|
973
|
+
groupToggleEphemeral,
|
|
974
|
+
executeUSyncQuery,
|
|
975
|
+
newsletterMetadata
|
|
976
|
+
} = suki
|
|
977
|
+
|
|
978
|
+
const userDevicesCache = config.userDevicesCache || new NodeCache({
|
|
979
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
980
|
+
useClones: false
|
|
981
|
+
})
|
|
982
|
+
|
|
983
|
+
const peerSessionsCache = new NodeCache({
|
|
984
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
985
|
+
useClones: false
|
|
986
|
+
})
|
|
987
|
+
|
|
988
|
+
// Initialize message retry manager if enabled
|
|
989
|
+
const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null
|
|
990
|
+
|
|
991
|
+
// Prevent race conditions in Signal session encryption by user
|
|
992
|
+
const encryptionMutex = makeKeyedMutex()
|
|
993
|
+
|
|
994
|
+
let mediaConn
|
|
995
|
+
|
|
996
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
997
|
+
const media = await mediaConn
|
|
998
|
+
|
|
999
|
+
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
1000
|
+
mediaConn = (async () => {
|
|
1001
|
+
const result = await query({
|
|
1002
|
+
tag: 'iq',
|
|
1003
|
+
attrs: {
|
|
1004
|
+
type: 'set',
|
|
1005
|
+
xmlns: 'w:m',
|
|
1006
|
+
to: S_WHATSAPP_NET
|
|
1007
|
+
},
|
|
1008
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
1009
|
+
})
|
|
1010
|
+
|
|
1011
|
+
const mediaConnNode = getBinaryNodeChild(result, 'media_conn')
|
|
1012
|
+
|
|
1013
|
+
// TODO: explore full length of data that whatsapp provides
|
|
1014
|
+
const node = {
|
|
1015
|
+
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
1016
|
+
hostname: attrs.hostname,
|
|
1017
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
1018
|
+
})),
|
|
1019
|
+
auth: mediaConnNode.attrs.auth,
|
|
1020
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
1021
|
+
fetchDate: new Date()
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
logger.debug('fetched media conn')
|
|
1025
|
+
|
|
1026
|
+
return node
|
|
1027
|
+
})()
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
return mediaConn
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* generic send receipt function
|
|
1035
|
+
* used for receipts of phone call, read, delivery etc.
|
|
1036
|
+
* */
|
|
1037
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
1038
|
+
if (!messageIds || messageIds.length === 0) {
|
|
1039
|
+
throw new Boom('missing ids in receipt')
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
const node = {
|
|
1043
|
+
tag: 'receipt',
|
|
1044
|
+
attrs: {
|
|
1045
|
+
id: messageIds[0]
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const isReadReceipt = type === 'read' || type === 'read-self'
|
|
1050
|
+
|
|
1051
|
+
if (isReadReceipt) {
|
|
1052
|
+
node.attrs.t = unixTimestampSeconds().toString()
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
|
|
1056
|
+
node.attrs.recipient = jid
|
|
1057
|
+
node.attrs.to = participant
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
else {
|
|
1061
|
+
node.attrs.to = jid
|
|
1062
|
+
|
|
1063
|
+
if (participant) {
|
|
1064
|
+
node.attrs.participant = participant
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
if (type) {
|
|
1069
|
+
node.attrs.type = type
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
const remainingMessageIds = messageIds.slice(1)
|
|
1073
|
+
|
|
1074
|
+
if (remainingMessageIds.length) {
|
|
1075
|
+
node.content = [
|
|
1076
|
+
{
|
|
1077
|
+
tag: 'list',
|
|
1078
|
+
attrs: {},
|
|
1079
|
+
content: remainingMessageIds.map(id => ({
|
|
1080
|
+
tag: 'item',
|
|
1081
|
+
attrs: { id }
|
|
1082
|
+
}))
|
|
1083
|
+
}
|
|
1084
|
+
]
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
|
|
1088
|
+
|
|
1089
|
+
await sendNode(node)
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/** Correctly bulk send receipts to multiple chats, participants */
|
|
1093
|
+
const sendReceipts = async (keys, type) => {
|
|
1094
|
+
const recps = aggregateMessageKeysNotFromMe(keys)
|
|
1095
|
+
|
|
1096
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
1097
|
+
await sendReceipt(jid, participant, messageIds, type)
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/** Bulk read messages. Keys can be from different chats & participants */
|
|
1102
|
+
const readMessages = async (keys) => {
|
|
1103
|
+
const privacySettings = await fetchPrivacySettings()
|
|
1104
|
+
|
|
1105
|
+
// based on privacy settings, we have to change the read type
|
|
1106
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
|
|
1107
|
+
|
|
1108
|
+
await sendReceipts(keys, readType)
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** Fetch all the devices we've to send a message to */
|
|
1112
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
1113
|
+
const deviceResults = []
|
|
1114
|
+
|
|
1115
|
+
if (!useCache) {
|
|
1116
|
+
logger.debug('not using cache for devices')
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
const toFetch = []
|
|
1120
|
+
|
|
1121
|
+
const jidsWithUser = jids
|
|
1122
|
+
.map(jid => {
|
|
1123
|
+
const decoded = jidDecode(jid)
|
|
1124
|
+
const user = decoded?.user
|
|
1125
|
+
const device = decoded?.device
|
|
1126
|
+
const isExplicitDevice = typeof device === 'number' && device >= 0
|
|
1127
|
+
|
|
1128
|
+
if (isExplicitDevice && user) {
|
|
1129
|
+
deviceResults.push({
|
|
1130
|
+
user,
|
|
1131
|
+
device,
|
|
1132
|
+
jid
|
|
1133
|
+
})
|
|
1134
|
+
|
|
1135
|
+
return null
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
jid = jidNormalizedUser(jid)
|
|
1139
|
+
|
|
1140
|
+
return { jid, user }
|
|
1141
|
+
}).filter(jid => jid !== null)
|
|
1142
|
+
|
|
1143
|
+
let mgetDevices
|
|
1144
|
+
|
|
1145
|
+
if (useCache && userDevicesCache.mget) {
|
|
1146
|
+
const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean)
|
|
1147
|
+
|
|
1148
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch)
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
for (const { jid, user } of jidsWithUser) {
|
|
1152
|
+
if (useCache) {
|
|
1153
|
+
const devices = mgetDevices?.[user] ||
|
|
1154
|
+
(userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)))
|
|
1155
|
+
|
|
1156
|
+
if (devices) {
|
|
1157
|
+
const devicesWithJid = devices.map(d => ({
|
|
1158
|
+
...d,
|
|
1159
|
+
jid: jidEncode(d.user, d.server, d.device)
|
|
1160
|
+
}))
|
|
1161
|
+
|
|
1162
|
+
deviceResults.push(...devicesWithJid)
|
|
1163
|
+
|
|
1164
|
+
logger.trace({ user }, 'using cache for devices')
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
else {
|
|
1168
|
+
toFetch.push(jid)
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
else {
|
|
1173
|
+
toFetch.push(jid)
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
if (!toFetch.length) {
|
|
1178
|
+
return deviceResults
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
const requestedLidUsers = new Set()
|
|
1182
|
+
|
|
1183
|
+
for (const jid of toFetch) {
|
|
1184
|
+
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
1185
|
+
const user = jidDecode(jid)?.user
|
|
1186
|
+
|
|
1187
|
+
if (user)
|
|
1188
|
+
requestedLidUsers.add(user)
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol()
|
|
1193
|
+
|
|
1194
|
+
for (const jid of toFetch) {
|
|
1195
|
+
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
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const result = await executeUSyncQuery(query)
|
|
1199
|
+
|
|
1200
|
+
if (result) {
|
|
1201
|
+
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
1202
|
+
const lidResults = result.list.filter(a => !!a.lid)
|
|
1203
|
+
|
|
1204
|
+
if (lidResults.length > 0) {
|
|
1205
|
+
logger.trace('Storing LID maps from device call')
|
|
1206
|
+
|
|
1207
|
+
await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })))
|
|
1208
|
+
|
|
1209
|
+
// Force-refresh sessions for newly mapped LIDs to align identity addressing
|
|
1210
|
+
try {
|
|
1211
|
+
const lids = lidResults.map(a => a.lid)
|
|
1212
|
+
|
|
1213
|
+
if (lids.length) {
|
|
1214
|
+
await assertSessions(lids, true)
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
catch (e) {
|
|
1219
|
+
logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs')
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices)
|
|
1224
|
+
|
|
1225
|
+
const deviceMap = {}
|
|
1226
|
+
|
|
1227
|
+
for (const item of extracted) {
|
|
1228
|
+
deviceMap[item.user] = deviceMap[item.user] || []
|
|
1229
|
+
deviceMap[item.user]?.push(item)
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// Process each user's devices as a group for bulk LID migration
|
|
1233
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
1234
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
1235
|
+
// Process all devices for this user
|
|
1236
|
+
for (const item of userDevices) {
|
|
1237
|
+
const finalJid = isLidUser
|
|
1238
|
+
? jidEncode(user, item.server, item.device)
|
|
1239
|
+
: jidEncode(item.user, item.server, item.device)
|
|
1240
|
+
deviceResults.push({
|
|
1241
|
+
...item,
|
|
1242
|
+
jid: finalJid
|
|
1243
|
+
})
|
|
1244
|
+
|
|
1245
|
+
logger.debug({
|
|
1246
|
+
user: item.user,
|
|
1247
|
+
device: item.device,
|
|
1248
|
+
finalJid,
|
|
1249
|
+
usedLid: isLidUser
|
|
1250
|
+
}, 'Processed device with LID priority')
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
if (userDevicesCache.mset) {
|
|
1255
|
+
// if the cache supports mset, we can set all devices in one go
|
|
1256
|
+
await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })))
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
else {
|
|
1260
|
+
for (const key in deviceMap) {
|
|
1261
|
+
if (deviceMap[key])
|
|
1262
|
+
await userDevicesCache.set(key, deviceMap[key])
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
const userDeviceUpdates = {}
|
|
1267
|
+
|
|
1268
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
1269
|
+
if (devices && devices.length > 0) {
|
|
1270
|
+
userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0')
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
1275
|
+
try {
|
|
1276
|
+
await authState.keys.set({ 'device-list': userDeviceUpdates })
|
|
1277
|
+
|
|
1278
|
+
logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration')
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
catch (error) {
|
|
1282
|
+
logger.warn({ error }, 'failed to store user device lists')
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
return deviceResults
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const updateMemberLabel = (jid, memberLabel) => {
|
|
1291
|
+
if (!isJidGroup(jid)) {
|
|
1292
|
+
throw new Error('Jid must a group!')
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
const protocolMessage = {
|
|
1296
|
+
protocolMessage: {
|
|
1297
|
+
type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
|
|
1298
|
+
memberLabel: {
|
|
1299
|
+
label: memberLabel?.slice(0, 30),
|
|
1300
|
+
labelTimestamp: unixTimestampSeconds()
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
return relayMessage(jid, protocolMessage, {
|
|
1306
|
+
additionalNodes: [
|
|
1307
|
+
{
|
|
1308
|
+
tag: 'meta',
|
|
1309
|
+
attrs: {
|
|
1310
|
+
tag_reason: 'user_update',
|
|
1311
|
+
appdata: 'member_tag'
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
]
|
|
1315
|
+
})
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
const assertSessions = async (jids, force) => {
|
|
1319
|
+
let didFetchNewSession = false
|
|
1320
|
+
|
|
1321
|
+
const uniqueJids = [...new Set(jids)] // Deduplicate JIDs
|
|
1322
|
+
const jidsRequiringFetch = []
|
|
1323
|
+
|
|
1324
|
+
logger.debug({ jids }, 'assertSessions call with jids')
|
|
1325
|
+
|
|
1326
|
+
// Check peerSessionsCache and validate sessions using libsignal loadSession
|
|
1327
|
+
for (const jid of uniqueJids) {
|
|
1328
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(jid)
|
|
1329
|
+
const cachedSession = peerSessionsCache.get(signalId)
|
|
1330
|
+
|
|
1331
|
+
if (cachedSession !== undefined) {
|
|
1332
|
+
if (cachedSession && !force) {
|
|
1333
|
+
continue // Session exists in cache
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
else {
|
|
1338
|
+
const sessionValidation = await signalRepository.validateSession(jid)
|
|
1339
|
+
const hasSession = sessionValidation.exists
|
|
1340
|
+
|
|
1341
|
+
peerSessionsCache.set(signalId, hasSession)
|
|
1342
|
+
|
|
1343
|
+
if (hasSession && !force) {
|
|
1344
|
+
continue
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
jidsRequiringFetch.push(jid)
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
if (jidsRequiringFetch.length) {
|
|
1352
|
+
// LID if mapped, otherwise original
|
|
1353
|
+
const wireJids = [
|
|
1354
|
+
...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
1355
|
+
...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
|
|
1356
|
+
]
|
|
1357
|
+
|
|
1358
|
+
logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions')
|
|
1359
|
+
|
|
1360
|
+
const result = await query({
|
|
1361
|
+
tag: 'iq',
|
|
1362
|
+
attrs: {
|
|
1363
|
+
xmlns: 'encrypt',
|
|
1364
|
+
type: 'get',
|
|
1365
|
+
to: S_WHATSAPP_NET
|
|
1366
|
+
},
|
|
1367
|
+
content: [
|
|
1368
|
+
{
|
|
1369
|
+
tag: 'key',
|
|
1370
|
+
attrs: {},
|
|
1371
|
+
content: wireJids.map(jid => {
|
|
1372
|
+
const attrs = { jid }
|
|
1373
|
+
|
|
1374
|
+
if (force) attrs.reason = 'identity'
|
|
1375
|
+
|
|
1376
|
+
return { tag: 'user', attrs }
|
|
1377
|
+
})
|
|
1378
|
+
}
|
|
1379
|
+
]
|
|
1380
|
+
})
|
|
1381
|
+
|
|
1382
|
+
await parseAndInjectE2ESessions(result, signalRepository)
|
|
1383
|
+
|
|
1384
|
+
didFetchNewSession = true
|
|
1385
|
+
|
|
1386
|
+
// Cache fetched sessions using wire JIDs
|
|
1387
|
+
for (const wireJid of wireJids) {
|
|
1388
|
+
const signalId = signalRepository.jidToSignalProtocolAddress(wireJid)
|
|
1389
|
+
peerSessionsCache.set(signalId, true)
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
return didFetchNewSession
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
1397
|
+
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
|
1398
|
+
if (!authState.creds.me?.id) {
|
|
1399
|
+
throw new Boom('Not authenticated')
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
const protocolMessage = {
|
|
1403
|
+
protocolMessage: {
|
|
1404
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
1405
|
+
type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
const meJid = jidNormalizedUser(authState.creds.me.id)
|
|
1410
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
1411
|
+
additionalAttributes: {
|
|
1412
|
+
category: 'peer',
|
|
1413
|
+
push_priority: 'high_force'
|
|
1414
|
+
},
|
|
1415
|
+
additionalNodes: [
|
|
1416
|
+
{
|
|
1417
|
+
tag: 'meta',
|
|
1418
|
+
attrs: { appdata: 'default' }
|
|
1419
|
+
}
|
|
1420
|
+
]
|
|
1421
|
+
})
|
|
1422
|
+
|
|
1423
|
+
return msgId
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
|
|
1427
|
+
if (!recipientJids.length) {
|
|
1428
|
+
return { nodes: [], shouldIncludeDeviceIdentity: false }
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
const patched = await patchMessageBeforeSending(message, recipientJids)
|
|
1432
|
+
const patchedMessages = Array.isArray(patched)
|
|
1433
|
+
? patched
|
|
1434
|
+
: recipientJids.map(jid => ({ recipientJid: jid, message: patched }))
|
|
1435
|
+
|
|
1436
|
+
let shouldIncludeDeviceIdentity = false
|
|
1437
|
+
|
|
1438
|
+
const meId = authState.creds.me.id
|
|
1439
|
+
const meLid = authState.creds.me?.lid
|
|
1440
|
+
const meLidUser = meLid ? jidDecode(meLid)?.user : null
|
|
1441
|
+
const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
1442
|
+
if (!jid) return null
|
|
1443
|
+
|
|
1444
|
+
let msgToEncrypt = patchedMessage
|
|
1445
|
+
|
|
1446
|
+
if (dsmMessage) {
|
|
1447
|
+
const { user: targetUser } = jidDecode(jid)
|
|
1448
|
+
const { user: ownPnUser } = jidDecode(meId)
|
|
1449
|
+
const ownLidUser = meLidUser
|
|
1450
|
+
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser)
|
|
1451
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
|
|
1452
|
+
|
|
1453
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
1454
|
+
msgToEncrypt = dsmMessage
|
|
1455
|
+
logger.debug({ jid, targetUser }, 'Using DSM for own device')
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
const bytes = encodeWAMessage(msgToEncrypt)
|
|
1460
|
+
const mutexKey = jid
|
|
1461
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
1462
|
+
const { type, ciphertext } = await signalRepository.encryptMessage({
|
|
1463
|
+
jid,
|
|
1464
|
+
data: bytes
|
|
1465
|
+
})
|
|
1466
|
+
|
|
1467
|
+
if (type === 'pkmsg') {
|
|
1468
|
+
shouldIncludeDeviceIdentity = true
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
return {
|
|
1472
|
+
tag: 'to',
|
|
1473
|
+
attrs: { jid },
|
|
1474
|
+
content: [
|
|
1475
|
+
{
|
|
1476
|
+
tag: 'enc',
|
|
1477
|
+
attrs: {
|
|
1478
|
+
v: '2',
|
|
1479
|
+
type,
|
|
1480
|
+
...(extraAttrs || {})
|
|
1481
|
+
},
|
|
1482
|
+
content: ciphertext
|
|
1483
|
+
}
|
|
1484
|
+
]
|
|
1485
|
+
};
|
|
1486
|
+
})
|
|
1487
|
+
|
|
1488
|
+
return node
|
|
1489
|
+
})
|
|
1490
|
+
|
|
1491
|
+
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null)
|
|
1492
|
+
|
|
1493
|
+
return { nodes, shouldIncludeDeviceIdentity }
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
/** Fetch image for groups, user, and newsletter **/
|
|
1497
|
+
const profilePictureUrl = async (jid) => {
|
|
1498
|
+
if (isJidNewsletter(jid)) {
|
|
1499
|
+
const metadata = await suki.newsletterMetadata('JID', jid)
|
|
1500
|
+
|
|
1501
|
+
return getUrlFromDirectPath(metadata.thread_metadata.picture?.direct_path || '')
|
|
1502
|
+
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
else {
|
|
1506
|
+
const result = await query({
|
|
1507
|
+
tag: 'iq',
|
|
1508
|
+
attrs: {
|
|
1509
|
+
target: jidNormalizedUser(jid),
|
|
1510
|
+
to: S_WHATSAPP_NET,
|
|
1511
|
+
type: 'get',
|
|
1512
|
+
xmlns: 'w:profile:picture'
|
|
1513
|
+
},
|
|
1514
|
+
content: [{
|
|
1515
|
+
tag: 'picture',
|
|
1516
|
+
attrs: {
|
|
1517
|
+
type: 'image',
|
|
1518
|
+
query: 'url'
|
|
1519
|
+
}
|
|
1520
|
+
}]
|
|
1521
|
+
})
|
|
1522
|
+
|
|
1523
|
+
const child = getBinaryNodeChild(result, 'picture')
|
|
1524
|
+
|
|
1525
|
+
return child?.attrs?.url || null
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, additionalNodes, AI = false }) => {
|
|
1530
|
+
const meId = authState.creds.me.id
|
|
1531
|
+
const meLid = authState.creds.me?.lid
|
|
1532
|
+
const isRetryResend = Boolean(participant?.jid)
|
|
1533
|
+
|
|
1534
|
+
let shouldIncludeDeviceIdentity = isRetryResend
|
|
1535
|
+
let didPushAdditional = false
|
|
1536
|
+
|
|
1537
|
+
const statusJid = 'status@broadcast'
|
|
1538
|
+
const { user, server } = jidDecode(jid)
|
|
1539
|
+
const isGroup = server === 'g.us'
|
|
1540
|
+
const isStatus = jid === statusJid
|
|
1541
|
+
const isLid = server === 'lid'
|
|
1542
|
+
const isNewsletter = server === 'newsletter'
|
|
1543
|
+
const isGroupOrStatus = isGroup || isStatus
|
|
1544
|
+
const finalJid = jid
|
|
1545
|
+
|
|
1546
|
+
msgId = msgId || generateMessageID(meId)
|
|
1547
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
1548
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
|
|
1549
|
+
|
|
1550
|
+
const participants = []
|
|
1551
|
+
const destinationJid = !isStatus ? finalJid : statusJid
|
|
1552
|
+
const binaryNodeContent = []
|
|
1553
|
+
const devices = []
|
|
1554
|
+
|
|
1555
|
+
const meMsg = {
|
|
1556
|
+
deviceSentMessage: {
|
|
1557
|
+
destinationJid,
|
|
1558
|
+
message
|
|
1559
|
+
},
|
|
1560
|
+
messageContextInfo: message.messageContextInfo
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
const extraAttrs = {}
|
|
1564
|
+
|
|
1565
|
+
const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
|
|
1566
|
+
|
|
1567
|
+
const messages = normalizeMessageContent(message)
|
|
1568
|
+
|
|
1569
|
+
const buttonType = getButtonType(messages)
|
|
1570
|
+
const pollMessage = messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
|
|
1571
|
+
|
|
1572
|
+
|
|
1573
|
+
if (participant) {
|
|
1574
|
+
if (!isGroup && !isStatus) {
|
|
1575
|
+
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
const { user, device } = jidDecode(participant.jid)
|
|
1579
|
+
|
|
1580
|
+
devices.push({
|
|
1581
|
+
user,
|
|
1582
|
+
device,
|
|
1583
|
+
jid: participant.jid
|
|
1584
|
+
})
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
await authState.keys.transaction(async () => {
|
|
1588
|
+
const mediaType = getMediaType(message)
|
|
1589
|
+
|
|
1590
|
+
if (mediaType) {
|
|
1591
|
+
extraAttrs['mediatype'] = mediaType
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
if (isNewsletter) {
|
|
1595
|
+
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message
|
|
1596
|
+
const bytes = encodeNewsletterMessage(patched)
|
|
1597
|
+
|
|
1598
|
+
binaryNodeContent.push({
|
|
1599
|
+
tag: 'plaintext',
|
|
1600
|
+
attrs: {},
|
|
1601
|
+
content: bytes
|
|
1602
|
+
})
|
|
1603
|
+
|
|
1604
|
+
const stanza = {
|
|
1605
|
+
tag: 'message',
|
|
1606
|
+
attrs: {
|
|
1607
|
+
to: jid,
|
|
1608
|
+
id: msgId,
|
|
1609
|
+
type: getTypeMessage(message),
|
|
1610
|
+
...(additionalAttributes || {})
|
|
1611
|
+
},
|
|
1612
|
+
content: binaryNodeContent
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
logger.debug({ msgId }, `sending newsletter message to ${jid}`)
|
|
1616
|
+
|
|
1617
|
+
await sendNode(stanza)
|
|
1618
|
+
|
|
1619
|
+
return
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
|
|
1623
|
+
extraAttrs['decrypt-fail'] = 'hide'
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
|
|
1627
|
+
extraAttrs['native_flow_name'] = messages.interactiveResponseMessage.nativeFlowResponseMessage?.name || 'menu_options'
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
if (isGroupOrStatus && !isRetryResend) {
|
|
1631
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
1632
|
+
(async () => {
|
|
1633
|
+
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?
|
|
1634
|
+
|
|
1635
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
1636
|
+
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
else if (!isStatus) {
|
|
1640
|
+
groupData = await groupMetadata(jid) // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
return groupData
|
|
1644
|
+
})(),
|
|
1645
|
+
(async () => {
|
|
1646
|
+
if (!participant && !isStatus) {
|
|
1647
|
+
// what if sender memory is less accurate than the cached metadata
|
|
1648
|
+
// on participant change in group, we should do sender memory manipulation
|
|
1649
|
+
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?
|
|
1650
|
+
|
|
1651
|
+
return result[jid] || {}
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
return {}
|
|
1655
|
+
})()
|
|
1656
|
+
])
|
|
1657
|
+
|
|
1658
|
+
const participantsList = groupData ? groupData.participants.map(p => p.id) : []
|
|
1659
|
+
|
|
1660
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
1661
|
+
additionalAttributes = {
|
|
1662
|
+
...additionalAttributes,
|
|
1663
|
+
expiration: groupData.ephemeralDuration.toString()
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
if (isStatus && statusJidList) {
|
|
1668
|
+
participantsList.push(...statusJidList)
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
|
|
1672
|
+
|
|
1673
|
+
devices.push(...additionalDevices)
|
|
1674
|
+
|
|
1675
|
+
if (isGroup) {
|
|
1676
|
+
additionalAttributes = {
|
|
1677
|
+
...additionalAttributes,
|
|
1678
|
+
addressing_mode: groupData?.addressingMode || 'lid'
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
const patched = await patchMessageBeforeSending(message)
|
|
1683
|
+
|
|
1684
|
+
if (Array.isArray(patched)) {
|
|
1685
|
+
throw new Boom('Per-jid patching is not supported in groups')
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
const bytes = encodeWAMessage(patched)
|
|
1689
|
+
const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
|
|
1690
|
+
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId
|
|
1691
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
1692
|
+
group: destinationJid,
|
|
1693
|
+
data: bytes,
|
|
1694
|
+
meId: groupSenderIdentity
|
|
1695
|
+
})
|
|
1696
|
+
|
|
1697
|
+
const senderKeyRecipients = []
|
|
1698
|
+
|
|
1699
|
+
for (const device of devices) {
|
|
1700
|
+
const deviceJid = device.jid
|
|
1701
|
+
const hasKey = !!senderKeyMap[deviceJid]
|
|
1702
|
+
|
|
1703
|
+
if ((!hasKey || !!participant) &&
|
|
1704
|
+
!isHostedLidUser(deviceJid) &&
|
|
1705
|
+
!isHostedPnUser(deviceJid) &&
|
|
1706
|
+
device.device !== 99) {
|
|
1707
|
+
//todo: revamp all this logic
|
|
1708
|
+
// 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
|
|
1709
|
+
senderKeyRecipients.push(deviceJid)
|
|
1710
|
+
senderKeyMap[deviceJid] = true
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
if (senderKeyRecipients.length) {
|
|
1715
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
|
|
1716
|
+
|
|
1717
|
+
const senderKeyMsg = {
|
|
1718
|
+
senderKeyDistributionMessage: {
|
|
1719
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
1720
|
+
groupId: destinationJid
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
const senderKeySessionTargets = senderKeyRecipients
|
|
1725
|
+
|
|
1726
|
+
await assertSessions(senderKeySessionTargets)
|
|
1727
|
+
|
|
1728
|
+
const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
|
|
1729
|
+
|
|
1730
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
1731
|
+
participants.push(...result.nodes)
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
binaryNodeContent.push({
|
|
1735
|
+
tag: 'enc',
|
|
1736
|
+
attrs: { v: '2', type: 'skmsg', ...extraAttrs },
|
|
1737
|
+
content: ciphertext
|
|
1738
|
+
})
|
|
1739
|
+
|
|
1740
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
else {
|
|
1744
|
+
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
1745
|
+
// TODO: investigate if this is true
|
|
1746
|
+
let ownId = meId
|
|
1747
|
+
|
|
1748
|
+
if (isLid && meLid) {
|
|
1749
|
+
ownId = meLid;
|
|
1750
|
+
logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
else {
|
|
1754
|
+
logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
const { user: ownUser } = jidDecode(ownId)
|
|
1758
|
+
|
|
1759
|
+
if (!isRetryResend) {
|
|
1760
|
+
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net'
|
|
1761
|
+
|
|
1762
|
+
devices.push({
|
|
1763
|
+
user,
|
|
1764
|
+
device: 0,
|
|
1765
|
+
jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
|
|
1766
|
+
})
|
|
1767
|
+
|
|
1768
|
+
if (user !== ownUser) {
|
|
1769
|
+
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net'
|
|
1770
|
+
const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user
|
|
1771
|
+
|
|
1772
|
+
devices.push({
|
|
1773
|
+
user: ownUserForAddressing,
|
|
1774
|
+
device: 0,
|
|
1775
|
+
jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
|
|
1776
|
+
})
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
1780
|
+
// Clear placeholders and enumerate actual devices
|
|
1781
|
+
devices.length = 0
|
|
1782
|
+
|
|
1783
|
+
// Use conversation-appropriate sender identity
|
|
1784
|
+
const senderIdentity = isLid && meLid
|
|
1785
|
+
? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
|
|
1786
|
+
: jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
|
|
1787
|
+
// Enumerate devices for sender and target with consistent addressing
|
|
1788
|
+
const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
|
|
1789
|
+
|
|
1790
|
+
devices.push(...sessionDevices)
|
|
1791
|
+
|
|
1792
|
+
logger.debug({
|
|
1793
|
+
deviceCount: devices.length,
|
|
1794
|
+
devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
|
|
1795
|
+
}, 'Device enumeration complete with unified addressing')
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
const allRecipients = []
|
|
1800
|
+
const meRecipients = []
|
|
1801
|
+
const otherRecipients = []
|
|
1802
|
+
|
|
1803
|
+
const { user: mePnUser } = jidDecode(meId)
|
|
1804
|
+
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null }
|
|
1805
|
+
|
|
1806
|
+
for (const { user, jid } of devices) {
|
|
1807
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
|
|
1808
|
+
|
|
1809
|
+
if (isExactSenderDevice) {
|
|
1810
|
+
logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
|
|
1811
|
+
continue
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// Check if this is our device (could match either PN or LID user)
|
|
1815
|
+
const isMe = user === mePnUser || user === meLidUser
|
|
1816
|
+
|
|
1817
|
+
if (isMe) {
|
|
1818
|
+
meRecipients.push(jid);
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
else {
|
|
1822
|
+
otherRecipients.push(jid)
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
allRecipients.push(jid)
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
await assertSessions(allRecipients)
|
|
1829
|
+
|
|
1830
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
1831
|
+
// For own devices: use DSM if available (1:1 chats only)
|
|
1832
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
1833
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
|
|
1834
|
+
])
|
|
1835
|
+
|
|
1836
|
+
participants.push(...meNodes)
|
|
1837
|
+
participants.push(...otherNodes)
|
|
1838
|
+
|
|
1839
|
+
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
1840
|
+
extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients])
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
if (isRetryResend) {
|
|
1847
|
+
const isParticipantLid = isLidUser(participant.jid)
|
|
1848
|
+
const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId)
|
|
1849
|
+
const encodedMessageToSend = isMe
|
|
1850
|
+
? encodeWAMessage({
|
|
1851
|
+
deviceSentMessage: {
|
|
1852
|
+
destinationJid,
|
|
1853
|
+
message
|
|
1854
|
+
}
|
|
1855
|
+
})
|
|
1856
|
+
: encodeWAMessage(message)
|
|
1857
|
+
const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
|
|
1858
|
+
data: encodedMessageToSend,
|
|
1859
|
+
jid: participant.jid
|
|
1860
|
+
})
|
|
1861
|
+
|
|
1862
|
+
binaryNodeContent.push({
|
|
1863
|
+
tag: 'enc',
|
|
1864
|
+
attrs: {
|
|
1865
|
+
v: '2',
|
|
1866
|
+
type,
|
|
1867
|
+
count: participant.count.toString()
|
|
1868
|
+
},
|
|
1869
|
+
content: encryptedContent
|
|
1870
|
+
})
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
if (participants.length) {
|
|
1874
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
1875
|
+
const peerNode = participants[0]?.content?.[0]
|
|
1876
|
+
|
|
1877
|
+
if (peerNode) {
|
|
1878
|
+
binaryNodeContent.push(peerNode) // push only enc
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
else {
|
|
1883
|
+
binaryNodeContent.push({
|
|
1884
|
+
tag: 'participants',
|
|
1885
|
+
attrs: {},
|
|
1886
|
+
content: participants
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
const stanza = {
|
|
1892
|
+
tag: 'message',
|
|
1893
|
+
attrs: {
|
|
1894
|
+
id: msgId,
|
|
1895
|
+
to: destinationJid,
|
|
1896
|
+
type: getTypeMessage(message),
|
|
1897
|
+
...(additionalAttributes || {})
|
|
1898
|
+
},
|
|
1899
|
+
content: binaryNodeContent
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// if the participant to send to is explicitly specified (generally retry recp)
|
|
1903
|
+
// ensure the message is only sent to that person
|
|
1904
|
+
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
1905
|
+
if (participant) {
|
|
1906
|
+
if (isJidGroup(destinationJid)) {
|
|
1907
|
+
stanza.attrs.to = destinationJid
|
|
1908
|
+
stanza.attrs.participant = participant.jid
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
else if (areJidsSameUser(participant.jid, meId)) {
|
|
1912
|
+
stanza.attrs.to = participant.jid
|
|
1913
|
+
stanza.attrs.recipient = destinationJid
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
else {
|
|
1917
|
+
stanza.attrs.to = participant.jid
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
else {
|
|
1922
|
+
stanza.attrs.to = destinationJid
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
if (shouldIncludeDeviceIdentity) {
|
|
1926
|
+
stanza.content.push({
|
|
1927
|
+
tag: 'device-identity',
|
|
1928
|
+
attrs: {},
|
|
1929
|
+
content: encodeSignedDeviceIdentity(authState.creds.account, true)
|
|
1930
|
+
})
|
|
1931
|
+
|
|
1932
|
+
logger.debug({ jid }, 'adding device identity')
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {}
|
|
1936
|
+
const tcTokenBuffer = contactTcTokenData[destinationJid]?.token
|
|
1937
|
+
|
|
1938
|
+
if (tcTokenBuffer) {
|
|
1939
|
+
stanza.content.push({
|
|
1940
|
+
tag: 'tctoken',
|
|
1941
|
+
attrs: {},
|
|
1942
|
+
content: tcTokenBuffer
|
|
1943
|
+
})
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
if (isGroup && regexGroupOld.test(jid) && !message.reactionMessage) {
|
|
1947
|
+
stanza.content.push({
|
|
1948
|
+
tag: 'multicast',
|
|
1949
|
+
attrs: {}
|
|
1950
|
+
})
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
if (pollMessage || messages.eventMessage) {
|
|
1954
|
+
stanza.content.push({
|
|
1955
|
+
tag: 'meta',
|
|
1956
|
+
attrs: messages.eventMessage ? {
|
|
1957
|
+
event_type: 'creation'
|
|
1958
|
+
} : isNewsletter ? {
|
|
1959
|
+
polltype: 'creation',
|
|
1960
|
+
contenttype: pollMessage?.pollContentType === 2 ? 'image' : 'text'
|
|
1961
|
+
} : {
|
|
1962
|
+
polltype: 'creation'
|
|
1963
|
+
}
|
|
1964
|
+
})
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
if (!isNewsletter && buttonType) {
|
|
1968
|
+
const buttonsNode = getButtonArgs(messages)
|
|
1969
|
+
const filteredButtons = getBinaryFilteredButtons(additionalNodes ? additionalNodes : [])
|
|
1970
|
+
|
|
1971
|
+
if (filteredButtons) {
|
|
1972
|
+
stanza.content.push(...additionalNodes)
|
|
1973
|
+
didPushAdditional = true
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
else {
|
|
1977
|
+
stanza.content.push(buttonsNode)
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
if (AI && isPrivate) {
|
|
1982
|
+
const botNode = {
|
|
1983
|
+
tag: 'bot',
|
|
1984
|
+
attrs: {
|
|
1985
|
+
biz_bot: '1'
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
const filteredBizBot = getBinaryFilteredBizBot(additionalNodes ? additionalNodes : [])
|
|
1990
|
+
|
|
1991
|
+
if (filteredBizBot) {
|
|
1992
|
+
stanza.content.push(...additionalNodes)
|
|
1993
|
+
didPushAdditional = true
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
else {
|
|
1997
|
+
stanza.content.push(botNode)
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
|
|
2002
|
+
stanza.content.push(...additionalNodes)
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
|
2006
|
+
|
|
2007
|
+
await sendNode(stanza)
|
|
2008
|
+
|
|
2009
|
+
// Add message to retry cache if enabled
|
|
2010
|
+
if (messageRetryManager && !participant) {
|
|
2011
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message)
|
|
2012
|
+
}
|
|
2013
|
+
}, meId)
|
|
2014
|
+
|
|
2015
|
+
return msgId
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
const getTypeMessage = (msg) => {
|
|
2019
|
+
const message = normalizeMessageContent(msg)
|
|
2020
|
+
if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
|
2021
|
+
return 'poll'
|
|
2022
|
+
}
|
|
2023
|
+
else if (message.reactionMessage) {
|
|
2024
|
+
return 'reaction'
|
|
2025
|
+
}
|
|
2026
|
+
else if (message.eventMessage) {
|
|
2027
|
+
return 'event'
|
|
2028
|
+
}
|
|
2029
|
+
else if (getMediaType(message)) {
|
|
2030
|
+
return 'media'
|
|
2031
|
+
}
|
|
2032
|
+
else {
|
|
2033
|
+
return 'text'
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
const getMediaType = (message) => {
|
|
2038
|
+
if (message.imageMessage) {
|
|
2039
|
+
return 'image'
|
|
2040
|
+
}
|
|
2041
|
+
else if (message.stickerMessage) {
|
|
2042
|
+
return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker'
|
|
2043
|
+
}
|
|
2044
|
+
else if (message.videoMessage) {
|
|
2045
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video'
|
|
2046
|
+
}
|
|
2047
|
+
else if (message.audioMessage) {
|
|
2048
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio'
|
|
2049
|
+
}
|
|
2050
|
+
else if (message.ptvMessage) {
|
|
2051
|
+
return 'ptv'
|
|
2052
|
+
}
|
|
2053
|
+
else if (message.albumMessage) {
|
|
2054
|
+
return 'collection'
|
|
2055
|
+
}
|
|
2056
|
+
else if (message.contactMessage) {
|
|
2057
|
+
return 'vcard'
|
|
2058
|
+
}
|
|
2059
|
+
else if (message.documentMessage) {
|
|
2060
|
+
return 'document'
|
|
2061
|
+
}
|
|
2062
|
+
else if (message.stickerPackMessage) {
|
|
2063
|
+
return 'sticker_pack'
|
|
2064
|
+
}
|
|
2065
|
+
else if (message.contactsArrayMessage) {
|
|
2066
|
+
return 'contact_array'
|
|
2067
|
+
}
|
|
2068
|
+
else if (message.locationMessage) {
|
|
2069
|
+
return 'location'
|
|
2070
|
+
}
|
|
2071
|
+
else if (message.liveLocationMessage) {
|
|
2072
|
+
return 'livelocation'
|
|
2073
|
+
}
|
|
2074
|
+
else if (message.listMessage) {
|
|
2075
|
+
return 'list'
|
|
2076
|
+
}
|
|
2077
|
+
else if (message.listResponseMessage) {
|
|
2078
|
+
return 'list_response'
|
|
2079
|
+
}
|
|
2080
|
+
else if (message.buttonsResponseMessage) {
|
|
2081
|
+
return 'buttons_response'
|
|
2082
|
+
}
|
|
2083
|
+
else if (message.orderMessage) {
|
|
2084
|
+
return 'order'
|
|
2085
|
+
}
|
|
2086
|
+
else if (message.productMessage) {
|
|
2087
|
+
return 'product'
|
|
2088
|
+
}
|
|
2089
|
+
else if (message.interactiveResponseMessage) {
|
|
2090
|
+
return 'native_flow_response'
|
|
2091
|
+
}
|
|
2092
|
+
else if (/https:\/\/wa\.me\/c\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
2093
|
+
return 'cataloglink'
|
|
2094
|
+
}
|
|
2095
|
+
else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
|
|
2096
|
+
return 'productlink'
|
|
2097
|
+
}
|
|
2098
|
+
else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
|
|
2099
|
+
return 'url'
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
const getButtonType = (message) => {
|
|
2104
|
+
if (message.listMessage) {
|
|
2105
|
+
return 'list'
|
|
2106
|
+
}
|
|
2107
|
+
else if (message.buttonsMessage) {
|
|
2108
|
+
return 'buttons'
|
|
2109
|
+
}
|
|
2110
|
+
else if(message.interactiveMessage?.nativeFlowMessage) {
|
|
2111
|
+
return 'native_flow'
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
const getButtonArgs = (message) => {
|
|
2116
|
+
const nativeFlow = message.interactiveMessage?.nativeFlowMessage
|
|
2117
|
+
const firstButtonName = nativeFlow?.buttons?.[0]?.name
|
|
2118
|
+
const nativeFlowSpecials = [
|
|
2119
|
+
'mpm', 'cta_catalog', 'send_location',
|
|
2120
|
+
'call_permission_request', 'wa_payment_transaction_details',
|
|
2121
|
+
'automated_greeting_message_view_catalog'
|
|
2122
|
+
]
|
|
2123
|
+
|
|
2124
|
+
if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
|
|
2125
|
+
return {
|
|
2126
|
+
tag: 'biz',
|
|
2127
|
+
attrs: {
|
|
2128
|
+
native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
} else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
|
|
2132
|
+
// Only works for WhatsApp Original, not WhatsApp Business
|
|
2133
|
+
return {
|
|
2134
|
+
tag: 'biz',
|
|
2135
|
+
attrs: {
|
|
2136
|
+
actual_actors: '2',
|
|
2137
|
+
host_storage: '2',
|
|
2138
|
+
privacy_mode_ts: unixTimestampSeconds().toString()
|
|
2139
|
+
},
|
|
2140
|
+
content: [{
|
|
2141
|
+
tag: 'interactive',
|
|
2142
|
+
attrs: {
|
|
2143
|
+
type: 'native_flow',
|
|
2144
|
+
v: '1'
|
|
2145
|
+
},
|
|
2146
|
+
content: [{
|
|
2147
|
+
tag: 'native_flow',
|
|
2148
|
+
attrs: {
|
|
2149
|
+
v: '2',
|
|
2150
|
+
name: firstButtonName
|
|
2151
|
+
}
|
|
2152
|
+
}]
|
|
2153
|
+
},
|
|
2154
|
+
{
|
|
2155
|
+
tag: 'quality_control',
|
|
2156
|
+
attrs: {
|
|
2157
|
+
source_type: 'third_party'
|
|
2158
|
+
}
|
|
2159
|
+
}]
|
|
2160
|
+
}
|
|
2161
|
+
} else if (nativeFlow || message.buttonsMessage) {
|
|
2162
|
+
// It works for whatsapp original and whatsapp business
|
|
2163
|
+
return {
|
|
2164
|
+
tag: 'biz',
|
|
2165
|
+
attrs: {
|
|
2166
|
+
actual_actors: '2',
|
|
2167
|
+
host_storage: '2',
|
|
2168
|
+
privacy_mode_ts: unixTimestampSeconds().toString()
|
|
2169
|
+
},
|
|
2170
|
+
content: [{
|
|
2171
|
+
tag: 'interactive',
|
|
2172
|
+
attrs: {
|
|
2173
|
+
type: 'native_flow',
|
|
2174
|
+
v: '1'
|
|
2175
|
+
},
|
|
2176
|
+
content: [{
|
|
2177
|
+
tag: 'native_flow',
|
|
2178
|
+
attrs: {
|
|
2179
|
+
v: '9',
|
|
2180
|
+
name: 'mixed'
|
|
2181
|
+
}
|
|
2182
|
+
}]
|
|
2183
|
+
},
|
|
2184
|
+
{
|
|
2185
|
+
tag: 'quality_control',
|
|
2186
|
+
attrs: {
|
|
2187
|
+
source_type: 'third_party'
|
|
2188
|
+
}
|
|
2189
|
+
}]
|
|
2190
|
+
}
|
|
2191
|
+
} else if (message.listMessage) {
|
|
2192
|
+
return {
|
|
2193
|
+
tag: 'biz',
|
|
2194
|
+
attrs: {
|
|
2195
|
+
actual_actors: '2',
|
|
2196
|
+
host_storage: '2',
|
|
2197
|
+
privacy_mode_ts: unixTimestampSeconds().toString()
|
|
2198
|
+
},
|
|
2199
|
+
content: [{
|
|
2200
|
+
tag: 'list',
|
|
2201
|
+
attrs: {
|
|
2202
|
+
v: '2',
|
|
2203
|
+
type: 'product_list'
|
|
2204
|
+
}
|
|
2205
|
+
},
|
|
2206
|
+
{
|
|
2207
|
+
tag: 'quality_control',
|
|
2208
|
+
attrs: {
|
|
2209
|
+
source_type: 'third_party'
|
|
2210
|
+
}
|
|
2211
|
+
}]
|
|
2212
|
+
}
|
|
2213
|
+
} else {
|
|
2214
|
+
return {
|
|
2215
|
+
tag: 'biz',
|
|
2216
|
+
attrs: {
|
|
2217
|
+
actual_actors: '2',
|
|
2218
|
+
host_storage: '2',
|
|
2219
|
+
privacy_mode_ts: unixTimestampSeconds().toString()
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
const getPrivacyTokens = async (jids) => {
|
|
2226
|
+
const t = unixTimestampSeconds().toString()
|
|
2227
|
+
|
|
2228
|
+
const result = await query({
|
|
2229
|
+
tag: 'iq',
|
|
2230
|
+
attrs: {
|
|
2231
|
+
to: S_WHATSAPP_NET,
|
|
2232
|
+
type: 'set',
|
|
2233
|
+
xmlns: 'privacy'
|
|
2234
|
+
},
|
|
2235
|
+
content: [
|
|
2236
|
+
{
|
|
2237
|
+
tag: 'tokens',
|
|
2238
|
+
attrs: {},
|
|
2239
|
+
content: jids.map(jid => ({
|
|
2240
|
+
tag: 'token',
|
|
2241
|
+
attrs: {
|
|
2242
|
+
jid: jidNormalizedUser(jid),
|
|
2243
|
+
t,
|
|
2244
|
+
type: 'trusted_contact'
|
|
2245
|
+
}
|
|
2246
|
+
}))
|
|
2247
|
+
}
|
|
2248
|
+
]
|
|
2249
|
+
})
|
|
2250
|
+
|
|
2251
|
+
return result
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
const getEphemeralGroup = (jid) => {
|
|
2255
|
+
if (!isJidGroup(jid)) throw new TypeError("Jid should originate from a group!")
|
|
2256
|
+
|
|
2257
|
+
return groupQuery(jid, 'get', [{
|
|
2258
|
+
tag: 'query',
|
|
2259
|
+
attrs: {
|
|
2260
|
+
request: 'interactive'
|
|
2261
|
+
}
|
|
2262
|
+
}])
|
|
2263
|
+
.then((groups) => getBinaryNodeChild(groups, 'group'))
|
|
2264
|
+
.then((metadata) => getBinaryNodeChild(metadata, 'ephemeral')?.attrs?.expiration || 0)
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn)
|
|
2268
|
+
|
|
2269
|
+
const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update')
|
|
2270
|
+
|
|
2271
|
+
return {
|
|
2272
|
+
...suki,
|
|
2273
|
+
getPrivacyTokens,
|
|
2274
|
+
assertSessions,
|
|
2275
|
+
profilePictureUrl,
|
|
2276
|
+
relayMessage,
|
|
2277
|
+
sendReceipt,
|
|
2278
|
+
sendReceipts,
|
|
2279
|
+
readMessages,
|
|
2280
|
+
getUSyncDevices,
|
|
2281
|
+
refreshMediaConn,
|
|
2282
|
+
waUploadToServer,
|
|
2283
|
+
getEphemeralGroup,
|
|
2284
|
+
fetchPrivacySettings,
|
|
2285
|
+
messageRetryManager,
|
|
2286
|
+
createParticipantNodes,
|
|
2287
|
+
sendPeerDataOperationMessage,
|
|
2288
|
+
updateMemberLabel,
|
|
2289
|
+
updateMediaMessage: async (message) => {
|
|
2290
|
+
const content = assertMediaContent(message.message)
|
|
2291
|
+
const mediaKey = content.mediaKey
|
|
2292
|
+
const meId = authState.creds.me.id
|
|
2293
|
+
const node = await encryptMediaRetryRequest(message.key, mediaKey, meId)
|
|
2294
|
+
|
|
2295
|
+
let error = undefined
|
|
2296
|
+
|
|
2297
|
+
await Promise.all([
|
|
2298
|
+
sendNode(node),
|
|
2299
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
2300
|
+
const result = update.find(c => c.key.id === message.key.id)
|
|
2301
|
+
|
|
2302
|
+
if (result) {
|
|
2303
|
+
if (result.error) {
|
|
2304
|
+
error = result.error
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
else {
|
|
2308
|
+
try {
|
|
2309
|
+
const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id)
|
|
2310
|
+
|
|
2311
|
+
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
2312
|
+
const resultStr = proto.MediaRetryNotification.ResultType[media.result]
|
|
2313
|
+
|
|
2314
|
+
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
|
2315
|
+
data: media,
|
|
2316
|
+
statusCode: getStatusCodeForMediaRetry(media.result) || 404
|
|
2317
|
+
})
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
content.directPath = media.directPath
|
|
2321
|
+
content.url = getUrlFromDirectPath(content.directPath)
|
|
2322
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
catch (err) {
|
|
2326
|
+
error = err
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
return true
|
|
2331
|
+
}
|
|
2332
|
+
})
|
|
2333
|
+
])
|
|
2334
|
+
|
|
2335
|
+
if (error) {
|
|
2336
|
+
throw error
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }])
|
|
2340
|
+
|
|
2341
|
+
return message
|
|
2342
|
+
},
|
|
2343
|
+
sendStatusMentions: async (content, jids = []) => {
|
|
2344
|
+
const userJid = jidNormalizedUser(authState.creds.me.id)
|
|
2345
|
+
let allUsers = new Set()
|
|
2346
|
+
allUsers.add(userJid)
|
|
2347
|
+
|
|
2348
|
+
for (const id of jids) {
|
|
2349
|
+
const isGroup = isJidGroup(id)
|
|
2350
|
+
const isPrivate = isPnUser(id)
|
|
2351
|
+
|
|
2352
|
+
if (isGroup) {
|
|
2353
|
+
try {
|
|
2354
|
+
const metadata = await cachedGroupMetadata(id) || await groupMetadata(id)
|
|
2355
|
+
const participants = metadata.participants.map(p => jidNormalizedUser(p.id))
|
|
2356
|
+
participants.forEach(jid => allUsers.add(jid))
|
|
2357
|
+
} catch (error) {
|
|
2358
|
+
logger.error(`Error getting metadata for group ${id}: ${error}`)
|
|
2359
|
+
}
|
|
2360
|
+
} else if (isPrivate) {
|
|
2361
|
+
allUsers.add(jidNormalizedUser(id))
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
const uniqueUsers = Array.from(allUsers)
|
|
2366
|
+
const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")
|
|
2367
|
+
|
|
2368
|
+
const isMedia = content.image || content.video || content.audio
|
|
2369
|
+
const isAudio = !!content.audio
|
|
2370
|
+
|
|
2371
|
+
const messageContent = { ...content }
|
|
2372
|
+
|
|
2373
|
+
if (isMedia && !isAudio) {
|
|
2374
|
+
if (messageContent.text) {
|
|
2375
|
+
messageContent.caption = messageContent.text
|
|
2376
|
+
|
|
2377
|
+
delete messageContent.text
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
delete messageContent.ptt
|
|
2381
|
+
delete messageContent.font
|
|
2382
|
+
delete messageContent.backgroundColor
|
|
2383
|
+
delete messageContent.textColor
|
|
2384
|
+
}
|
|
2385
|
+
|
|
2386
|
+
if (isAudio) {
|
|
2387
|
+
delete messageContent.text
|
|
2388
|
+
delete messageContent.caption
|
|
2389
|
+
delete messageContent.font
|
|
2390
|
+
delete messageContent.textColor
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined
|
|
2394
|
+
const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined
|
|
2395
|
+
const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined
|
|
2396
|
+
const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined
|
|
2397
|
+
|
|
2398
|
+
let msg
|
|
2399
|
+
let mediaHandle
|
|
2400
|
+
try {
|
|
2401
|
+
msg = await generateWAMessage(STORIES_JID, messageContent, {
|
|
2402
|
+
logger,
|
|
2403
|
+
userJid,
|
|
2404
|
+
getUrlInfo: text => getUrlInfo(text, {
|
|
2405
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
2406
|
+
fetchOpts: {
|
|
2407
|
+
timeout: 3000,
|
|
2408
|
+
...(httpRequestOptions || {})
|
|
2409
|
+
},
|
|
2410
|
+
logger,
|
|
2411
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
2412
|
+
}),
|
|
2413
|
+
upload: async (encFilePath, opts) => {
|
|
2414
|
+
const up = await waUploadToServer(encFilePath, { ...opts })
|
|
2415
|
+
mediaHandle = up.handle
|
|
2416
|
+
return up
|
|
2417
|
+
},
|
|
2418
|
+
mediaCache: config.mediaCache,
|
|
2419
|
+
options: config.options,
|
|
2420
|
+
font,
|
|
2421
|
+
textColor,
|
|
2422
|
+
backgroundColor,
|
|
2423
|
+
ptt
|
|
2424
|
+
})
|
|
2425
|
+
} catch (error) {
|
|
2426
|
+
logger.error(`Error generating message: ${error}`)
|
|
2427
|
+
throw error
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
await relayMessage(STORIES_JID, msg.message, {
|
|
2431
|
+
messageId: msg.key.id,
|
|
2432
|
+
statusJidList: uniqueUsers,
|
|
2433
|
+
additionalNodes: [
|
|
2434
|
+
{
|
|
2435
|
+
tag: 'meta',
|
|
2436
|
+
attrs: {},
|
|
2437
|
+
content: [
|
|
2438
|
+
{
|
|
2439
|
+
tag: 'mentioned_users',
|
|
2440
|
+
attrs: {},
|
|
2441
|
+
content: jids.map(jid => ({
|
|
2442
|
+
tag: 'to',
|
|
2443
|
+
attrs: { jid: jidNormalizedUser(jid) }
|
|
2444
|
+
}))
|
|
2445
|
+
}]
|
|
2446
|
+
}]
|
|
2447
|
+
})
|
|
2448
|
+
|
|
2449
|
+
for (const id of jids) {
|
|
2450
|
+
try {
|
|
2451
|
+
const normalizedId = jidNormalizedUser(id)
|
|
2452
|
+
const isPrivate = isPnUser(normalizedId)
|
|
2453
|
+
const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage'
|
|
2454
|
+
|
|
2455
|
+
const protocolMessage = {
|
|
2456
|
+
[type]: {
|
|
2457
|
+
message: {
|
|
2458
|
+
protocolMessage: {
|
|
2459
|
+
key: msg.key,
|
|
2460
|
+
type: 25
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
},
|
|
2464
|
+
messageContextInfo: {
|
|
2465
|
+
messageSecret: randomBytes(32)
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
const statusMsg = await generateWAMessageFromContent(normalizedId,
|
|
2470
|
+
protocolMessage,
|
|
2471
|
+
{}
|
|
2472
|
+
)
|
|
2473
|
+
|
|
2474
|
+
await relayMessage(
|
|
2475
|
+
normalizedId,
|
|
2476
|
+
statusMsg.message,
|
|
2477
|
+
{
|
|
2478
|
+
additionalNodes: [{
|
|
2479
|
+
tag: 'meta',
|
|
2480
|
+
attrs: isPrivate ?
|
|
2481
|
+
{ is_status_mention: 'true' } :
|
|
2482
|
+
{ is_group_status_mention: 'true' }
|
|
2483
|
+
}]
|
|
2484
|
+
}
|
|
2485
|
+
)
|
|
2486
|
+
|
|
2487
|
+
await delay(2000)
|
|
2488
|
+
} catch (error) {
|
|
2489
|
+
logger.error(`Error sending to ${id}: ${error}`)
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
return msg
|
|
2494
|
+
},
|
|
2495
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
2496
|
+
const userJid = authState.creds.me.id
|
|
2497
|
+
const additionalAttributes = {}
|
|
2498
|
+
|
|
2499
|
+
if (!options.ephemeralExpiration) {
|
|
2500
|
+
if (isJidGroup(jid)) {
|
|
2501
|
+
const expiration = await getEphemeralGroup(jid)
|
|
2502
|
+
options.ephemeralExpiration = expiration
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
if (typeof content === 'object' &&
|
|
2507
|
+
'disappearingMessagesInChat' in content &&
|
|
2508
|
+
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
|
2509
|
+
isJidGroup(jid)) {
|
|
2510
|
+
|
|
2511
|
+
const { disappearingMessagesInChat } = content
|
|
2512
|
+
|
|
2513
|
+
const value = typeof disappearingMessagesInChat === 'boolean' ?
|
|
2514
|
+
(disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) :
|
|
2515
|
+
disappearingMessagesInChat
|
|
2516
|
+
|
|
2517
|
+
await groupToggleEphemeral(jid, value)
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
else if (typeof content === 'object' && 'album' in content && content.album) {
|
|
2521
|
+
const albumMsg = await prepareAlbumMessageContent(jid, content.album, {
|
|
2522
|
+
suki: {
|
|
2523
|
+
relayMessage,
|
|
2524
|
+
waUploadToServer
|
|
2525
|
+
},
|
|
2526
|
+
userJid: userJid,
|
|
2527
|
+
...options
|
|
2528
|
+
})
|
|
2529
|
+
|
|
2530
|
+
for (const media of albumMsg) {
|
|
2531
|
+
await delay(options.delay || 500)
|
|
2532
|
+
await relayMessage(jid, media.message, { messageId: media.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, AI: options.ai })
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
return albumMsg
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
else {
|
|
2539
|
+
let mediaHandle
|
|
2540
|
+
|
|
2541
|
+
const fullMsg = await generateWAMessage(jid, content, {
|
|
2542
|
+
logger,
|
|
2543
|
+
userJid,
|
|
2544
|
+
getUrlInfo: text => getUrlInfo(text, {
|
|
2545
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
2546
|
+
fetchOpts: {
|
|
2547
|
+
timeout: 3000,
|
|
2548
|
+
...(httpRequestOptions || {})
|
|
2549
|
+
},
|
|
2550
|
+
logger,
|
|
2551
|
+
uploadImage: generateHighQualityLinkPreview
|
|
2552
|
+
? waUploadToServer
|
|
2553
|
+
: undefined
|
|
2554
|
+
}),
|
|
2555
|
+
getProfilePicUrl: profilePictureUrl,
|
|
2556
|
+
getCallLink: createCallLink,
|
|
2557
|
+
upload: async (encFilePath, opts) => {
|
|
2558
|
+
const up = await waUploadToServer(encFilePath, { ...opts, newsletter: isJidNewsletter(jid) })
|
|
2559
|
+
mediaHandle = up.handle
|
|
2560
|
+
return up
|
|
2561
|
+
},
|
|
2562
|
+
mediaCache: config.mediaCache,
|
|
2563
|
+
options: config.options,
|
|
2564
|
+
messageId: generateMessageID(userJid),
|
|
2565
|
+
...options,
|
|
2566
|
+
})
|
|
2567
|
+
|
|
2568
|
+
const isPin = 'pin' in content && !!content.pin
|
|
2569
|
+
const isEdit = 'edit' in content && !!content.edit
|
|
2570
|
+
const isDelete = 'delete' in content && !!content.delete
|
|
2571
|
+
const isKeep = 'keep' in content && !!content.keep && content.keep?.type === 2
|
|
2572
|
+
|
|
2573
|
+
if (isDelete || isKeep) {
|
|
2574
|
+
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
2575
|
+
if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe || isJidNewsletter(jid)) {
|
|
2576
|
+
additionalAttributes.edit = '8'
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
else {
|
|
2580
|
+
additionalAttributes.edit = '7'
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
else if (isEdit) {
|
|
2585
|
+
additionalAttributes.edit = isJidNewsletter(jid) ? '3' : '1'
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
else if (isPin) {
|
|
2589
|
+
additionalAttributes.edit = '2'
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
if (mediaHandle) {
|
|
2593
|
+
additionalAttributes['media_id'] = mediaHandle
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
if ('cachedGroupMetadata' in options) {
|
|
2597
|
+
console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.')
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes: options.additionalNodes, AI: options.ai })
|
|
2601
|
+
|
|
2602
|
+
if (config.emitOwnEvents) {
|
|
2603
|
+
process.nextTick(async () => {
|
|
2604
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'))
|
|
2605
|
+
})
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
return fullMsg
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
module.exports = {
|
|
2615
|
+
makeMessagesSocket
|
|
2616
|
+
}
|
|
2617
|
+
return module.exports;
|
|
2618
|
+
})();
|
|
2619
|
+
for (const key of Object.keys(__kageModule30)) {
|
|
2620
|
+
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule30[key]});
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
// Kage: funciones avanzadas.
|
|
2624
|
+
const __kageModule136 = (() => {
|
|
2625
|
+
const module = { exports: {} }; const exports = module.exports;
|
|
2626
|
+
"use strict";
|
|
2627
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2628
|
+
exports.makeMessagesSocket = void 0;
|
|
2629
|
+
const node_crypto_1 = require("node:crypto");
|
|
2630
|
+
const index_js_1 = require("../../WAProto/index.js");
|
|
2631
|
+
const index_js_2 = require("../Addon/index.js");
|
|
2632
|
+
const index_js_3 = require("../Defaults/index.js");
|
|
2633
|
+
const index_js_4 = require("../Utils/index.js");
|
|
2634
|
+
const index_js_5 = require("../Types/index.js");
|
|
2635
|
+
const link_preview_js_1 = require("../Utils/link-preview.js");
|
|
2636
|
+
const make_mutex_js_1 = require("../Utils/make-mutex.js");
|
|
2637
|
+
const reporting_utils_js_1 = require("../Utils/reporting-utils.js");
|
|
2638
|
+
const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
|
|
2639
|
+
const index_js_6 = require("../WABinary/index.js");
|
|
2640
|
+
const index_js_7 = require("../WAUSync/index.js");
|
|
2641
|
+
const newsletter_js_1 = require("./newsletter.js");
|
|
2642
|
+
const makeMessagesSocket = (config) => {
|
|
2643
|
+
const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
|
|
2644
|
+
const sock = (0, newsletter_js_1.makeNewsletterSocket)(config);
|
|
2645
|
+
const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
|
|
2646
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
2647
|
+
/**
|
|
2648
|
+
* Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
|
|
2649
|
+
* Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
|
|
2650
|
+
* Entries are always removed in `.finally()`, so the set is bounded by concurrency.
|
|
2651
|
+
*/
|
|
2652
|
+
const inFlightTcTokenIssuance = new Set();
|
|
2653
|
+
const userDevicesCache = config.userDevicesCache ||
|
|
2654
|
+
(0, index_js_2.createCache)({
|
|
2655
|
+
ttl: index_js_3.DEFAULT_CACHE_TTLS.USER_DEVICES // 5 minutes
|
|
2656
|
+
});
|
|
2657
|
+
/** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
|
|
2658
|
+
const devicesMutex = (0, make_mutex_js_1.makeMutex)();
|
|
2659
|
+
// Initialize message retry manager if enabled
|
|
2660
|
+
const messageRetryManager = enableRecentMessageCache ? new index_js_4.MessageRetryManager(logger, maxMsgRetryCount) : null;
|
|
2661
|
+
// Prevent race conditions in Signal session encryption by user
|
|
2662
|
+
const encryptionMutex = (0, make_mutex_js_1.makeKeyedMutex)();
|
|
2663
|
+
// Prevent race conditions in media connection refresh
|
|
2664
|
+
const mediaConnMutex = (0, make_mutex_js_1.makeKeyedMutex)();
|
|
2665
|
+
let mediaConn;
|
|
2666
|
+
/** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
|
|
2667
|
+
let mediaHost = index_js_4.DEF_MEDIA_HOST;
|
|
2668
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
2669
|
+
return mediaConnMutex.mutex('media-conn', async () => {
|
|
2670
|
+
const media = await mediaConn;
|
|
2671
|
+
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
2672
|
+
mediaConn = (async () => {
|
|
2673
|
+
const result = await query({
|
|
2674
|
+
tag: 'iq',
|
|
2675
|
+
attrs: {
|
|
2676
|
+
type: 'set',
|
|
2677
|
+
xmlns: 'w:m',
|
|
2678
|
+
to: index_js_6.S_WHATSAPP_NET
|
|
2679
|
+
},
|
|
2680
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
2681
|
+
});
|
|
2682
|
+
const mediaConnNode = (0, index_js_6.getBinaryNodeChild)(result, 'media_conn');
|
|
2683
|
+
// TODO: explore full length of data that whatsapp provides
|
|
2684
|
+
const node = {
|
|
2685
|
+
hosts: (0, index_js_6.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
2686
|
+
hostname: attrs.hostname,
|
|
2687
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
2688
|
+
})),
|
|
2689
|
+
auth: mediaConnNode.attrs.auth,
|
|
2690
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
2691
|
+
fetchDate: new Date()
|
|
2692
|
+
};
|
|
2693
|
+
logger.debug('fetched media conn');
|
|
2694
|
+
if (node.hosts[0]) {
|
|
2695
|
+
mediaHost = node.hosts[0].hostname;
|
|
2696
|
+
}
|
|
2697
|
+
return node;
|
|
2698
|
+
})();
|
|
2699
|
+
}
|
|
2700
|
+
return mediaConn;
|
|
2701
|
+
});
|
|
2702
|
+
};
|
|
2703
|
+
/**
|
|
2704
|
+
* generic send receipt function
|
|
2705
|
+
* used for receipts of phone call, read, delivery etc.
|
|
2706
|
+
* */
|
|
2707
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
2708
|
+
if (!messageIds || messageIds.length === 0) {
|
|
2709
|
+
throw new index_js_2.HttpError('missing ids in receipt');
|
|
2710
|
+
}
|
|
2711
|
+
const node = {
|
|
2712
|
+
tag: 'receipt',
|
|
2713
|
+
attrs: {
|
|
2714
|
+
id: messageIds[0]
|
|
2715
|
+
}
|
|
2716
|
+
};
|
|
2717
|
+
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
2718
|
+
if (isReadReceipt) {
|
|
2719
|
+
node.attrs.t = (0, index_js_4.unixTimestampSeconds)().toString();
|
|
2720
|
+
}
|
|
2721
|
+
if (type === 'sender' && ((0, index_js_6.isPnUser)(jid) || (0, index_js_6.isLidUser)(jid))) {
|
|
2722
|
+
node.attrs.recipient = jid;
|
|
2723
|
+
node.attrs.to = participant;
|
|
2724
|
+
}
|
|
2725
|
+
else {
|
|
2726
|
+
node.attrs.to = jid;
|
|
2727
|
+
if (participant) {
|
|
2728
|
+
node.attrs.participant = participant;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
if (type) {
|
|
2732
|
+
node.attrs.type = type;
|
|
2733
|
+
}
|
|
2734
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
2735
|
+
if (remainingMessageIds.length) {
|
|
2736
|
+
node.content = [
|
|
2737
|
+
{
|
|
2738
|
+
tag: 'list',
|
|
2739
|
+
attrs: {},
|
|
2740
|
+
content: remainingMessageIds.map(id => ({
|
|
2741
|
+
tag: 'item',
|
|
2742
|
+
attrs: { id }
|
|
2743
|
+
}))
|
|
2744
|
+
}
|
|
2745
|
+
];
|
|
2746
|
+
}
|
|
2747
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
|
|
2748
|
+
await sendNode(node);
|
|
2749
|
+
};
|
|
2750
|
+
/** Correctly bulk send receipts to multiple chats, participants */
|
|
2751
|
+
const sendReceipts = async (keys, type) => {
|
|
2752
|
+
const recps = (0, index_js_4.aggregateMessageKeysNotFromMe)(keys);
|
|
2753
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
2754
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
/** Bulk read messages. Keys can be from different chats & participants */
|
|
2758
|
+
const readMessages = async (keys) => {
|
|
2759
|
+
const privacySettings = await fetchPrivacySettings();
|
|
2760
|
+
// based on privacy settings, we have to change the read type
|
|
2761
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
2762
|
+
await sendReceipts(keys, readType);
|
|
2763
|
+
};
|
|
2764
|
+
/** Fetch all the devices we've to send a message to */
|
|
2765
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
2766
|
+
const deviceResults = [];
|
|
2767
|
+
if (!useCache) {
|
|
2768
|
+
logger.debug('not using cache for devices');
|
|
2769
|
+
}
|
|
2770
|
+
const toFetch = [];
|
|
2771
|
+
const jidsWithUser = jids
|
|
2772
|
+
.map(jid => {
|
|
2773
|
+
const decoded = (0, index_js_6.jidDecode)(jid);
|
|
2774
|
+
const user = decoded?.user;
|
|
2775
|
+
const device = decoded?.device;
|
|
2776
|
+
const isExplicitDevice = typeof device === 'number' && device >= 0;
|
|
2777
|
+
if (isExplicitDevice && user) {
|
|
2778
|
+
deviceResults.push({
|
|
2779
|
+
user,
|
|
2780
|
+
device,
|
|
2781
|
+
jid
|
|
2782
|
+
});
|
|
2783
|
+
return null;
|
|
2784
|
+
}
|
|
2785
|
+
jid = (0, index_js_6.jidNormalizedUser)(jid);
|
|
2786
|
+
return { jid, user };
|
|
2787
|
+
})
|
|
2788
|
+
.filter(jid => jid !== null);
|
|
2789
|
+
let mgetDevices;
|
|
2790
|
+
if (useCache && userDevicesCache.mget) {
|
|
2791
|
+
const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
|
|
2792
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
2793
|
+
}
|
|
2794
|
+
for (const { jid, user } of jidsWithUser) {
|
|
2795
|
+
if (useCache) {
|
|
2796
|
+
const devices = mgetDevices?.[user] ||
|
|
2797
|
+
(userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
|
|
2798
|
+
if (devices) {
|
|
2799
|
+
const devicesWithJid = devices.map(d => ({
|
|
2800
|
+
...d,
|
|
2801
|
+
jid: (0, index_js_6.jidEncode)(d.user, d.server, d.device)
|
|
2802
|
+
}));
|
|
2803
|
+
deviceResults.push(...devicesWithJid);
|
|
2804
|
+
logger.trace({ user }, 'using cache for devices');
|
|
2805
|
+
}
|
|
2806
|
+
else {
|
|
2807
|
+
toFetch.push(jid);
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
else {
|
|
2811
|
+
toFetch.push(jid);
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
if (!toFetch.length) {
|
|
2815
|
+
return deviceResults;
|
|
2816
|
+
}
|
|
2817
|
+
const requestedLidUsers = new Set();
|
|
2818
|
+
for (const jid of toFetch) {
|
|
2819
|
+
if ((0, index_js_6.isLidUser)(jid) || (0, index_js_6.isHostedLidUser)(jid)) {
|
|
2820
|
+
const user = (0, index_js_6.jidDecode)(jid)?.user;
|
|
2821
|
+
if (user)
|
|
2822
|
+
requestedLidUsers.add(user);
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
const query = new index_js_7.USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
|
|
2826
|
+
for (const jid of toFetch) {
|
|
2827
|
+
query.withUser(new index_js_7.USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
|
|
2828
|
+
}
|
|
2829
|
+
const result = await sock.executeUSyncQuery(query);
|
|
2830
|
+
if (result) {
|
|
2831
|
+
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
2832
|
+
const lidResults = result.list.filter(a => !!a.lid);
|
|
2833
|
+
if (lidResults.length > 0) {
|
|
2834
|
+
logger.trace('Storing LID maps from device call');
|
|
2835
|
+
await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
|
|
2836
|
+
// Force-refresh sessions for newly mapped LIDs to align identity addressing
|
|
2837
|
+
try {
|
|
2838
|
+
const lids = lidResults.map(a => a.lid);
|
|
2839
|
+
if (lids.length) {
|
|
2840
|
+
await assertSessions(lids, true);
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
catch (e) {
|
|
2844
|
+
logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
const extracted = (0, index_js_4.extractDeviceJids)(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
|
|
2848
|
+
const deviceMap = {};
|
|
2849
|
+
for (const item of extracted) {
|
|
2850
|
+
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
2851
|
+
deviceMap[item.user]?.push(item);
|
|
2852
|
+
}
|
|
2853
|
+
// Process each user's devices as a group for bulk LID migration
|
|
2854
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
2855
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
2856
|
+
// Process all devices for this user
|
|
2857
|
+
for (const item of userDevices) {
|
|
2858
|
+
const finalJid = isLidUser
|
|
2859
|
+
? (0, index_js_6.jidEncode)(user, item.server, item.device)
|
|
2860
|
+
: (0, index_js_6.jidEncode)(item.user, item.server, item.device);
|
|
2861
|
+
deviceResults.push({
|
|
2862
|
+
...item,
|
|
2863
|
+
jid: finalJid
|
|
2864
|
+
});
|
|
2865
|
+
logger.debug({
|
|
2866
|
+
user: item.user,
|
|
2867
|
+
device: item.device,
|
|
2868
|
+
finalJid,
|
|
2869
|
+
usedLid: isLidUser
|
|
2870
|
+
}, 'Processed device with LID priority');
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
await devicesMutex.mutex(async () => {
|
|
2874
|
+
if (userDevicesCache.mset) {
|
|
2875
|
+
// if the cache supports mset, we can set all devices in one go
|
|
2876
|
+
await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
|
|
2877
|
+
}
|
|
2878
|
+
else {
|
|
2879
|
+
for (const key in deviceMap) {
|
|
2880
|
+
if (deviceMap[key])
|
|
2881
|
+
await userDevicesCache.set(key, deviceMap[key]);
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
});
|
|
2885
|
+
const userDeviceUpdates = {};
|
|
2886
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
2887
|
+
if (devices && devices.length > 0) {
|
|
2888
|
+
userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
2892
|
+
try {
|
|
2893
|
+
await authState.keys.set({ 'device-list': userDeviceUpdates });
|
|
2894
|
+
logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
|
|
2895
|
+
}
|
|
2896
|
+
catch (error) {
|
|
2897
|
+
logger.warn({ error }, 'failed to store user device lists');
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
return deviceResults;
|
|
2902
|
+
};
|
|
2903
|
+
/**
|
|
2904
|
+
* Update Member Label
|
|
2905
|
+
*/
|
|
2906
|
+
const updateMemberLabel = (jid, memberLabel) => {
|
|
2907
|
+
return relayMessage(jid, {
|
|
2908
|
+
protocolMessage: {
|
|
2909
|
+
type: index_js_1.proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
|
|
2910
|
+
memberLabel: {
|
|
2911
|
+
label: memberLabel?.slice(0, 30),
|
|
2912
|
+
labelTimestamp: (0, index_js_4.unixTimestampSeconds)()
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
}, {
|
|
2916
|
+
additionalNodes: [
|
|
2917
|
+
{
|
|
2918
|
+
tag: 'meta',
|
|
2919
|
+
attrs: {
|
|
2920
|
+
tag_reason: 'user_update',
|
|
2921
|
+
appdata: 'member_tag'
|
|
2922
|
+
},
|
|
2923
|
+
content: undefined
|
|
2924
|
+
}
|
|
2925
|
+
]
|
|
2926
|
+
});
|
|
2927
|
+
};
|
|
2928
|
+
const assertSessions = async (jids, force) => {
|
|
2929
|
+
let didFetchNewSession = false;
|
|
2930
|
+
const uniqueJids = [...new Set(jids)];
|
|
2931
|
+
const jidsRequiringFetch = [];
|
|
2932
|
+
logger.debug({ jids }, 'assertSessions call with jids');
|
|
2933
|
+
for (const jid of uniqueJids) {
|
|
2934
|
+
if (!force) {
|
|
2935
|
+
const sessionValidation = await signalRepository.validateSession(jid);
|
|
2936
|
+
if (sessionValidation.exists) {
|
|
2937
|
+
continue;
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
jidsRequiringFetch.push(jid);
|
|
2941
|
+
}
|
|
2942
|
+
if (jidsRequiringFetch.length) {
|
|
2943
|
+
// LID if mapped, otherwise original
|
|
2944
|
+
const wireJids = [
|
|
2945
|
+
...jidsRequiringFetch.filter(jid => !!(0, index_js_6.isLidUser)(jid) || !!(0, index_js_6.isHostedLidUser)(jid)),
|
|
2946
|
+
...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!(0, index_js_6.isPnUser)(jid) || !!(0, index_js_6.isHostedPnUser)(jid)))) || []).map(a => a.lid)
|
|
2947
|
+
];
|
|
2948
|
+
logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
|
|
2949
|
+
const result = await query({
|
|
2950
|
+
tag: 'iq',
|
|
2951
|
+
attrs: {
|
|
2952
|
+
xmlns: 'encrypt',
|
|
2953
|
+
type: 'get',
|
|
2954
|
+
to: index_js_6.S_WHATSAPP_NET
|
|
2955
|
+
},
|
|
2956
|
+
content: [
|
|
2957
|
+
{
|
|
2958
|
+
tag: 'key',
|
|
2959
|
+
attrs: {},
|
|
2960
|
+
content: wireJids.map(jid => {
|
|
2961
|
+
const attrs = { jid };
|
|
2962
|
+
if (force)
|
|
2963
|
+
attrs.reason = 'identity';
|
|
2964
|
+
return { tag: 'user', attrs };
|
|
2965
|
+
})
|
|
2966
|
+
}
|
|
2967
|
+
]
|
|
2968
|
+
});
|
|
2969
|
+
await (0, index_js_4.parseAndInjectE2ESessions)(result, signalRepository);
|
|
2970
|
+
didFetchNewSession = true;
|
|
2971
|
+
}
|
|
2972
|
+
return didFetchNewSession;
|
|
2973
|
+
};
|
|
2974
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
2975
|
+
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
|
2976
|
+
if (!authState.creds.me?.id) {
|
|
2977
|
+
throw new index_js_2.HttpError('Not authenticated');
|
|
2978
|
+
}
|
|
2979
|
+
const protocolMessage = {
|
|
2980
|
+
protocolMessage: {
|
|
2981
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
2982
|
+
type: index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
|
|
2983
|
+
}
|
|
2984
|
+
};
|
|
2985
|
+
const meJid = (0, index_js_6.jidNormalizedUser)(authState.creds.me.id);
|
|
2986
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
2987
|
+
additionalAttributes: {
|
|
2988
|
+
category: 'peer',
|
|
2989
|
+
push_priority: 'high_force'
|
|
2990
|
+
},
|
|
2991
|
+
additionalNodes: [
|
|
2992
|
+
{
|
|
2993
|
+
tag: 'meta',
|
|
2994
|
+
attrs: { appdata: 'default' }
|
|
2995
|
+
}
|
|
2996
|
+
]
|
|
2997
|
+
});
|
|
2998
|
+
return msgId;
|
|
2999
|
+
};
|
|
3000
|
+
const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
|
|
3001
|
+
if (!recipientJids.length) {
|
|
3002
|
+
return { nodes: [], shouldIncludeDeviceIdentity: false };
|
|
3003
|
+
}
|
|
3004
|
+
const patched = await patchMessageBeforeSending(message, recipientJids);
|
|
3005
|
+
const patchedMessages = Array.isArray(patched)
|
|
3006
|
+
? patched
|
|
3007
|
+
: recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
|
|
3008
|
+
let shouldIncludeDeviceIdentity = false;
|
|
3009
|
+
const meId = authState.creds.me.id;
|
|
3010
|
+
const meLid = authState.creds.me?.lid;
|
|
3011
|
+
const meLidUser = meLid ? (0, index_js_6.jidDecode)(meLid)?.user : null;
|
|
3012
|
+
const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
3013
|
+
try {
|
|
3014
|
+
if (!jid)
|
|
3015
|
+
return null;
|
|
3016
|
+
let msgToEncrypt = patchedMessage;
|
|
3017
|
+
if (dsmMessage) {
|
|
3018
|
+
const { user: targetUser } = (0, index_js_6.jidDecode)(jid);
|
|
3019
|
+
const { user: ownPnUser } = (0, index_js_6.jidDecode)(meId);
|
|
3020
|
+
const ownLidUser = meLidUser;
|
|
3021
|
+
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
|
|
3022
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
3023
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
3024
|
+
msgToEncrypt = dsmMessage;
|
|
3025
|
+
logger.debug({ jid, targetUser }, 'Using DSM for own device');
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
const bytes = (0, index_js_4.encodeWAMessage)(msgToEncrypt);
|
|
3029
|
+
const mutexKey = jid;
|
|
3030
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
3031
|
+
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
|
|
3032
|
+
if (type === 'pkmsg') {
|
|
3033
|
+
shouldIncludeDeviceIdentity = true;
|
|
3034
|
+
}
|
|
3035
|
+
return {
|
|
3036
|
+
tag: 'to',
|
|
3037
|
+
attrs: { jid },
|
|
3038
|
+
content: [
|
|
3039
|
+
{
|
|
3040
|
+
tag: 'enc',
|
|
3041
|
+
attrs: { v: '2', type, ...(extraAttrs || {}) },
|
|
3042
|
+
content: ciphertext
|
|
3043
|
+
}
|
|
3044
|
+
]
|
|
3045
|
+
};
|
|
3046
|
+
});
|
|
3047
|
+
return node;
|
|
3048
|
+
}
|
|
3049
|
+
catch (err) {
|
|
3050
|
+
logger.error({ jid, err }, 'Failed to encrypt for recipient');
|
|
3051
|
+
return null;
|
|
3052
|
+
}
|
|
3053
|
+
});
|
|
3054
|
+
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
|
|
3055
|
+
if (recipientJids.length > 0 && nodes.length === 0) {
|
|
3056
|
+
throw new index_js_2.HttpError('All encryptions failed', { statusCode: 500 });
|
|
3057
|
+
}
|
|
3058
|
+
return { nodes, shouldIncludeDeviceIdentity };
|
|
3059
|
+
};
|
|
3060
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
|
|
3061
|
+
const meId = (0, index_js_4.assertMeId)(authState.creds);
|
|
3062
|
+
const meLid = authState.creds.me?.lid;
|
|
3063
|
+
const isRetryResend = Boolean(participant?.jid);
|
|
3064
|
+
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
3065
|
+
const statusJid = 'status@broadcast';
|
|
3066
|
+
const { user, server } = (0, index_js_6.jidDecode)(jid);
|
|
3067
|
+
const isGroup = server === 'g.us';
|
|
3068
|
+
const isStatus = jid === statusJid;
|
|
3069
|
+
const isLid = server === 'lid';
|
|
3070
|
+
const isNewsletter = server === 'newsletter';
|
|
3071
|
+
const isGroupOrStatus = isGroup || isStatus;
|
|
3072
|
+
const finalJid = jid;
|
|
3073
|
+
msgId = msgId || (0, index_js_4.generateMessageIDV2)(meId);
|
|
3074
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
3075
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
3076
|
+
const participants = [];
|
|
3077
|
+
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
3078
|
+
const binaryNodeContent = [];
|
|
3079
|
+
const devices = [];
|
|
3080
|
+
let reportingMessage;
|
|
3081
|
+
const meMsg = {
|
|
3082
|
+
deviceSentMessage: {
|
|
3083
|
+
destinationJid,
|
|
3084
|
+
message
|
|
3085
|
+
},
|
|
3086
|
+
messageContextInfo: message.messageContextInfo
|
|
3087
|
+
};
|
|
3088
|
+
const extraAttrs = {};
|
|
3089
|
+
if (participant) {
|
|
3090
|
+
if (!isGroup && !isStatus) {
|
|
3091
|
+
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
|
|
3092
|
+
}
|
|
3093
|
+
const { user, device } = (0, index_js_6.jidDecode)(participant.jid);
|
|
3094
|
+
devices.push({
|
|
3095
|
+
user,
|
|
3096
|
+
device,
|
|
3097
|
+
jid: participant.jid
|
|
3098
|
+
});
|
|
3099
|
+
}
|
|
3100
|
+
await authState.keys.transaction(async () => {
|
|
3101
|
+
// Kage: actualización de compatibilidad.
|
|
3102
|
+
const innerMessage = (0, index_js_4.normalizeMessageContent)(message);
|
|
3103
|
+
const mediaType = getMediaType(innerMessage);
|
|
3104
|
+
if (mediaType) {
|
|
3105
|
+
extraAttrs['mediatype'] = mediaType;
|
|
3106
|
+
}
|
|
3107
|
+
if (isNewsletter) {
|
|
3108
|
+
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
|
|
3109
|
+
const bytes = (0, index_js_4.encodeNewsletterMessage)(patched);
|
|
3110
|
+
// Kage: actualización de compatibilidad.
|
|
3111
|
+
if (additionalNodes && additionalNodes.length > 0) {
|
|
3112
|
+
;
|
|
3113
|
+
binaryNodeContent.push(...additionalNodes);
|
|
3114
|
+
}
|
|
3115
|
+
binaryNodeContent.push({
|
|
3116
|
+
tag: 'plaintext',
|
|
3117
|
+
attrs: extraAttrs, // Kage: actualización de compatibilidad.
|
|
3118
|
+
content: bytes
|
|
3119
|
+
});
|
|
3120
|
+
const stanza = {
|
|
3121
|
+
tag: 'message',
|
|
3122
|
+
attrs: {
|
|
3123
|
+
to: jid,
|
|
3124
|
+
id: msgId,
|
|
3125
|
+
type: getMessageType(innerMessage),
|
|
3126
|
+
...(additionalAttributes || {})
|
|
3127
|
+
},
|
|
3128
|
+
content: binaryNodeContent
|
|
3129
|
+
};
|
|
3130
|
+
logger.debug({ msgId }, `sending newsletter message to ${jid}`);
|
|
3131
|
+
await sendNode(stanza);
|
|
3132
|
+
return;
|
|
3133
|
+
}
|
|
3134
|
+
// Kage: actualización de compatibilidad.
|
|
3135
|
+
const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
|
|
3136
|
+
// Kage: actualización de compatibilidad.
|
|
3137
|
+
const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
|
|
3138
|
+
const isPollUpdate = innerMessage?.pollUpdateMessage;
|
|
3139
|
+
if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
|
|
3140
|
+
const metaAttrs = {};
|
|
3141
|
+
if (isNeedMetaAttrs) {
|
|
3142
|
+
metaAttrs.content_type = 'add_on';
|
|
3143
|
+
}
|
|
3144
|
+
if (isPollUpdate && !isGroupStatus) {
|
|
3145
|
+
metaAttrs.polltype = 'vote';
|
|
3146
|
+
}
|
|
3147
|
+
if (isGroupStatus) {
|
|
3148
|
+
metaAttrs.is_group_status = 'true';
|
|
3149
|
+
}
|
|
3150
|
+
binaryNodeContent.push({
|
|
3151
|
+
tag: 'meta',
|
|
3152
|
+
attrs: metaAttrs,
|
|
3153
|
+
content: undefined
|
|
3154
|
+
});
|
|
3155
|
+
}
|
|
3156
|
+
if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
|
|
3157
|
+
extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
|
|
3158
|
+
}
|
|
3159
|
+
// Kage: actualización de compatibilidad.
|
|
3160
|
+
if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
|
|
3161
|
+
extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
|
|
3162
|
+
}
|
|
3163
|
+
if (isGroupOrStatus && !isRetryResend) {
|
|
3164
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
3165
|
+
(async () => {
|
|
3166
|
+
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?
|
|
3167
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
3168
|
+
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
|
|
3169
|
+
}
|
|
3170
|
+
else if (!isStatus) {
|
|
3171
|
+
groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
3172
|
+
}
|
|
3173
|
+
return groupData;
|
|
3174
|
+
})(),
|
|
3175
|
+
(async () => {
|
|
3176
|
+
if (!participant && !isStatus) {
|
|
3177
|
+
// what if sender memory is less accurate than the cached metadata
|
|
3178
|
+
// on participant change in group, we should do sender memory manipulation
|
|
3179
|
+
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?
|
|
3180
|
+
return result[jid] || {};
|
|
3181
|
+
}
|
|
3182
|
+
return {};
|
|
3183
|
+
})()
|
|
3184
|
+
]);
|
|
3185
|
+
const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
|
|
3186
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
3187
|
+
additionalAttributes = {
|
|
3188
|
+
...additionalAttributes,
|
|
3189
|
+
expiration: groupData.ephemeralDuration.toString()
|
|
3190
|
+
};
|
|
3191
|
+
}
|
|
3192
|
+
if (isStatus && statusJidList) {
|
|
3193
|
+
participantsList.push(...statusJidList);
|
|
3194
|
+
}
|
|
3195
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
|
|
3196
|
+
devices.push(...additionalDevices);
|
|
3197
|
+
if (isGroup) {
|
|
3198
|
+
additionalAttributes = {
|
|
3199
|
+
...additionalAttributes,
|
|
3200
|
+
addressing_mode: groupData?.addressingMode || 'lid'
|
|
3201
|
+
};
|
|
3202
|
+
}
|
|
3203
|
+
const patched = await patchMessageBeforeSending(message);
|
|
3204
|
+
if (Array.isArray(patched)) {
|
|
3205
|
+
throw new index_js_2.HttpError('Per-jid patching is not supported in groups');
|
|
3206
|
+
}
|
|
3207
|
+
const bytes = (0, index_js_4.encodeWAMessage)(patched);
|
|
3208
|
+
reportingMessage = patched;
|
|
3209
|
+
const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
|
|
3210
|
+
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
|
|
3211
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
3212
|
+
group: destinationJid,
|
|
3213
|
+
data: bytes,
|
|
3214
|
+
meId: groupSenderIdentity
|
|
3215
|
+
});
|
|
3216
|
+
const senderKeyRecipients = [];
|
|
3217
|
+
for (const device of devices) {
|
|
3218
|
+
const deviceJid = device.jid;
|
|
3219
|
+
const hasKey = !!senderKeyMap[deviceJid];
|
|
3220
|
+
if ((!hasKey || !!participant) &&
|
|
3221
|
+
!(0, index_js_6.isHostedLidUser)(deviceJid) &&
|
|
3222
|
+
!(0, index_js_6.isHostedPnUser)(deviceJid) &&
|
|
3223
|
+
device.device !== 99) {
|
|
3224
|
+
//todo: revamp all this logic
|
|
3225
|
+
// 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
|
|
3226
|
+
senderKeyRecipients.push(deviceJid);
|
|
3227
|
+
senderKeyMap[deviceJid] = true;
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
if (senderKeyRecipients.length) {
|
|
3231
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
|
|
3232
|
+
const senderKeyMsg = {
|
|
3233
|
+
senderKeyDistributionMessage: {
|
|
3234
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
3235
|
+
groupId: destinationJid
|
|
3236
|
+
}
|
|
3237
|
+
};
|
|
3238
|
+
const senderKeySessionTargets = senderKeyRecipients;
|
|
3239
|
+
await assertSessions(senderKeySessionTargets);
|
|
3240
|
+
const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
|
|
3241
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
3242
|
+
participants.push(...result.nodes);
|
|
3243
|
+
}
|
|
3244
|
+
binaryNodeContent.push({
|
|
3245
|
+
tag: 'enc',
|
|
3246
|
+
attrs: { v: '2', type: 'skmsg', ...extraAttrs },
|
|
3247
|
+
content: ciphertext
|
|
3248
|
+
});
|
|
3249
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
|
|
3250
|
+
}
|
|
3251
|
+
else {
|
|
3252
|
+
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
3253
|
+
// TODO: investigate if this is true
|
|
3254
|
+
let ownId = meId;
|
|
3255
|
+
if (isLid && meLid) {
|
|
3256
|
+
ownId = meLid;
|
|
3257
|
+
logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
|
|
3258
|
+
}
|
|
3259
|
+
else {
|
|
3260
|
+
logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
|
|
3261
|
+
}
|
|
3262
|
+
const { user: ownUser } = (0, index_js_6.jidDecode)(ownId);
|
|
3263
|
+
if (!participant) {
|
|
3264
|
+
const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
|
|
3265
|
+
reportingMessage = Array.isArray(patchedForReporting)
|
|
3266
|
+
? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
|
|
3267
|
+
: patchedForReporting;
|
|
3268
|
+
}
|
|
3269
|
+
if (!isRetryResend) {
|
|
3270
|
+
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
3271
|
+
devices.push({
|
|
3272
|
+
user,
|
|
3273
|
+
device: 0,
|
|
3274
|
+
jid: (0, index_js_6.jidEncode)(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
|
|
3275
|
+
});
|
|
3276
|
+
if (user !== ownUser) {
|
|
3277
|
+
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
3278
|
+
const ownUserForAddressing = isLid && meLid ? (0, index_js_6.jidDecode)(meLid).user : (0, index_js_6.jidDecode)(meId).user;
|
|
3279
|
+
devices.push({
|
|
3280
|
+
user: ownUserForAddressing,
|
|
3281
|
+
device: 0,
|
|
3282
|
+
jid: (0, index_js_6.jidEncode)(ownUserForAddressing, ownUserServer, 0)
|
|
3283
|
+
});
|
|
3284
|
+
}
|
|
3285
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
3286
|
+
// Clear placeholders and enumerate actual devices
|
|
3287
|
+
devices.length = 0;
|
|
3288
|
+
// Use conversation-appropriate sender identity
|
|
3289
|
+
const senderIdentity = isLid && meLid
|
|
3290
|
+
? (0, index_js_6.jidEncode)((0, index_js_6.jidDecode)(meLid)?.user, 'lid', undefined)
|
|
3291
|
+
: (0, index_js_6.jidEncode)((0, index_js_6.jidDecode)(meId)?.user, 's.whatsapp.net', undefined);
|
|
3292
|
+
// Enumerate devices for sender and target with consistent addressing
|
|
3293
|
+
const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
|
|
3294
|
+
devices.push(...sessionDevices);
|
|
3295
|
+
logger.debug({
|
|
3296
|
+
deviceCount: devices.length,
|
|
3297
|
+
devices: devices.map(d => `${d.user}:${d.device}@${(0, index_js_6.jidDecode)(d.jid)?.server}`)
|
|
3298
|
+
}, 'Device enumeration complete with unified addressing');
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
const allRecipients = [];
|
|
3302
|
+
const meRecipients = [];
|
|
3303
|
+
const otherRecipients = [];
|
|
3304
|
+
const { user: mePnUser } = (0, index_js_6.jidDecode)(meId);
|
|
3305
|
+
const { user: meLidUser } = meLid ? (0, index_js_6.jidDecode)(meLid) : { user: null };
|
|
3306
|
+
for (const { user, jid } of devices) {
|
|
3307
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
3308
|
+
if (isExactSenderDevice) {
|
|
3309
|
+
logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
|
|
3310
|
+
continue;
|
|
3311
|
+
}
|
|
3312
|
+
// Check if this is our device (could match either PN or LID user)
|
|
3313
|
+
const isMe = user === mePnUser || user === meLidUser;
|
|
3314
|
+
if (isMe) {
|
|
3315
|
+
meRecipients.push(jid);
|
|
3316
|
+
}
|
|
3317
|
+
else {
|
|
3318
|
+
otherRecipients.push(jid);
|
|
3319
|
+
}
|
|
3320
|
+
allRecipients.push(jid);
|
|
3321
|
+
}
|
|
3322
|
+
await assertSessions(allRecipients);
|
|
3323
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
3324
|
+
// For own devices: use DSM if available (1:1 chats only)
|
|
3325
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
3326
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
|
|
3327
|
+
]);
|
|
3328
|
+
participants.push(...meNodes);
|
|
3329
|
+
participants.push(...otherNodes);
|
|
3330
|
+
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
3331
|
+
extraAttrs['phash'] = (0, index_js_4.generateParticipantHashV2)([...meRecipients, ...otherRecipients]);
|
|
3332
|
+
}
|
|
3333
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
3334
|
+
}
|
|
3335
|
+
if (isRetryResend) {
|
|
3336
|
+
const isParticipantLid = (0, index_js_6.isLidUser)(participant.jid);
|
|
3337
|
+
const isMe = (0, index_js_6.areJidsSameUser)(participant.jid, isParticipantLid ? meLid : meId);
|
|
3338
|
+
let messageToSend = message;
|
|
3339
|
+
if (isGroupOrStatus) {
|
|
3340
|
+
let groupSenderIdentity;
|
|
3341
|
+
if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
|
|
3342
|
+
groupSenderIdentity = meLid;
|
|
3343
|
+
}
|
|
3344
|
+
else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
|
|
3345
|
+
groupSenderIdentity = meId;
|
|
3346
|
+
}
|
|
3347
|
+
if (groupSenderIdentity) {
|
|
3348
|
+
try {
|
|
3349
|
+
const skdm = await signalRepository.getSenderKeyDistributionMessage({
|
|
3350
|
+
group: destinationJid,
|
|
3351
|
+
meId: groupSenderIdentity
|
|
3352
|
+
});
|
|
3353
|
+
messageToSend = {
|
|
3354
|
+
...message,
|
|
3355
|
+
senderKeyDistributionMessage: {
|
|
3356
|
+
groupId: destinationJid,
|
|
3357
|
+
axolotlSenderKeyDistributionMessage: skdm
|
|
3358
|
+
}
|
|
3359
|
+
};
|
|
3360
|
+
}
|
|
3361
|
+
catch (err) {
|
|
3362
|
+
logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
|
|
3363
|
+
}
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
const encodedMessageToSend = isMe
|
|
3367
|
+
? (0, index_js_4.encodeWAMessage)({
|
|
3368
|
+
deviceSentMessage: {
|
|
3369
|
+
destinationJid,
|
|
3370
|
+
message: messageToSend
|
|
3371
|
+
}
|
|
3372
|
+
})
|
|
3373
|
+
: (0, index_js_4.encodeWAMessage)(messageToSend);
|
|
3374
|
+
const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
|
|
3375
|
+
data: encodedMessageToSend,
|
|
3376
|
+
jid: participant.jid
|
|
3377
|
+
});
|
|
3378
|
+
binaryNodeContent.push({
|
|
3379
|
+
tag: 'enc',
|
|
3380
|
+
attrs: {
|
|
3381
|
+
v: '2',
|
|
3382
|
+
type,
|
|
3383
|
+
count: (participant.count || 0).toString()
|
|
3384
|
+
},
|
|
3385
|
+
content: encryptedContent
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
if (participants.length) {
|
|
3389
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
3390
|
+
const peerNode = participants[0]?.content?.[0];
|
|
3391
|
+
if (peerNode) {
|
|
3392
|
+
binaryNodeContent.push(peerNode); // push only enc
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
else {
|
|
3396
|
+
binaryNodeContent.push({
|
|
3397
|
+
tag: 'participants',
|
|
3398
|
+
attrs: {},
|
|
3399
|
+
content: participants
|
|
3400
|
+
});
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
const stanza = {
|
|
3404
|
+
tag: 'message',
|
|
3405
|
+
attrs: {
|
|
3406
|
+
id: msgId,
|
|
3407
|
+
to: destinationJid,
|
|
3408
|
+
type: getMessageType(innerMessage),
|
|
3409
|
+
...(additionalAttributes || {})
|
|
3410
|
+
},
|
|
3411
|
+
content: binaryNodeContent
|
|
3412
|
+
};
|
|
3413
|
+
// if the participant to send to is explicitly specified (generally retry recp)
|
|
3414
|
+
// ensure the message is only sent to that person
|
|
3415
|
+
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
3416
|
+
if (participant) {
|
|
3417
|
+
if ((0, index_js_6.isJidGroup)(destinationJid)) {
|
|
3418
|
+
stanza.attrs.to = destinationJid;
|
|
3419
|
+
stanza.attrs.participant = participant.jid;
|
|
3420
|
+
}
|
|
3421
|
+
else if ((0, index_js_6.areJidsSameUser)(participant.jid, meId)) {
|
|
3422
|
+
stanza.attrs.to = participant.jid;
|
|
3423
|
+
stanza.attrs.recipient = destinationJid;
|
|
3424
|
+
}
|
|
3425
|
+
else {
|
|
3426
|
+
stanza.attrs.to = participant.jid;
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3429
|
+
else {
|
|
3430
|
+
stanza.attrs.to = destinationJid;
|
|
3431
|
+
}
|
|
3432
|
+
if (shouldIncludeDeviceIdentity) {
|
|
3433
|
+
;
|
|
3434
|
+
stanza.content.push({
|
|
3435
|
+
tag: 'device-identity',
|
|
3436
|
+
attrs: {},
|
|
3437
|
+
content: (0, index_js_4.encodeSignedDeviceIdentity)(authState.creds.account, true)
|
|
3438
|
+
});
|
|
3439
|
+
logger.debug({ jid }, 'adding device identity');
|
|
3440
|
+
}
|
|
3441
|
+
if (!isNewsletter &&
|
|
3442
|
+
!isRetryResend &&
|
|
3443
|
+
reportingMessage?.messageContextInfo?.messageSecret &&
|
|
3444
|
+
(0, reporting_utils_js_1.shouldIncludeReportingToken)(reportingMessage)) {
|
|
3445
|
+
try {
|
|
3446
|
+
const encoded = (0, index_js_4.encodeWAMessage)(reportingMessage);
|
|
3447
|
+
const reportingKey = {
|
|
3448
|
+
id: msgId,
|
|
3449
|
+
fromMe: true,
|
|
3450
|
+
remoteJid: destinationJid,
|
|
3451
|
+
participant: participant?.jid
|
|
3452
|
+
};
|
|
3453
|
+
const reportingNode = await (0, reporting_utils_js_1.getMessageReportingToken)(encoded, reportingMessage, reportingKey);
|
|
3454
|
+
if (reportingNode) {
|
|
3455
|
+
;
|
|
3456
|
+
stanza.content.push(reportingNode);
|
|
3457
|
+
logger.trace({ jid }, 'added reporting token to message');
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
catch (error) {
|
|
3461
|
+
logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
// WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
|
|
3465
|
+
const isPeerMessage = additionalAttributes?.['category'] === 'peer';
|
|
3466
|
+
const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
|
|
3467
|
+
// Resolve destination to LID for tctoken storage — matches Signal session key pattern
|
|
3468
|
+
const tcTokenJid = is1on1Send ? await (0, tc_token_utils_js_1.resolveTcTokenJid)(destinationJid, getLIDForPN) : destinationJid;
|
|
3469
|
+
const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
|
|
3470
|
+
const existingTokenEntry = contactTcTokenData[tcTokenJid];
|
|
3471
|
+
let tcTokenBuffer = existingTokenEntry?.token;
|
|
3472
|
+
// Treat expired tokens the same as missing — clear from cache
|
|
3473
|
+
if (tcTokenBuffer?.length && (0, tc_token_utils_js_1.isTcTokenExpired)(existingTokenEntry?.timestamp)) {
|
|
3474
|
+
logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
|
|
3475
|
+
tcTokenBuffer = undefined;
|
|
3476
|
+
// Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
|
|
3477
|
+
const cleared = existingTokenEntry?.senderTimestamp !== undefined
|
|
3478
|
+
? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
|
|
3479
|
+
: null;
|
|
3480
|
+
try {
|
|
3481
|
+
await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
|
|
3482
|
+
}
|
|
3483
|
+
catch (err) {
|
|
3484
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
|
|
3488
|
+
;
|
|
3489
|
+
stanza.content.push({
|
|
3490
|
+
tag: 'tctoken',
|
|
3491
|
+
attrs: {},
|
|
3492
|
+
content: tcTokenBuffer
|
|
3493
|
+
});
|
|
3494
|
+
}
|
|
3495
|
+
let alreadyHasBizNode = false;
|
|
3496
|
+
if (additionalNodes && additionalNodes.length > 0) {
|
|
3497
|
+
;
|
|
3498
|
+
stanza.content.push(...additionalNodes);
|
|
3499
|
+
alreadyHasBizNode = !addBizAttributes &&
|
|
3500
|
+
additionalNodes.some(node => node.tag === 'biz');
|
|
3501
|
+
}
|
|
3502
|
+
// Kage: actualización de compatibilidad.
|
|
3503
|
+
if ((!alreadyHasBizNode && (0, index_js_4.shouldIncludeBizBinaryNode)(innerMessage)) || addBizAttributes) {
|
|
3504
|
+
const bizNode = (0, index_js_6.getBizBinaryNode)(innerMessage);
|
|
3505
|
+
stanza.content.push(bizNode);
|
|
3506
|
+
}
|
|
3507
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`);
|
|
3508
|
+
await sendNode(stanza);
|
|
3509
|
+
// Fire-and-forget: issue our token to the contact AFTER message send.
|
|
3510
|
+
// WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
|
|
3511
|
+
const isProtocolMsg = !!innerMessage?.protocolMessage;
|
|
3512
|
+
const isBotOrPSA = destinationJid === index_js_6.PSA_WID || (0, index_js_6.isJidBot)(destinationJid) || (0, index_js_6.isJidMetaAI)(destinationJid);
|
|
3513
|
+
if (is1on1Send &&
|
|
3514
|
+
!isProtocolMsg &&
|
|
3515
|
+
!isBotOrPSA &&
|
|
3516
|
+
(0, tc_token_utils_js_1.shouldSendNewTcToken)(existingTokenEntry?.senderTimestamp) &&
|
|
3517
|
+
!inFlightTcTokenIssuance.has(tcTokenJid)) {
|
|
3518
|
+
inFlightTcTokenIssuance.add(tcTokenJid);
|
|
3519
|
+
const issueTimestamp = (0, index_js_4.unixTimestampSeconds)();
|
|
3520
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
3521
|
+
(0, tc_token_utils_js_1.resolveIssuanceJid)(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
|
|
3522
|
+
.then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
|
|
3523
|
+
.then(async (result) => {
|
|
3524
|
+
await (0, tc_token_utils_js_1.storeTcTokensFromIqResult)({
|
|
3525
|
+
result,
|
|
3526
|
+
fallbackJid: tcTokenJid,
|
|
3527
|
+
keys: authState.keys,
|
|
3528
|
+
getLIDForPN
|
|
3529
|
+
});
|
|
3530
|
+
const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
|
|
3531
|
+
const currentEntry = currentData[tcTokenJid];
|
|
3532
|
+
const indexWrite = await (0, tc_token_utils_js_1.buildMergedTcTokenIndexWrite)(authState.keys, [tcTokenJid]);
|
|
3533
|
+
await authState.keys.set({
|
|
3534
|
+
tctoken: {
|
|
3535
|
+
[tcTokenJid]: {
|
|
3536
|
+
token: Buffer.alloc(0),
|
|
3537
|
+
...currentEntry,
|
|
3538
|
+
senderTimestamp: issueTimestamp
|
|
3539
|
+
},
|
|
3540
|
+
...indexWrite
|
|
3541
|
+
}
|
|
3542
|
+
});
|
|
3543
|
+
})
|
|
3544
|
+
.catch(err => {
|
|
3545
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
|
|
3546
|
+
})
|
|
3547
|
+
.finally(() => {
|
|
3548
|
+
inFlightTcTokenIssuance.delete(tcTokenJid);
|
|
3549
|
+
});
|
|
3550
|
+
}
|
|
3551
|
+
// Add message to retry cache if enabled
|
|
3552
|
+
if (messageRetryManager && !participant) {
|
|
3553
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
3554
|
+
}
|
|
3555
|
+
}, meId);
|
|
3556
|
+
return msgId;
|
|
3557
|
+
};
|
|
3558
|
+
const getMessageType = (message) => {
|
|
3559
|
+
if (!message)
|
|
3560
|
+
return 'text';
|
|
3561
|
+
if (message.reactionMessage || message.encReactionMessage) {
|
|
3562
|
+
return 'reaction';
|
|
3563
|
+
}
|
|
3564
|
+
if (message.pollCreationMessage ||
|
|
3565
|
+
message.pollCreationMessageV2 ||
|
|
3566
|
+
message.pollCreationMessageV3 ||
|
|
3567
|
+
message.pollCreationMessageV5 ||
|
|
3568
|
+
message.pollCreationMessageV6 ||
|
|
3569
|
+
message.pollUpdateMessage) {
|
|
3570
|
+
return 'poll';
|
|
3571
|
+
}
|
|
3572
|
+
if (message.eventMessage) {
|
|
3573
|
+
return 'event';
|
|
3574
|
+
}
|
|
3575
|
+
if (getMediaType(message) !== '') {
|
|
3576
|
+
return 'media';
|
|
3577
|
+
}
|
|
3578
|
+
return 'text';
|
|
3579
|
+
};
|
|
3580
|
+
const getMediaType = (message) => {
|
|
3581
|
+
if (message.imageMessage) {
|
|
3582
|
+
return 'image';
|
|
3583
|
+
}
|
|
3584
|
+
else if (message.videoMessage) {
|
|
3585
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video';
|
|
3586
|
+
}
|
|
3587
|
+
else if (message.stickerMessage) {
|
|
3588
|
+
return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
|
|
3589
|
+
}
|
|
3590
|
+
else if (message.audioMessage) {
|
|
3591
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio';
|
|
3592
|
+
}
|
|
3593
|
+
else if (message.albumMessage) {
|
|
3594
|
+
return 'collection';
|
|
3595
|
+
}
|
|
3596
|
+
else if (message.contactMessage) {
|
|
3597
|
+
return 'vcard';
|
|
3598
|
+
}
|
|
3599
|
+
else if (message.documentMessage) {
|
|
3600
|
+
return 'document';
|
|
3601
|
+
}
|
|
3602
|
+
else if (message.contactsArrayMessage) {
|
|
3603
|
+
return 'contact_array';
|
|
3604
|
+
}
|
|
3605
|
+
else if (message.liveLocationMessage) {
|
|
3606
|
+
return 'livelocation';
|
|
3607
|
+
}
|
|
3608
|
+
else if (message.stickerPackMessage) {
|
|
3609
|
+
return 'sticker_pack';
|
|
3610
|
+
}
|
|
3611
|
+
else if (message.listMessage) {
|
|
3612
|
+
return 'list';
|
|
3613
|
+
}
|
|
3614
|
+
else if (message.listResponseMessage) {
|
|
3615
|
+
return 'list_response';
|
|
3616
|
+
}
|
|
3617
|
+
else if (message.buttonsResponseMessage) {
|
|
3618
|
+
return 'buttons_response';
|
|
3619
|
+
}
|
|
3620
|
+
else if (message.orderMessage) {
|
|
3621
|
+
return 'order';
|
|
3622
|
+
}
|
|
3623
|
+
else if (message.productMessage) {
|
|
3624
|
+
return 'product';
|
|
3625
|
+
}
|
|
3626
|
+
else if (message.interactiveResponseMessage) {
|
|
3627
|
+
return 'native_flow_response';
|
|
3628
|
+
}
|
|
3629
|
+
else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
|
|
3630
|
+
return 'url';
|
|
3631
|
+
}
|
|
3632
|
+
// Kage: nota de compatibilidad.
|
|
3633
|
+
else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
|
|
3634
|
+
return 'cataloglink';
|
|
3635
|
+
}
|
|
3636
|
+
else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
|
|
3637
|
+
return 'productlink';
|
|
3638
|
+
}
|
|
3639
|
+
return '';
|
|
3640
|
+
};
|
|
3641
|
+
const issuePrivacyTokens = async (jids, timestamp) => {
|
|
3642
|
+
const t = (timestamp ?? (0, index_js_4.unixTimestampSeconds)()).toString();
|
|
3643
|
+
const result = await query({
|
|
3644
|
+
tag: 'iq',
|
|
3645
|
+
attrs: {
|
|
3646
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
3647
|
+
type: 'set',
|
|
3648
|
+
xmlns: 'privacy'
|
|
3649
|
+
},
|
|
3650
|
+
content: [
|
|
3651
|
+
{
|
|
3652
|
+
tag: 'tokens',
|
|
3653
|
+
attrs: {},
|
|
3654
|
+
content: jids.map(jid => ({
|
|
3655
|
+
tag: 'token',
|
|
3656
|
+
attrs: {
|
|
3657
|
+
jid: (0, index_js_6.jidNormalizedUser)(jid),
|
|
3658
|
+
t,
|
|
3659
|
+
type: 'trusted_contact'
|
|
3660
|
+
}
|
|
3661
|
+
}))
|
|
3662
|
+
}
|
|
3663
|
+
]
|
|
3664
|
+
});
|
|
3665
|
+
return result;
|
|
3666
|
+
};
|
|
3667
|
+
const waUploadToServer = (0, index_js_4.getWAUploadToServer)(config, refreshMediaConn);
|
|
3668
|
+
const waitForMsgMediaUpdate = (0, index_js_4.bindWaitForEvent)(ev, 'messages.media-update');
|
|
3669
|
+
registerSocketEndHandler(() => {
|
|
3670
|
+
if (!config.userDevicesCache && userDevicesCache.close) {
|
|
3671
|
+
userDevicesCache.close();
|
|
3672
|
+
}
|
|
3673
|
+
mediaConn = undefined;
|
|
3674
|
+
if (messageRetryManager) {
|
|
3675
|
+
messageRetryManager.flushAll();
|
|
3676
|
+
}
|
|
3677
|
+
});
|
|
3678
|
+
return {
|
|
3679
|
+
...sock,
|
|
3680
|
+
userDevicesCache,
|
|
3681
|
+
devicesMutex,
|
|
3682
|
+
issuePrivacyTokens,
|
|
3683
|
+
assertSessions,
|
|
3684
|
+
relayMessage,
|
|
3685
|
+
sendReceipt,
|
|
3686
|
+
sendReceipts,
|
|
3687
|
+
readMessages,
|
|
3688
|
+
refreshMediaConn,
|
|
3689
|
+
// Function (not getter) so the spread in chats.ts preserves the live closure binding.
|
|
3690
|
+
getMediaHost: () => mediaHost,
|
|
3691
|
+
waUploadToServer,
|
|
3692
|
+
fetchPrivacySettings,
|
|
3693
|
+
sendPeerDataOperationMessage,
|
|
3694
|
+
createParticipantNodes,
|
|
3695
|
+
getUSyncDevices,
|
|
3696
|
+
messageRetryManager,
|
|
3697
|
+
updateMemberLabel,
|
|
3698
|
+
updateMediaMessage: async (message) => {
|
|
3699
|
+
const content = (0, index_js_4.assertMediaContent)(message.message);
|
|
3700
|
+
const mediaKey = content.mediaKey;
|
|
3701
|
+
const meId = authState.creds.me.id;
|
|
3702
|
+
const node = (0, index_js_4.encryptMediaRetryRequest)(message.key, mediaKey, meId);
|
|
3703
|
+
let error = undefined;
|
|
3704
|
+
await Promise.all([
|
|
3705
|
+
sendNode(node),
|
|
3706
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
3707
|
+
const result = update.find(c => c.key.id === message.key.id);
|
|
3708
|
+
if (result) {
|
|
3709
|
+
if (result.error) {
|
|
3710
|
+
error = result.error;
|
|
3711
|
+
}
|
|
3712
|
+
else {
|
|
3713
|
+
try {
|
|
3714
|
+
const media = (0, index_js_4.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
|
|
3715
|
+
if (media.result !== index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
3716
|
+
const resultStr = index_js_1.proto.MediaRetryNotification.ResultType[media.result];
|
|
3717
|
+
throw new index_js_2.HttpError(`Media re-upload failed by device (${resultStr})`, {
|
|
3718
|
+
data: media,
|
|
3719
|
+
statusCode: (0, index_js_4.getStatusCodeForMediaRetry)(media.result) || 404
|
|
3720
|
+
});
|
|
3721
|
+
}
|
|
3722
|
+
content.directPath = media.directPath;
|
|
3723
|
+
content.url = (0, index_js_4.getUrlFromDirectPath)(content.directPath, mediaHost);
|
|
3724
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
|
|
3725
|
+
}
|
|
3726
|
+
catch (err) {
|
|
3727
|
+
error = err;
|
|
3728
|
+
}
|
|
3729
|
+
}
|
|
3730
|
+
return true;
|
|
3731
|
+
}
|
|
3732
|
+
})
|
|
3733
|
+
]);
|
|
3734
|
+
if (error) {
|
|
3735
|
+
throw error;
|
|
3736
|
+
}
|
|
3737
|
+
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
|
|
3738
|
+
return message;
|
|
3739
|
+
},
|
|
3740
|
+
// Kage: actualización de compatibilidad.
|
|
3741
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
3742
|
+
var _a;
|
|
3743
|
+
const userJid = authState.creds.me.id;
|
|
3744
|
+
// Kage: actualización de compatibilidad.
|
|
3745
|
+
if (Array.isArray(jid)) {
|
|
3746
|
+
const { delayMs = 1500 } = options;
|
|
3747
|
+
const allUsers = new Set();
|
|
3748
|
+
const fullMsg = await (0, index_js_4.generateWAMessage)('status@broadcast', content, {
|
|
3749
|
+
logger,
|
|
3750
|
+
userJid,
|
|
3751
|
+
upload: waUploadToServer,
|
|
3752
|
+
mediaCache: config.mediaCache,
|
|
3753
|
+
options: config.options,
|
|
3754
|
+
...options,
|
|
3755
|
+
messageId: (0, index_js_4.generateMessageIDV2)(userJid)
|
|
3756
|
+
});
|
|
3757
|
+
for (const id of jid) {
|
|
3758
|
+
if ((0, index_js_6.isJidGroup)(id)) {
|
|
3759
|
+
try {
|
|
3760
|
+
const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
|
|
3761
|
+
for (const participant of groupData.participants) {
|
|
3762
|
+
if (allUsers.has(participant.id))
|
|
3763
|
+
continue;
|
|
3764
|
+
allUsers.add(participant.id);
|
|
3765
|
+
}
|
|
3766
|
+
}
|
|
3767
|
+
catch (error) {
|
|
3768
|
+
logger.error(`Error getting metadata group from ${id}: ${error}`);
|
|
3769
|
+
}
|
|
3770
|
+
}
|
|
3771
|
+
else if (!allUsers.has(id)) {
|
|
3772
|
+
allUsers.add(id);
|
|
3773
|
+
}
|
|
3774
|
+
}
|
|
3775
|
+
await relayMessage('status@broadcast', fullMsg.message, {
|
|
3776
|
+
messageId: fullMsg.key.id,
|
|
3777
|
+
statusJidList: Array.from(allUsers),
|
|
3778
|
+
additionalNodes: [
|
|
3779
|
+
{
|
|
3780
|
+
tag: 'meta',
|
|
3781
|
+
attrs: {},
|
|
3782
|
+
content: [
|
|
3783
|
+
{
|
|
3784
|
+
tag: 'mentioned_users',
|
|
3785
|
+
attrs: {},
|
|
3786
|
+
content: jid.map(id => ({
|
|
3787
|
+
tag: 'to',
|
|
3788
|
+
attrs: { jid: id },
|
|
3789
|
+
content: undefined
|
|
3790
|
+
}))
|
|
3791
|
+
}
|
|
3792
|
+
]
|
|
3793
|
+
}
|
|
3794
|
+
]
|
|
3795
|
+
});
|
|
3796
|
+
if (config.emitOwnEvents) {
|
|
3797
|
+
process.nextTick(async () => {
|
|
3798
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
3799
|
+
});
|
|
3800
|
+
}
|
|
3801
|
+
for (const id of jid) {
|
|
3802
|
+
const isGroup = (0, index_js_6.isJidGroup)(id);
|
|
3803
|
+
const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
|
|
3804
|
+
const mentionMsg = (0, index_js_4.generateWAMessageFromContent)(id, {
|
|
3805
|
+
messageContextInfo: {
|
|
3806
|
+
messageSecret: (0, node_crypto_1.randomBytes)(32)
|
|
3807
|
+
},
|
|
3808
|
+
[sendType]: {
|
|
3809
|
+
message: {
|
|
3810
|
+
protocolMessage: {
|
|
3811
|
+
key: fullMsg.key,
|
|
3812
|
+
type: 25
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
}
|
|
3816
|
+
}, {
|
|
3817
|
+
userJid
|
|
3818
|
+
});
|
|
3819
|
+
await relayMessage(id, mentionMsg.message, {
|
|
3820
|
+
additionalNodes: [
|
|
3821
|
+
{
|
|
3822
|
+
tag: 'meta',
|
|
3823
|
+
attrs: isGroup ?
|
|
3824
|
+
{ is_group_status_mention: 'true' } :
|
|
3825
|
+
{ is_status_mention: 'true' },
|
|
3826
|
+
content: undefined
|
|
3827
|
+
}
|
|
3828
|
+
]
|
|
3829
|
+
});
|
|
3830
|
+
if (config.emitOwnEvents) {
|
|
3831
|
+
process.nextTick(async () => {
|
|
3832
|
+
await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
|
|
3833
|
+
});
|
|
3834
|
+
}
|
|
3835
|
+
await (0, index_js_4.delay)(delayMs);
|
|
3836
|
+
}
|
|
3837
|
+
return fullMsg;
|
|
3838
|
+
}
|
|
3839
|
+
else if ('disappearingMessagesInChat' in content && (0, index_js_6.isJidGroup)(jid)) {
|
|
3840
|
+
const { disappearingMessagesInChat } = content;
|
|
3841
|
+
const value = typeof disappearingMessagesInChat === 'boolean'
|
|
3842
|
+
? disappearingMessagesInChat
|
|
3843
|
+
? index_js_3.WA_DEFAULT_EPHEMERAL
|
|
3844
|
+
: 0
|
|
3845
|
+
: disappearingMessagesInChat;
|
|
3846
|
+
await groupToggleEphemeral(jid, value);
|
|
3847
|
+
}
|
|
3848
|
+
else {
|
|
3849
|
+
const fullMsg = await (0, index_js_4.generateWAMessage)(jid, content, {
|
|
3850
|
+
logger,
|
|
3851
|
+
userJid,
|
|
3852
|
+
getUrlInfo: text => (0, link_preview_js_1.getUrlInfo)(text, {
|
|
3853
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
3854
|
+
fetchOpts: {
|
|
3855
|
+
timeout: 3000,
|
|
3856
|
+
...(httpRequestOptions || {})
|
|
3857
|
+
},
|
|
3858
|
+
logger,
|
|
3859
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
3860
|
+
}),
|
|
3861
|
+
//TODO: CACHE
|
|
3862
|
+
getProfilePicUrl: sock.profilePictureUrl,
|
|
3863
|
+
getCallLink: sock.createCallLink,
|
|
3864
|
+
upload: waUploadToServer,
|
|
3865
|
+
mediaCache: config.mediaCache,
|
|
3866
|
+
options: config.options,
|
|
3867
|
+
...options,
|
|
3868
|
+
messageId: (0, index_js_4.generateMessageIDV2)(userJid)
|
|
3869
|
+
});
|
|
3870
|
+
const isNewsletter = (0, index_js_6.isJidNewsletter)(jid);
|
|
3871
|
+
const isEventMsg = 'event' in content && !!content.event;
|
|
3872
|
+
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
3873
|
+
const isEditMsg = 'edit' in content && !!content.edit;
|
|
3874
|
+
const isPinMsg = 'pin' in content && !!content.pin;
|
|
3875
|
+
const isKeepMsg = 'keep' in content && !!content.keep;
|
|
3876
|
+
const isPollMsg = 'poll' in content && !!content.poll;
|
|
3877
|
+
const isQuizMsg = 'poll' in content && !!content.poll.pollType;
|
|
3878
|
+
const isAiMsg = 'ai' in content && !!content.ai;
|
|
3879
|
+
const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
|
|
3880
|
+
const additionalAttributes = options.additionalAttributes || {};
|
|
3881
|
+
const additionalNodes = options.additionalNodes || [];
|
|
3882
|
+
// required for delete
|
|
3883
|
+
if (isDeleteMsg || isKeepMsg) {
|
|
3884
|
+
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
3885
|
+
if ((0, index_js_6.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) {
|
|
3886
|
+
additionalAttributes.edit = '8';
|
|
3887
|
+
}
|
|
3888
|
+
else {
|
|
3889
|
+
additionalAttributes.edit = '7';
|
|
3890
|
+
}
|
|
3891
|
+
}
|
|
3892
|
+
else if (isEditMsg) {
|
|
3893
|
+
additionalAttributes.edit = isNewsletter ? '3' : '1';
|
|
3894
|
+
}
|
|
3895
|
+
else if (isPinMsg) {
|
|
3896
|
+
additionalAttributes.edit = '2';
|
|
3897
|
+
}
|
|
3898
|
+
else if (isPollMsg) {
|
|
3899
|
+
if (!isNewsletter && isQuizMsg) {
|
|
3900
|
+
throw new index_js_2.HttpError('Quiz are only allowed for newsletter', { statusCode: 400 });
|
|
3901
|
+
}
|
|
3902
|
+
additionalNodes.push({
|
|
3903
|
+
tag: 'meta',
|
|
3904
|
+
attrs: {
|
|
3905
|
+
// Kage: nota de compatibilidad.
|
|
3906
|
+
polltype: isQuizMsg ? 'quiz_creation' : 'creation',
|
|
3907
|
+
contenttype: isPollMsg && isNewsletter ? 'text' : undefined
|
|
3908
|
+
},
|
|
3909
|
+
content: undefined
|
|
3910
|
+
});
|
|
3911
|
+
}
|
|
3912
|
+
else if (isEventMsg) {
|
|
3913
|
+
additionalNodes.push({
|
|
3914
|
+
tag: 'meta',
|
|
3915
|
+
attrs: {
|
|
3916
|
+
event_type: 'creation'
|
|
3917
|
+
},
|
|
3918
|
+
content: undefined
|
|
3919
|
+
});
|
|
3920
|
+
}
|
|
3921
|
+
// Kage: actualización de compatibilidad.
|
|
3922
|
+
else if (isAiMsg) {
|
|
3923
|
+
if (!((0, index_js_6.isPnUser)(jid) || (0, index_js_6.isLidUser)(jid))) {
|
|
3924
|
+
throw new index_js_2.HttpError('AI icon on message are only allowed in private chat', { statusCode: 400 });
|
|
3925
|
+
}
|
|
3926
|
+
if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
|
|
3927
|
+
fullMsg.message.messageContextInfo.supportPayload = index_js_3.BIZ_BOT_SUPPORT_PAYLOAD;
|
|
3928
|
+
}
|
|
3929
|
+
;
|
|
3930
|
+
additionalNodes.push({
|
|
3931
|
+
tag: 'bot',
|
|
3932
|
+
attrs: {
|
|
3933
|
+
biz_bot: '1'
|
|
3934
|
+
},
|
|
3935
|
+
content: undefined
|
|
3936
|
+
});
|
|
3937
|
+
delete content.ai;
|
|
3938
|
+
}
|
|
3939
|
+
await relayMessage(jid, fullMsg.message, {
|
|
3940
|
+
messageId: fullMsg.key.id,
|
|
3941
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
3942
|
+
addBizAttributes: isNeedBizAttrs,
|
|
3943
|
+
statusJidList: options.statusJidList,
|
|
3944
|
+
additionalAttributes,
|
|
3945
|
+
additionalNodes
|
|
3946
|
+
});
|
|
3947
|
+
if (config.emitOwnEvents) {
|
|
3948
|
+
process.nextTick(async () => {
|
|
3949
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
3950
|
+
});
|
|
3951
|
+
}
|
|
3952
|
+
// Kage: actualización de compatibilidad.
|
|
3953
|
+
// Kage: nota de compatibilidad.
|
|
3954
|
+
if ('album' in content) {
|
|
3955
|
+
const { delayMs = 1500 } = options;
|
|
3956
|
+
for (const albumMedia of content.album) {
|
|
3957
|
+
const albumMsg = await (0, index_js_4.generateWAMessage)(jid, albumMedia, {
|
|
3958
|
+
logger,
|
|
3959
|
+
userJid,
|
|
3960
|
+
upload: waUploadToServer,
|
|
3961
|
+
mediaCache: config.mediaCache,
|
|
3962
|
+
options: config.options,
|
|
3963
|
+
...options,
|
|
3964
|
+
messageId: (0, index_js_4.generateMessageIDV2)(userJid)
|
|
3965
|
+
});
|
|
3966
|
+
if (!(0, index_js_4.hasValidAlbumMedia)((0, index_js_4.normalizeMessageContent)(albumMsg.message))) {
|
|
3967
|
+
throw new index_js_2.HttpError('Invalid message type for album', { statusCode: 400 });
|
|
3968
|
+
}
|
|
3969
|
+
(_a = albumMsg.message).messageContextInfo || (_a.messageContextInfo = {});
|
|
3970
|
+
albumMsg.message.messageContextInfo.messageAssociation = {
|
|
3971
|
+
parentMessageKey: fullMsg.key,
|
|
3972
|
+
associationType: index_js_5.AssociationType.MEDIA_ALBUM
|
|
3973
|
+
};
|
|
3974
|
+
await relayMessage(jid, albumMsg.message, {
|
|
3975
|
+
messageId: albumMsg.key.id,
|
|
3976
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
3977
|
+
addBizAttributes: isNeedBizAttrs,
|
|
3978
|
+
statusJidList: options.statusJidList,
|
|
3979
|
+
additionalAttributes,
|
|
3980
|
+
additionalNodes
|
|
3981
|
+
});
|
|
3982
|
+
if (config.emitOwnEvents) {
|
|
3983
|
+
process.nextTick(async () => {
|
|
3984
|
+
await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
|
|
3985
|
+
});
|
|
3986
|
+
}
|
|
3987
|
+
await (0, index_js_4.delay)(delayMs);
|
|
3988
|
+
}
|
|
3989
|
+
}
|
|
3990
|
+
return fullMsg;
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
};
|
|
3994
|
+
};
|
|
3995
|
+
exports.makeMessagesSocket = makeMessagesSocket;
|
|
3996
|
+
|
|
3997
|
+
return module.exports;
|
|
3998
|
+
})();
|
|
3999
|
+
for (const key of Object.keys(__kageModule136)) {
|
|
4000
|
+
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule136[key]});
|
|
4001
|
+
}
|
|
4002
|
+
Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule136, configurable:true});
|