@sixcore/baileys 1.0.2 → 1.1.0

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