@fanzxnothuman/baileys 2.0.17

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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +479 -0
  3. package/WAProto/index.js +204542 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +158 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Function/Download/tiktok.js +19 -0
  9. package/lib/Function/Tools/bypass.js +19 -0
  10. package/lib/Function/index.js +13 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +99 -0
  13. package/lib/Signal/Group/group_cipher.js +131 -0
  14. package/lib/Signal/Group/index.js +141 -0
  15. package/lib/Signal/Group/keyhelper.js +78 -0
  16. package/lib/Signal/Group/queue-job.js +54 -0
  17. package/lib/Signal/Group/sender-chain-key.js +39 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +76 -0
  19. package/lib/Signal/Group/sender-key-message.js +86 -0
  20. package/lib/Signal/Group/sender-key-name.js +53 -0
  21. package/lib/Signal/Group/sender-key-record.js +71 -0
  22. package/lib/Signal/Group/sender-key-state.js +123 -0
  23. package/lib/Signal/Group/sender-message-key.js +33 -0
  24. package/lib/Signal/libsignal.js +223 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +35 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +96 -0
  28. package/lib/Socket/Client/web-socket-client.js +96 -0
  29. package/lib/Socket/business.js +289 -0
  30. package/lib/Socket/chats.js +1230 -0
  31. package/lib/Socket/dugong.js +689 -0
  32. package/lib/Socket/groups.js +401 -0
  33. package/lib/Socket/index.js +12 -0
  34. package/lib/Socket/messages-recv.js +1531 -0
  35. package/lib/Socket/messages-send.js +1011 -0
  36. package/lib/Socket/newsletter.js +526 -0
  37. package/lib/Socket/registration.js +212 -0
  38. package/lib/Socket/socket.js +842 -0
  39. package/lib/Socket/usync.js +67 -0
  40. package/lib/Store/index.js +16 -0
  41. package/lib/Store/make-cache-manager-store.js +90 -0
  42. package/lib/Store/make-in-memory-store.js +520 -0
  43. package/lib/Store/make-ordered-dictionary.js +78 -0
  44. package/lib/Store/object-repository.js +27 -0
  45. package/lib/Types/Auth.js +2 -0
  46. package/lib/Types/Call.js +2 -0
  47. package/lib/Types/Chat.js +10 -0
  48. package/lib/Types/Contact.js +2 -0
  49. package/lib/Types/Events.js +2 -0
  50. package/lib/Types/GroupMetadata.js +2 -0
  51. package/lib/Types/Label.js +27 -0
  52. package/lib/Types/LabelAssociation.js +12 -0
  53. package/lib/Types/Message.js +14 -0
  54. package/lib/Types/Newsletter.js +38 -0
  55. package/lib/Types/Product.js +2 -0
  56. package/lib/Types/Signal.js +2 -0
  57. package/lib/Types/Socket.js +2 -0
  58. package/lib/Types/State.js +2 -0
  59. package/lib/Types/USync.js +2 -0
  60. package/lib/Types/index.js +67 -0
  61. package/lib/Utils/auth-utils.js +223 -0
  62. package/lib/Utils/baileys-event-stream.js +67 -0
  63. package/lib/Utils/business.js +308 -0
  64. package/lib/Utils/chat-utils.js +1030 -0
  65. package/lib/Utils/crypto.js +210 -0
  66. package/lib/Utils/decode-wa-message.js +225 -0
  67. package/lib/Utils/event-buffer.js +559 -0
  68. package/lib/Utils/generics.js +599 -0
  69. package/lib/Utils/history.js +132 -0
  70. package/lib/Utils/index.js +49 -0
  71. package/lib/Utils/link-preview.js +112 -0
  72. package/lib/Utils/logger.js +11 -0
  73. package/lib/Utils/lt-hash.js +58 -0
  74. package/lib/Utils/make-mutex.js +41 -0
  75. package/lib/Utils/messages-media.js +978 -0
  76. package/lib/Utils/messages.js +1052 -0
  77. package/lib/Utils/noise-handler.js +185 -0
  78. package/lib/Utils/process-message.js +466 -0
  79. package/lib/Utils/signal.js +199 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +129 -0
  81. package/lib/Utils/validate-connection.js +285 -0
  82. package/lib/WABinary/constants.js +1307 -0
  83. package/lib/WABinary/decode.js +287 -0
  84. package/lib/WABinary/encode.js +286 -0
  85. package/lib/WABinary/generic-utils.js +227 -0
  86. package/lib/WABinary/index.js +37 -0
  87. package/lib/WABinary/jid-utils.js +92 -0
  88. package/lib/WABinary/types.js +2 -0
  89. package/lib/WAM/BinaryInfo.js +13 -0
  90. package/lib/WAM/constants.js +15260 -0
  91. package/lib/WAM/encode.js +153 -0
  92. package/lib/WAM/index.js +35 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +37 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +78 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  99. package/lib/WAUSync/Protocols/index.js +36 -0
  100. package/lib/WAUSync/USyncQuery.js +105 -0
  101. package/lib/WAUSync/USyncUser.js +26 -0
  102. package/lib/WAUSync/index.js +35 -0
  103. package/lib/index.js +65 -0
  104. package/package.json +109 -0
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeNoiseHandler = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WAProto_1 = require("../../WAProto");
6
+ const Defaults_1 = require("../Defaults");
7
+ const WABinary_1 = require("../WABinary");
8
+ const crypto_1 = require("./crypto");
9
+ const generateIV = (counter) => {
10
+ const iv = new ArrayBuffer(12);
11
+ new DataView(iv).setUint32(8, counter);
12
+ return new Uint8Array(iv);
13
+ };
14
+ const makeNoiseHandler = ({
15
+ keyPair: { private: privateKey, public: publicKey },
16
+ NOISE_HEADER,
17
+ mobile,
18
+ logger,
19
+ routingInfo,
20
+ }) => {
21
+ logger = logger.child({ class: "ns" });
22
+ const authenticate = (data) => {
23
+ if (!isFinished) {
24
+ hash = (0, crypto_1.sha256)(Buffer.concat([hash, data]));
25
+ }
26
+ };
27
+ const encrypt = (plaintext) => {
28
+ const result = (0, crypto_1.aesEncryptGCM)(
29
+ plaintext,
30
+ encKey,
31
+ generateIV(writeCounter),
32
+ hash,
33
+ );
34
+ writeCounter += 1;
35
+ authenticate(result);
36
+ return result;
37
+ };
38
+ const decrypt = (ciphertext) => {
39
+ // before the handshake is finished, we use the same counter
40
+ // after handshake, the counters are different
41
+ const iv = generateIV(isFinished ? readCounter : writeCounter);
42
+ const result = (0, crypto_1.aesDecryptGCM)(ciphertext, decKey, iv, hash);
43
+ if (isFinished) {
44
+ readCounter += 1;
45
+ } else {
46
+ writeCounter += 1;
47
+ }
48
+ authenticate(ciphertext);
49
+ return result;
50
+ };
51
+ const localHKDF = (data) => {
52
+ const key = (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: "" });
53
+ return [key.slice(0, 32), key.slice(32)];
54
+ };
55
+ const mixIntoKey = (data) => {
56
+ const [write, read] = localHKDF(data);
57
+ salt = write;
58
+ encKey = read;
59
+ decKey = read;
60
+ readCounter = 0;
61
+ writeCounter = 0;
62
+ };
63
+ const finishInit = () => {
64
+ const [write, read] = localHKDF(new Uint8Array(0));
65
+ encKey = write;
66
+ decKey = read;
67
+ hash = Buffer.from([]);
68
+ readCounter = 0;
69
+ writeCounter = 0;
70
+ isFinished = true;
71
+ };
72
+ const data = Buffer.from(Defaults_1.NOISE_MODE);
73
+ let hash = Buffer.from(
74
+ data.byteLength === 32 ? data : (0, crypto_1.sha256)(data),
75
+ );
76
+ let salt = hash;
77
+ let encKey = hash;
78
+ let decKey = hash;
79
+ let readCounter = 0;
80
+ let writeCounter = 0;
81
+ let isFinished = false;
82
+ let sentIntro = false;
83
+ let inBytes = Buffer.alloc(0);
84
+ authenticate(NOISE_HEADER);
85
+ authenticate(publicKey);
86
+ return {
87
+ encrypt,
88
+ decrypt,
89
+ authenticate,
90
+ mixIntoKey,
91
+ finishInit,
92
+ processHandshake: ({ serverHello }, noiseKey) => {
93
+ authenticate(serverHello.ephemeral);
94
+ mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
95
+ const decStaticContent = decrypt(serverHello.static);
96
+ mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
97
+ const certDecoded = decrypt(serverHello.payload);
98
+ if (mobile) {
99
+ WAProto_1.proto.CertChain.NoiseCertificate.decode(certDecoded);
100
+ } else {
101
+ const { intermediate: certIntermediate } =
102
+ WAProto_1.proto.CertChain.decode(certDecoded);
103
+ const { issuerSerial } =
104
+ WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(
105
+ certIntermediate.details,
106
+ );
107
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
108
+ throw new boom_1.Boom("certification match failed", {
109
+ statusCode: 400,
110
+ });
111
+ }
112
+ }
113
+ const keyEnc = encrypt(noiseKey.public);
114
+ mixIntoKey(
115
+ crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral),
116
+ );
117
+ return keyEnc;
118
+ },
119
+ encodeFrame: (data) => {
120
+ if (isFinished) {
121
+ data = encrypt(data);
122
+ }
123
+ let header;
124
+ if (routingInfo) {
125
+ header = Buffer.alloc(7);
126
+ header.write("ED", 0, "utf8");
127
+ header.writeUint8(0, 2);
128
+ header.writeUint8(1, 3);
129
+ header.writeUint8(routingInfo.byteLength >> 16, 4);
130
+ header.writeUint16BE(routingInfo.byteLength & 65535, 5);
131
+ header = Buffer.concat([header, routingInfo, NOISE_HEADER]);
132
+ } else {
133
+ header = Buffer.from(NOISE_HEADER);
134
+ }
135
+ const introSize = sentIntro ? 0 : header.length;
136
+ const frame = Buffer.alloc(introSize + 3 + data.byteLength);
137
+ if (!sentIntro) {
138
+ frame.set(header);
139
+ sentIntro = true;
140
+ }
141
+ frame.writeUInt8(data.byteLength >> 16, introSize);
142
+ frame.writeUInt16BE(65535 & data.byteLength, introSize + 1);
143
+ frame.set(data, introSize + 3);
144
+ return frame;
145
+ },
146
+ decodeFrame: (newData, onFrame) => {
147
+ var _a;
148
+ // the binary protocol uses its own framing mechanism
149
+ // on top of the WS frames
150
+ // so we get this data and separate out the frames
151
+ const getBytesSize = () => {
152
+ if (inBytes.length >= 3) {
153
+ return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1);
154
+ }
155
+ };
156
+ inBytes = Buffer.concat([inBytes, newData]);
157
+ logger.trace(
158
+ `recv ${newData.length} bytes, total recv ${inBytes.length} bytes`,
159
+ );
160
+ let size = getBytesSize();
161
+ while (size && inBytes.length >= size + 3) {
162
+ let frame = inBytes.slice(3, size + 3);
163
+ inBytes = inBytes.slice(size + 3);
164
+ if (isFinished) {
165
+ const result = decrypt(frame);
166
+ frame = (0, WABinary_1.decodeBinaryNode)(result);
167
+ }
168
+ logger.trace(
169
+ {
170
+ msg:
171
+ (_a =
172
+ frame === null || frame === void 0 ? void 0 : frame.attrs) ===
173
+ null || _a === void 0
174
+ ? void 0
175
+ : _a.id,
176
+ },
177
+ "recv frame",
178
+ );
179
+ onFrame(frame);
180
+ size = getBytesSize();
181
+ }
182
+ },
183
+ };
184
+ };
185
+ exports.makeNoiseHandler = makeNoiseHandler;
@@ -0,0 +1,466 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decryptPollVote =
4
+ exports.getChatId =
5
+ exports.shouldIncrementChatUnread =
6
+ exports.isRealMessage =
7
+ exports.cleanMessage =
8
+ void 0;
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Types_1 = require("../Types");
11
+ const messages_1 = require("../Utils/messages");
12
+ const WABinary_1 = require("../WABinary");
13
+ const crypto_1 = require("./crypto");
14
+ const generics_1 = require("./generics");
15
+ const history_1 = require("./history");
16
+ const REAL_MSG_STUB_TYPES = new Set([
17
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
18
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
19
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
20
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE,
21
+ ]);
22
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
23
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD,
24
+ ]);
25
+ /** Cleans a received message to further processing */
26
+ const cleanMessage = (message, meId) => {
27
+ // ensure remoteJid and participant doesn't have device or agent in it
28
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(
29
+ message.key.remoteJid,
30
+ );
31
+ message.key.participant = message.key.participant
32
+ ? (0, WABinary_1.jidNormalizedUser)(message.key.participant)
33
+ : undefined;
34
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
35
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
36
+ if (
37
+ content === null || content === void 0 ? void 0 : content.reactionMessage
38
+ ) {
39
+ normaliseKey(content.reactionMessage.key);
40
+ }
41
+ if (
42
+ content === null || content === void 0 ? void 0 : content.pollUpdateMessage
43
+ ) {
44
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
45
+ }
46
+ function normaliseKey(msgKey) {
47
+ // if the reaction is from another user
48
+ // we've to correctly map the key to this user's perspective
49
+ if (!message.key.fromMe) {
50
+ // if the sender believed the message being reacted to is not from them
51
+ // we've to correct the key to be from them, or some other participant
52
+ msgKey.fromMe = !msgKey.fromMe
53
+ ? (0, WABinary_1.areJidsSameUser)(
54
+ msgKey.participant || msgKey.remoteJid,
55
+ meId,
56
+ )
57
+ : // if the message being reacted to, was from them
58
+ // fromMe automatically becomes false
59
+ false;
60
+ // set the remoteJid to being the same as the chat the message came from
61
+ msgKey.remoteJid = message.key.remoteJid;
62
+ // set participant of the message
63
+ msgKey.participant = msgKey.participant || message.key.participant;
64
+ }
65
+ }
66
+ };
67
+ exports.cleanMessage = cleanMessage;
68
+ const isRealMessage = (message, meId) => {
69
+ var _a;
70
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(
71
+ message.message,
72
+ );
73
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
74
+ return (
75
+ (!!normalizedContent ||
76
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
77
+ (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) &&
78
+ ((_a = message.messageStubParameters) === null || _a === void 0
79
+ ? void 0
80
+ : _a.some((p) => (0, WABinary_1.areJidsSameUser)(meId, p))))) &&
81
+ hasSomeContent &&
82
+ !(normalizedContent === null || normalizedContent === void 0
83
+ ? void 0
84
+ : normalizedContent.protocolMessage) &&
85
+ !(normalizedContent === null || normalizedContent === void 0
86
+ ? void 0
87
+ : normalizedContent.reactionMessage) &&
88
+ !(normalizedContent === null || normalizedContent === void 0
89
+ ? void 0
90
+ : normalizedContent.pollUpdateMessage)
91
+ );
92
+ };
93
+ exports.isRealMessage = isRealMessage;
94
+ const shouldIncrementChatUnread = (message) =>
95
+ !message.key.fromMe && !message.messageStubType;
96
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
97
+ /**
98
+ * Get the ID of the chat from the given key.
99
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
100
+ */
101
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
102
+ if (
103
+ (0, WABinary_1.isJidBroadcast)(remoteJid) &&
104
+ !(0, WABinary_1.isJidStatusBroadcast)(remoteJid) &&
105
+ !fromMe
106
+ ) {
107
+ return participant;
108
+ }
109
+ return remoteJid;
110
+ };
111
+ exports.getChatId = getChatId;
112
+ /**
113
+ * Decrypt a poll vote
114
+ * @param vote encrypted vote
115
+ * @param ctx additional info about the poll required for decryption
116
+ * @returns list of SHA256 options
117
+ */
118
+ function decryptPollVote(
119
+ { encPayload, encIv },
120
+ { pollCreatorJid, pollMsgId, pollEncKey, voterJid },
121
+ ) {
122
+ const sign = Buffer.concat([
123
+ toBinary(pollMsgId),
124
+ toBinary(pollCreatorJid),
125
+ toBinary(voterJid),
126
+ toBinary("Poll Vote"),
127
+ new Uint8Array([1]),
128
+ ]);
129
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), "sha256");
130
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, "sha256");
131
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
132
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
133
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
134
+ function toBinary(txt) {
135
+ return Buffer.from(txt);
136
+ }
137
+ }
138
+ exports.decryptPollVote = decryptPollVote;
139
+ const processMessage = async (
140
+ message,
141
+ { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage },
142
+ ) => {
143
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
144
+ const meId = creds.me.id;
145
+ const { accountSettings } = creds;
146
+ const chat = {
147
+ id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)),
148
+ };
149
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
150
+ if (isRealMsg) {
151
+ chat.conversationTimestamp = (0, generics_1.toNumber)(
152
+ message.messageTimestamp,
153
+ );
154
+ // only increment unread count if not CIPHERTEXT and from another person
155
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
156
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
157
+ }
158
+ }
159
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
160
+ // unarchive chat if it's a real message, or someone reacted to our message
161
+ // and we've the unarchive chats setting on
162
+ if (
163
+ (isRealMsg ||
164
+ ((_b =
165
+ (_a =
166
+ content === null || content === void 0
167
+ ? void 0
168
+ : content.reactionMessage) === null || _a === void 0
169
+ ? void 0
170
+ : _a.key) === null || _b === void 0
171
+ ? void 0
172
+ : _b.fromMe)) &&
173
+ (accountSettings === null || accountSettings === void 0
174
+ ? void 0
175
+ : accountSettings.unarchiveChats)
176
+ ) {
177
+ chat.archived = false;
178
+ chat.readOnly = false;
179
+ }
180
+ const protocolMsg =
181
+ content === null || content === void 0 ? void 0 : content.protocolMessage;
182
+ if (protocolMsg) {
183
+ switch (protocolMsg.type) {
184
+ case WAProto_1.proto.Message.ProtocolMessage.Type
185
+ .HISTORY_SYNC_NOTIFICATION:
186
+ const histNotification = protocolMsg.historySyncNotification;
187
+ const process = shouldProcessHistoryMsg;
188
+ const isLatest = !((_c = creds.processedHistoryMessages) === null ||
189
+ _c === void 0
190
+ ? void 0
191
+ : _c.length);
192
+ logger === null || logger === void 0
193
+ ? void 0
194
+ : logger.info(
195
+ {
196
+ histNotification,
197
+ process,
198
+ id: message.key.id,
199
+ isLatest,
200
+ },
201
+ "got history notification",
202
+ );
203
+ if (process) {
204
+ ev.emit("creds.update", {
205
+ processedHistoryMessages: [
206
+ ...(creds.processedHistoryMessages || []),
207
+ { key: message.key, messageTimestamp: message.messageTimestamp },
208
+ ],
209
+ });
210
+ const data = await (0,
211
+ history_1.downloadAndProcessHistorySyncNotification)(
212
+ histNotification,
213
+ options,
214
+ );
215
+ ev.emit("messaging-history.set", { ...data, isLatest });
216
+ }
217
+ break;
218
+ case WAProto_1.proto.Message.ProtocolMessage.Type
219
+ .APP_STATE_SYNC_KEY_SHARE:
220
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
221
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
222
+ let newAppStateSyncKeyId = "";
223
+ await keyStore.transaction(async () => {
224
+ const newKeys = [];
225
+ for (const { keyData, keyId } of keys) {
226
+ const strKeyId = Buffer.from(keyId.keyId).toString("base64");
227
+ newKeys.push(strKeyId);
228
+ await keyStore.set({
229
+ "app-state-sync-key": { [strKeyId]: keyData },
230
+ });
231
+ newAppStateSyncKeyId = strKeyId;
232
+ }
233
+ logger === null || logger === void 0
234
+ ? void 0
235
+ : logger.info(
236
+ { newAppStateSyncKeyId, newKeys },
237
+ "injecting new app state sync keys",
238
+ );
239
+ });
240
+ ev.emit("creds.update", { myAppStateKeyId: newAppStateSyncKeyId });
241
+ } else {
242
+ logger === null || logger === void 0
243
+ ? void 0
244
+ : logger.info({ protocolMsg }, "recv app state sync with 0 keys");
245
+ }
246
+ break;
247
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
248
+ ev.emit("messages.update", [
249
+ {
250
+ key: {
251
+ ...message.key,
252
+ id: protocolMsg.key.id,
253
+ },
254
+ update: {
255
+ message: null,
256
+ messageStubType: Types_1.WAMessageStubType.REVOKE,
257
+ key: message.key,
258
+ },
259
+ },
260
+ ]);
261
+ break;
262
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
263
+ Object.assign(chat, {
264
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(
265
+ message.messageTimestamp,
266
+ ),
267
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null,
268
+ });
269
+ break;
270
+ case WAProto_1.proto.Message.ProtocolMessage.Type
271
+ .PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
272
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
273
+ if (response) {
274
+ const { peerDataOperationResult } = response;
275
+ for (const result of peerDataOperationResult) {
276
+ const { placeholderMessageResendResponse: retryResponse } = result;
277
+ if (retryResponse) {
278
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(
279
+ retryResponse.webMessageInfoBytes,
280
+ );
281
+ ev.emit("messages.update", [
282
+ {
283
+ key: webMessageInfo.key,
284
+ update: { message: webMessageInfo.message },
285
+ },
286
+ ]);
287
+ }
288
+ }
289
+ }
290
+ break;
291
+ }
292
+ } else if (
293
+ content === null || content === void 0 ? void 0 : content.reactionMessage
294
+ ) {
295
+ const reaction = {
296
+ ...content.reactionMessage,
297
+ key: message.key,
298
+ };
299
+ ev.emit("messages.reaction", [
300
+ {
301
+ reaction,
302
+ key: content.reactionMessage.key,
303
+ },
304
+ ]);
305
+ } else if (message.messageStubType) {
306
+ const jid = message.key.remoteJid;
307
+ //let actor = whatsappID (message.participant)
308
+ let participants;
309
+ const emitParticipantsUpdate = (action) =>
310
+ ev.emit("group-participants.update", {
311
+ id: jid,
312
+ author: message.participant,
313
+ participants,
314
+ action,
315
+ });
316
+ const emitGroupUpdate = (update) => {
317
+ var _a;
318
+ ev.emit("groups.update", [
319
+ {
320
+ id: jid,
321
+ ...update,
322
+ author:
323
+ (_a = message.participant) !== null && _a !== void 0
324
+ ? _a
325
+ : undefined,
326
+ },
327
+ ]);
328
+ };
329
+ const participantsIncludesMe = () =>
330
+ participants.find((jid) => (0, WABinary_1.areJidsSameUser)(meId, jid));
331
+ switch (message.messageStubType) {
332
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
333
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
334
+ participants = message.messageStubParameters || [];
335
+ emitParticipantsUpdate("remove");
336
+ // mark the chat read only if you left the group
337
+ if (participantsIncludesMe()) {
338
+ chat.readOnly = true;
339
+ }
340
+ break;
341
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
342
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
343
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
344
+ participants = message.messageStubParameters || [];
345
+ if (participantsIncludesMe()) {
346
+ chat.readOnly = false;
347
+ }
348
+ emitParticipantsUpdate("add");
349
+ break;
350
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
351
+ participants = message.messageStubParameters || [];
352
+ emitParticipantsUpdate("demote");
353
+ break;
354
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
355
+ participants = message.messageStubParameters || [];
356
+ emitParticipantsUpdate("promote");
357
+ break;
358
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
359
+ const announceValue =
360
+ (_d = message.messageStubParameters) === null || _d === void 0
361
+ ? void 0
362
+ : _d[0];
363
+ emitGroupUpdate({
364
+ announce: announceValue === "true" || announceValue === "on",
365
+ });
366
+ break;
367
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
368
+ const restrictValue =
369
+ (_e = message.messageStubParameters) === null || _e === void 0
370
+ ? void 0
371
+ : _e[0];
372
+ emitGroupUpdate({
373
+ restrict: restrictValue === "true" || restrictValue === "on",
374
+ });
375
+ break;
376
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
377
+ const name =
378
+ (_f = message.messageStubParameters) === null || _f === void 0
379
+ ? void 0
380
+ : _f[0];
381
+ chat.name = name;
382
+ emitGroupUpdate({ subject: name });
383
+ break;
384
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
385
+ const code =
386
+ (_g = message.messageStubParameters) === null || _g === void 0
387
+ ? void 0
388
+ : _g[0];
389
+ emitGroupUpdate({ inviteCode: code });
390
+ break;
391
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
392
+ const memberAddValue =
393
+ (_h = message.messageStubParameters) === null || _h === void 0
394
+ ? void 0
395
+ : _h[0];
396
+ emitGroupUpdate({ memberAddMode: memberAddValue === "all_member_add" });
397
+ break;
398
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
399
+ const approvalMode =
400
+ (_j = message.messageStubParameters) === null || _j === void 0
401
+ ? void 0
402
+ : _j[0];
403
+ emitGroupUpdate({ joinApprovalMode: approvalMode === "on" });
404
+ break;
405
+ }
406
+ } else if (
407
+ content === null || content === void 0 ? void 0 : content.pollUpdateMessage
408
+ ) {
409
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
410
+ // we need to fetch the poll creation message to get the poll enc key
411
+ const pollMsg = await getMessage(creationMsgKey);
412
+ if (pollMsg) {
413
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
414
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(
415
+ creationMsgKey,
416
+ meIdNormalised,
417
+ );
418
+ const voterJid = (0, generics_1.getKeyAuthor)(
419
+ message.key,
420
+ meIdNormalised,
421
+ );
422
+ const pollEncKey =
423
+ (_k = pollMsg.messageContextInfo) === null || _k === void 0
424
+ ? void 0
425
+ : _k.messageSecret;
426
+ try {
427
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
428
+ pollEncKey,
429
+ pollCreatorJid,
430
+ pollMsgId: creationMsgKey.id,
431
+ voterJid,
432
+ });
433
+ ev.emit("messages.update", [
434
+ {
435
+ key: creationMsgKey,
436
+ update: {
437
+ pollUpdates: [
438
+ {
439
+ pollUpdateMessageKey: message.key,
440
+ vote: voteMsg,
441
+ senderTimestampMs:
442
+ content.pollUpdateMessage.senderTimestampMs.toNumber(),
443
+ },
444
+ ],
445
+ },
446
+ },
447
+ ]);
448
+ } catch (err) {
449
+ logger === null || logger === void 0
450
+ ? void 0
451
+ : logger.warn({ err, creationMsgKey }, "failed to decrypt poll vote");
452
+ }
453
+ } else {
454
+ logger === null || logger === void 0
455
+ ? void 0
456
+ : logger.warn(
457
+ { creationMsgKey },
458
+ "poll creation message not found, cannot decrypt update",
459
+ );
460
+ }
461
+ }
462
+ if (Object.keys(chat).length > 1) {
463
+ ev.emit("chats.update", [chat]);
464
+ }
465
+ };
466
+ exports.default = processMessage;