@sanzoffc/baileys 3.0.1 → 3.0.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.
Files changed (114) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +769 -233
  3. package/WAProto/index.js +65801 -141371
  4. package/lib/Defaults/index.js +117 -114
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -14
  10. package/lib/Signal/Group/group-session-builder.js +10 -42
  11. package/lib/Signal/Group/group_cipher.js +75 -87
  12. package/lib/Signal/Group/index.js +13 -57
  13. package/lib/Signal/Group/keyhelper.js +17 -52
  14. package/lib/Signal/Group/sender-chain-key.js +27 -33
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -63
  16. package/lib/Signal/Group/sender-key-message.js +65 -66
  17. package/lib/Signal/Group/sender-key-name.js +45 -44
  18. package/lib/Signal/Group/sender-key-record.js +39 -49
  19. package/lib/Signal/Group/sender-key-state.js +80 -93
  20. package/lib/Signal/Group/sender-message-key.js +27 -28
  21. package/lib/Signal/libsignal.js +313 -163
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -18
  24. package/lib/Socket/Client/types.js +12 -12
  25. package/lib/Socket/Client/websocket.js +51 -71
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +359 -242
  28. package/lib/Socket/chats.js +858 -945
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +304 -324
  31. package/lib/Socket/index.js +15 -9
  32. package/lib/Socket/messages-recv.js +1105 -1046
  33. package/lib/Socket/messages-send.js +615 -389
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +224 -227
  36. package/lib/Socket/socket.js +795 -621
  37. package/lib/Store/index.js +6 -8
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +286 -435
  40. package/lib/Store/make-ordered-dictionary.js +77 -79
  41. package/lib/Store/object-repository.js +24 -26
  42. package/lib/Types/Auth.js +3 -2
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -2
  45. package/lib/Types/Chat.js +9 -4
  46. package/lib/Types/Contact.js +3 -2
  47. package/lib/Types/Events.js +3 -2
  48. package/lib/Types/GroupMetadata.js +3 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +12 -7
  52. package/lib/Types/Newsletter.js +32 -17
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -2
  55. package/lib/Types/Signal.js +3 -2
  56. package/lib/Types/Socket.js +4 -2
  57. package/lib/Types/State.js +11 -2
  58. package/lib/Types/USync.js +3 -2
  59. package/lib/Types/index.js +27 -41
  60. package/lib/Utils/auth-utils.js +211 -191
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +21 -31
  63. package/lib/Utils/business.js +213 -214
  64. package/lib/Utils/chat-utils.js +711 -689
  65. package/lib/Utils/crypto.js +112 -175
  66. package/lib/Utils/decode-wa-message.js +254 -194
  67. package/lib/Utils/event-buffer.js +510 -500
  68. package/lib/Utils/generics.js +318 -430
  69. package/lib/Utils/history.js +83 -90
  70. package/lib/Utils/index.js +21 -35
  71. package/lib/Utils/link-preview.js +71 -116
  72. package/lib/Utils/logger.js +5 -7
  73. package/lib/Utils/lt-hash.js +40 -46
  74. package/lib/Utils/make-mutex.js +34 -41
  75. package/lib/Utils/message-retry-manager.js +33 -48
  76. package/lib/Utils/messages-media.js +573 -825
  77. package/lib/Utils/messages.js +349 -489
  78. package/lib/Utils/noise-handler.js +138 -144
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +321 -384
  81. package/lib/Utils/signal.js +147 -139
  82. package/lib/Utils/use-multi-file-auth-state.js +95 -109
  83. package/lib/Utils/validate-connection.js +183 -212
  84. package/lib/WABinary/constants.js +1298 -1298
  85. package/lib/WABinary/decode.js +231 -256
  86. package/lib/WABinary/encode.js +207 -239
  87. package/lib/WABinary/generic-utils.js +119 -40
  88. package/lib/WABinary/index.js +7 -21
  89. package/lib/WABinary/jid-utils.js +87 -79
  90. package/lib/WABinary/types.js +3 -2
  91. package/lib/WAM/BinaryInfo.js +10 -12
  92. package/lib/WAM/constants.js +22851 -15348
  93. package/lib/WAM/encode.js +135 -136
  94. package/lib/WAM/index.js +5 -19
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -30
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +49 -53
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -28
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -39
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +26 -20
  101. package/lib/WAUSync/Protocols/index.js +6 -20
  102. package/lib/WAUSync/USyncQuery.js +86 -85
  103. package/lib/WAUSync/USyncUser.js +23 -25
  104. package/lib/WAUSync/index.js +5 -19
  105. package/lib/index.js +18 -49
  106. package/package.json +65 -78
  107. package/README.MD +0 -1295
  108. package/WAProto/GenerateStatics.sh +0 -4
  109. package/WAProto/p.html +0 -1
  110. package/engine-requirements.js +0 -10
  111. package/lib/Defaults/wileys-version.json +0 -3
  112. package/lib/Signal/Group/queue-job.js +0 -57
  113. package/lib/Socket/usync.js +0 -70
  114. package/lib/Utils/wileys-event-stream.js +0 -63
@@ -1,404 +1,341 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
- exports.decryptPollVote = decryptPollVote;
5
- const WAProto_1 = require("../../WAProto");
6
- const Types_1 = require("../Types");
7
- const messages_1 = require("../Utils/messages");
8
- const WABinary_1 = require("../WABinary");
9
- const crypto_1 = require("./crypto");
10
- const generics_1 = require("./generics");
11
- const history_1 = require("./history");
1
+ //=======================================================//
2
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, jidDecode, jidEncode, jidNormalizedUser } from "../WABinary/index.js";
3
+ import { getContentType, normalizeMessageContent } from "../Utils/messages.js";
4
+ import { downloadAndProcessHistorySyncNotification } from "./history.js";
5
+ import { WAMessageStubType } from "../Types/index.js";
6
+ import { aesDecryptGCM, hmacSign } from "./crypto.js";
7
+ import { proto } from "../../WAProto/index.js";
8
+ import { toNumber } from "./generics.js";
9
+ //=======================================================//
12
10
  const REAL_MSG_STUB_TYPES = new Set([
13
- Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
- Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
- Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
- Types_1.WAMessageStubType.CALL_MISSED_VOICE
11
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
12
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
13
+ WAMessageStubType.CALL_MISSED_VIDEO,
14
+ WAMessageStubType.CALL_MISSED_VOICE
17
15
  ]);
18
- const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
- Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
- ]);
21
- /** Cleans a received message to further processing */
22
- const cleanMessage = (message, meId) => {
23
- // ensure remoteJid and participant doesn't have device or agent in it
24
- // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
- try {
26
- message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
- }
28
- catch (_e) {
29
- // if normalization fails, retain original remoteJid
30
- }
31
- if (message.key.participant) {
32
- try {
33
- message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
- }
35
- catch (_e) {
36
- // ignore if can't normalize participant
37
- }
38
- }
39
- const content = (0, messages_1.normalizeMessageContent)(message.message);
40
- // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
41
- if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
42
- normaliseKey(content.reactionMessage.key);
43
- }
44
- if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
45
- normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
46
- }
47
- function normaliseKey(msgKey) {
48
- // if the reaction is from another user
49
- // we've to correctly map the key to this user's perspective
50
- if (!message.key.fromMe) {
51
- // if the sender believed the message being reacted to is not from them
52
- // we've to correct the key to be from them, or some other participant
53
- msgKey.fromMe = !msgKey.fromMe
54
- ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
55
- // if the message being reacted to, was from them
56
- // fromMe automatically becomes false
57
- : false;
58
- // set the remoteJid to being the same as the chat the message came from
59
- msgKey.remoteJid = message.key.remoteJid;
60
- // set participant of the message
61
- msgKey.participant = msgKey.participant || message.key.participant;
62
- }
16
+ //=======================================================//
17
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
18
+ //=======================================================//
19
+ export const cleanMessage = (message, meId, meLid) => {
20
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
21
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? "s.whatsapp.net" : "lid");
22
+ }
23
+ else {
24
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
25
+ }
26
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
27
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? "s.whatsapp.net" : "lid");
28
+ }
29
+ else {
30
+ message.key.participant = jidNormalizedUser(message.key.participant);
31
+ }
32
+ const content = normalizeMessageContent(message.message);
33
+ if (content?.reactionMessage) {
34
+ normaliseKey(content.reactionMessage.key);
35
+ }
36
+ if (content?.pollUpdateMessage) {
37
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
38
+ }
39
+ function normaliseKey(msgKey) {
40
+ if (!message.key.fromMe) {
41
+ msgKey.fromMe = !msgKey.fromMe
42
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
43
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
44
+ :
45
+ false;
46
+ msgKey.remoteJid = message.key.remoteJid;
47
+ msgKey.participant = msgKey.participant || message.key.participant;
63
48
  }
49
+ }
64
50
  };
65
- exports.cleanMessage = cleanMessage;
66
- const isRealMessage = (message, meId) => {
67
- var _a;
68
- const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
69
- const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
70
- return (!!normalizedContent
71
- || REAL_MSG_STUB_TYPES.has(message.messageStubType)
72
- || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
73
- && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
74
- && hasSomeContent
75
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
76
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
77
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
51
+ //=======================================================//
52
+ export const isRealMessage = (message) => {
53
+ const normalizedContent = normalizeMessageContent(message.message);
54
+ const hasSomeContent = !!getContentType(normalizedContent);
55
+ return ((!!normalizedContent ||
56
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
57
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
58
+ hasSomeContent &&
59
+ !normalizedContent?.protocolMessage &&
60
+ !normalizedContent?.reactionMessage &&
61
+ !normalizedContent?.pollUpdateMessage);
78
62
  };
79
- exports.isRealMessage = isRealMessage;
80
- const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
81
- exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
82
- /**
83
- * Get the ID of the chat from the given key.
84
- * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
85
- */
86
- const getChatId = ({ remoteJid, participant, fromMe }) => {
87
- if ((0, WABinary_1.isJidBroadcast)(remoteJid)
88
- && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
89
- && !fromMe) {
90
- return participant;
91
- }
92
- return remoteJid;
63
+ //=======================================================//
64
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
65
+ //=======================================================//
66
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
67
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
68
+ return participant;
69
+ }
70
+ return remoteJid;
93
71
  };
94
- exports.getChatId = getChatId;
95
- /**
96
- * Decrypt a poll vote
97
- * @param vote encrypted vote
98
- * @param ctx additional info about the poll required for decryption
99
- * @returns list of SHA256 options
100
- */
101
- function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
102
- const sign = Buffer.concat([
103
- toBinary(pollMsgId),
104
- toBinary(pollCreatorJid),
105
- toBinary(voterJid),
106
- toBinary('Poll Vote'),
107
- new Uint8Array([1])
108
- ]);
109
- const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
110
- const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
111
- const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
112
- const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
113
- return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
114
- function toBinary(txt) {
115
- return Buffer.from(txt);
116
- }
72
+ //=======================================================//
73
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
74
+ const sign = Buffer.concat([
75
+ toBinary(pollMsgId),
76
+ toBinary(pollCreatorJid),
77
+ toBinary(voterJid),
78
+ toBinary("Poll Vote"),
79
+ new Uint8Array([1])
80
+ ]);
81
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), "sha256");
82
+ const decKey = hmacSign(sign, key0, "sha256");
83
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
84
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
85
+ return proto.Message.PollVoteMessage.decode(decrypted);
86
+ function toBinary(txt) {
87
+ return Buffer.from(txt);
88
+ }
117
89
  }
118
- const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
119
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
120
- const meId = creds.me.id;
121
- const { accountSettings } = creds;
122
- const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
123
- const isRealMsg = (0, exports.isRealMessage)(message, meId);
124
- if (isRealMsg) {
125
- chat.messages = [{ message }];
126
- chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
127
- // only increment unread count if not CIPHERTEXT and from another person
128
- if ((0, exports.shouldIncrementChatUnread)(message)) {
129
- chat.unreadCount = (chat.unreadCount || 0) + 1;
130
- }
90
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options }) => {
91
+ const meId = creds.me.id;
92
+ const { accountSettings } = creds;
93
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
94
+ const isRealMsg = isRealMessage(message);
95
+ if (isRealMsg) {
96
+ chat.messages = [{ message }];
97
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
98
+ if (shouldIncrementChatUnread(message)) {
99
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
131
100
  }
132
- const content = (0, messages_1.normalizeMessageContent)(message.message);
133
- const senderId = message.key.participant || message.key.remoteJid;
134
- if ((0, WABinary_1.isLidUser)(senderId)) {
135
- const jid = (0, WABinary_1.lidToJid)(senderId);
136
- if (message.key.participant) {
137
- message.key.participant = jid;
101
+ }
102
+ const content = normalizeMessageContent(message.message);
103
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
104
+ chat.archived = false;
105
+ chat.readOnly = false;
106
+ }
107
+ const protocolMsg = content?.protocolMessage;
108
+ if (protocolMsg) {
109
+ switch (protocolMsg.type) {
110
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
111
+ const histNotification = protocolMsg.historySyncNotification;
112
+ const process = shouldProcessHistoryMsg;
113
+ const isLatest = !creds.processedHistoryMessages?.length;
114
+ logger?.info({
115
+ histNotification,
116
+ process,
117
+ id: message.key.id,
118
+ isLatest
119
+ }, "got history notification");
120
+ if (process) {
121
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
122
+ ev.emit("creds.update", {
123
+ processedHistoryMessages: [
124
+ ...(creds.processedHistoryMessages || []),
125
+ { key: message.key, messageTimestamp: message.messageTimestamp }
126
+ ]
127
+ });
128
+ }
129
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options);
130
+ ev.emit("messaging-history.set", {
131
+ ...data,
132
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
133
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
134
+ });
138
135
  }
139
- else {
140
- message.key.remoteJid = jid;
136
+ break;
137
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
138
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
139
+ if (keys?.length) {
140
+ let newAppStateSyncKeyId = "";
141
+ await keyStore.transaction(async () => {
142
+ const newKeys = [];
143
+ for (const { keyData, keyId } of keys) {
144
+ const strKeyId = Buffer.from(keyId.keyId).toString("base64");
145
+ newKeys.push(strKeyId);
146
+ await keyStore.set({ "app-state-sync-key": { [strKeyId]: keyData } });
147
+ newAppStateSyncKeyId = strKeyId;
148
+ }
149
+ logger?.info({ newAppStateSyncKeyId, newKeys }, "injecting new app state sync keys");
150
+ }, meId);
151
+ ev.emit("creds.update", { myAppStateKeyId: newAppStateSyncKeyId });
141
152
  }
142
- }
143
- const mJids = content && content.contextInfo && content.contextInfo.mentionedJid ? content.contextInfo.mentionedJid : [];
144
- for (let i = 0; i < mJids.length; i++) {
145
- if ((0, WABinary_1.isLidUser)(mJids[i])) {
146
- mJids[i] = (0, WABinary_1.lidToJid)(mJids[i]);
153
+ else {
154
+ logger?.info({ protocolMsg }, "recv app state sync with 0 keys");
147
155
  }
148
- }
149
- if (content && content.contextInfo && content.contextInfo.participant && (0, WABinary_1.isLidUser)(content.contextInfo.participant)) {
150
- content.contextInfo.participant = (0, WABinary_1.lidToJid)(content.contextInfo.participant);
151
- }
152
- // unarchive chat if it's a real message, or someone reacted to our message
153
- // and we've the unarchive chats setting on
154
- if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
155
- && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
156
- chat.archived = false;
157
- chat.readOnly = false;
158
- }
159
- const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
160
- if (protocolMsg) {
161
- switch (protocolMsg.type) {
162
- case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
163
- const histNotification = protocolMsg.historySyncNotification;
164
- const process = shouldProcessHistoryMsg;
165
- const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
166
- logger === null || logger === void 0 ? void 0 : logger.info({
167
- histNotification,
168
- process,
169
- id: message.key.id,
170
- isLatest,
171
- }, 'got history notification');
172
- if (process) {
173
- if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
174
- ev.emit('creds.update', {
175
- processedHistoryMessages: [
176
- ...(creds.processedHistoryMessages || []),
177
- { key: message.key, messageTimestamp: message.messageTimestamp }
178
- ]
179
- });
180
- }
181
- const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
182
- ev.emit('messaging-history.set', {
183
- ...data,
184
- isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
185
- ? isLatest
186
- : undefined,
187
- peerDataRequestSessionId: histNotification.peerDataRequestSessionId
188
- });
189
- }
190
- break;
191
- case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
192
- const keys = protocolMsg.appStateSyncKeyShare.keys;
193
- if (keys === null || keys === void 0 ? void 0 : keys.length) {
194
- let newAppStateSyncKeyId = '';
195
- await keyStore.transaction(async () => {
196
- const newKeys = [];
197
- for (const { keyData, keyId } of keys) {
198
- const strKeyId = Buffer.from(keyId.keyId).toString('base64');
199
- newKeys.push(strKeyId);
200
- await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
201
- newAppStateSyncKeyId = strKeyId;
202
- }
203
- logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
204
- });
205
- ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
206
- }
207
- else {
208
- logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
209
- }
210
- break;
211
- case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
212
- ev.emit('messages.update', [
213
- {
214
- key: {
215
- ...message.key,
216
- id: protocolMsg.key.id
217
- },
218
- update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
219
- }
220
- ]);
221
- break;
222
- case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
223
- Object.assign(chat, {
224
- ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
225
- ephemeralExpiration: protocolMsg.ephemeralExpiration || null
156
+ break;
157
+ case proto.Message.ProtocolMessage.Type.REVOKE:
158
+ ev.emit("messages.update", [
159
+ {
160
+ key: {
161
+ ...message.key,
162
+ id: protocolMsg.key.id
163
+ },
164
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
165
+ }
166
+ ]);
167
+ break;
168
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
169
+ Object.assign(chat, {
170
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
171
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
172
+ });
173
+ break;
174
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
175
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
176
+ if (response) {
177
+ await placeholderResendCache?.del(response.stanzaId);
178
+ const { peerDataOperationResult } = response;
179
+ for (const result of peerDataOperationResult) {
180
+ const { placeholderMessageResendResponse: retryResponse } = result;
181
+ if (retryResponse) {
182
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
183
+ setTimeout(() => {
184
+ ev.emit("messages.upsert", {
185
+ messages: [webMessageInfo],
186
+ type: "notify",
187
+ requestId: response.stanzaId
226
188
  });
227
- break;
228
- case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
229
- const response = protocolMsg.peerDataOperationRequestResponseMessage;
230
- if (response) {
231
- placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
232
- // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
233
- const { peerDataOperationResult } = response;
234
- for (const result of peerDataOperationResult) {
235
- const { placeholderMessageResendResponse: retryResponse } = result;
236
- if (retryResponse) {
237
- const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
238
- // wait till another upsert event is available, don't want it to be part of the PDO response message
239
- setTimeout(() => {
240
- ev.emit('messages.upsert', {
241
- messages: [webMessageInfo],
242
- type: 'notify',
243
- requestId: response.stanzaId
244
- });
245
- }, 500);
246
- }
247
- }
248
- }
249
- case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
250
- ev.emit('messages.update', [
251
- {
252
- // flip the sender / fromMe properties because they're in the perspective of the sender
253
- key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
254
- update: {
255
- message: {
256
- editedMessage: {
257
- message: protocolMsg.editedMessage
258
- }
259
- },
260
- messageTimestamp: protocolMsg.timestampMs
261
- ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
262
- : message.messageTimestamp
263
- }
264
- }
265
- ]);
266
- break;
189
+ }, 500);
190
+ }
191
+ }
267
192
  }
268
- }
269
- else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
270
- const reaction = {
271
- ...content.reactionMessage,
272
- key: message.key,
273
- };
274
- ev.emit('messages.reaction', [{
275
- reaction,
276
- key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
277
- }]);
278
- }
279
- else if (message.messageStubType) {
280
- const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
281
- //let actor = whatsappID (message.participant)
282
- let participants;
283
- const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
284
- const emitGroupUpdate = (update) => {
285
- var _a;
286
- ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
287
- };
288
- const emitGroupRequestJoin = (participant, action, method) => {
289
- ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
290
- };
291
- const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
292
- switch (message.messageStubType) {
293
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
294
- participants = message.messageStubParameters || [];
295
- emitParticipantsUpdate('modify');
296
- break;
297
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
298
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
299
- participants = message.messageStubParameters || [];
300
- emitParticipantsUpdate('remove');
301
- // mark the chat read only if you left the group
302
- if (participantsIncludesMe()) {
303
- chat.readOnly = true;
193
+ break;
194
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
195
+ ev.emit("messages.update", [
196
+ {
197
+ key: { ...message.key, id: protocolMsg.key?.id },
198
+ update: {
199
+ message: {
200
+ editedMessage: {
201
+ message: protocolMsg.editedMessage
304
202
  }
305
- break;
306
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
307
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
308
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
309
- participants = message.messageStubParameters || [];
310
- if (participantsIncludesMe()) {
311
- chat.readOnly = false;
312
- }
313
- emitParticipantsUpdate('add');
314
- break;
315
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
316
- participants = message.messageStubParameters || [];
317
- emitParticipantsUpdate('demote');
318
- break;
319
- case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
320
- participants = message.messageStubParameters || [];
321
- emitParticipantsUpdate('promote');
322
- break;
323
- case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
324
- const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
325
- emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
326
- break;
327
- case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
328
- const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
329
- emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
330
- break;
331
- case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
332
- const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
333
- chat.name = name;
334
- emitGroupUpdate({ subject: name });
335
- break;
336
- case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
337
- const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
338
- chat.description = description;
339
- emitGroupUpdate({ desc: description });
340
- break;
341
- case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
342
- const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
343
- emitGroupUpdate({ inviteCode: code });
344
- break;
345
- case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
346
- const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
347
- emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
348
- break;
349
- case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
350
- const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
351
- emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
352
- break;
353
- case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
354
- const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
355
- const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
356
- const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
357
- emitGroupRequestJoin(participant, action, method);
358
- break;
359
- }
360
- }
361
- else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
362
- const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
363
- // we need to fetch the poll creation message to get the poll enc key
364
- const pollMsg = await getMessage(creationMsgKey);
365
- if (pollMsg) {
366
- const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
367
- const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
368
- const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
369
- const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
370
- try {
371
- const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
372
- pollEncKey,
373
- pollCreatorJid,
374
- pollMsgId: creationMsgKey.id,
375
- voterJid,
376
- });
377
- ev.emit('messages.update', [
378
- {
379
- key: creationMsgKey,
380
- update: {
381
- pollUpdates: [
382
- {
383
- pollUpdateMessageKey: message.key,
384
- vote: voteMsg,
385
- senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
386
- }
387
- ]
388
- }
389
- }
390
- ]);
391
- }
392
- catch (err) {
393
- logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
203
+ },
204
+ messageTimestamp: protocolMsg.timestampMs
205
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
206
+ : message.messageTimestamp
394
207
  }
208
+ }
209
+ ]);
210
+ break;
211
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
212
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
213
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
214
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, "got lid mappings and chat db migration timestamp");
215
+ const pairs = [];
216
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
217
+ const lid = latestLid || assignedLid;
218
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
395
219
  }
396
- else {
397
- logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
220
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
221
+ if (pairs.length) {
222
+ for (const { pn, lid } of pairs) {
223
+ await signalRepository.migrateSession(pn, lid);
224
+ }
398
225
  }
399
226
  }
400
- if (Object.keys(chat).length > 1) {
401
- ev.emit('chats.update', [chat]);
227
+ }
228
+ else if (content?.reactionMessage) {
229
+ const reaction = {
230
+ ...content.reactionMessage,
231
+ key: message.key
232
+ };
233
+ ev.emit("messages.reaction", [
234
+ {
235
+ reaction,
236
+ key: content.reactionMessage?.key
237
+ }
238
+ ]);
239
+ }
240
+ else if (message.messageStubType) {
241
+ const jid = message.key?.remoteJid;
242
+ let participants;
243
+ const emitParticipantsUpdate = (action) => ev.emit("group-participants.update", {
244
+ id: jid,
245
+ author: message.key.participant,
246
+ authorPn: message.key.participantAlt,
247
+ participants,
248
+ action
249
+ });
250
+ const emitGroupUpdate = (update) => {
251
+ ev.emit("groups.update", [
252
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
253
+ ]);
254
+ };
255
+ const emitGroupRequestJoin = (participant, action, method) => {
256
+ ev.emit("group.join-request", {
257
+ id: jid,
258
+ author: message.key.participant,
259
+ authorPn: message.key.participantAlt,
260
+ participant: participant.lid,
261
+ participantPn: participant.pn,
262
+ action,
263
+ method: method
264
+ });
265
+ };
266
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber));
267
+ switch (message.messageStubType) {
268
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
269
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
270
+ emitParticipantsUpdate("modify");
271
+ break;
272
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
273
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
274
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
275
+ emitParticipantsUpdate("remove");
276
+ if (participantsIncludesMe()) {
277
+ chat.readOnly = true;
278
+ }
279
+ break;
280
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
281
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
282
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
283
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
284
+ if (participantsIncludesMe()) {
285
+ chat.readOnly = false;
286
+ }
287
+ emitParticipantsUpdate("add");
288
+ break;
289
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
290
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
291
+ emitParticipantsUpdate("demote");
292
+ break;
293
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
294
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
295
+ emitParticipantsUpdate("promote");
296
+ break;
297
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
298
+ const announceValue = message.messageStubParameters?.[0];
299
+ emitGroupUpdate({ announce: announceValue === "true" || announceValue === "on" });
300
+ break;
301
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
302
+ const restrictValue = message.messageStubParameters?.[0];
303
+ emitGroupUpdate({ restrict: restrictValue === "true" || restrictValue === "on" });
304
+ break;
305
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
306
+ const name = message.messageStubParameters?.[0];
307
+ chat.name = name;
308
+ emitGroupUpdate({ subject: name });
309
+ break;
310
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
311
+ const description = message.messageStubParameters?.[0];
312
+ chat.description = description;
313
+ emitGroupUpdate({ desc: description });
314
+ break;
315
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
316
+ const code = message.messageStubParameters?.[0];
317
+ emitGroupUpdate({ inviteCode: code });
318
+ break;
319
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
320
+ const memberAddValue = message.messageStubParameters?.[0];
321
+ emitGroupUpdate({ memberAddMode: memberAddValue === "all_member_add" });
322
+ break;
323
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
324
+ const approvalMode = message.messageStubParameters?.[0];
325
+ emitGroupUpdate({ joinApprovalMode: approvalMode === "on" });
326
+ break;
327
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
328
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
329
+ const action = message.messageStubParameters?.[1];
330
+ const method = message.messageStubParameters?.[2];
331
+ emitGroupRequestJoin(participant, action, method);
332
+ break;
402
333
  }
334
+ }
335
+ if (Object.keys(chat).length > 1) {
336
+ ev.emit("chats.update", [chat]);
337
+ }
403
338
  };
404
- exports.default = processMessage;
339
+ //=======================================================//
340
+ export default processMessage;
341
+ //=======================================================//