@skyzopedia/baileys-mod 5.0.7 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/WAProto/index.js +133384 -57814
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +53 -0
  5. package/lib/Defaults/index.js +141 -117
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +14 -12
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +42 -10
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +87 -75
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +52 -17
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +33 -27
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +63 -62
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +66 -65
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +44 -45
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +49 -39
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +93 -80
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/lib/Signal/Group/sender-message-key.js +28 -27
  33. package/lib/Signal/libsignal.d.ts +3 -0
  34. package/lib/Signal/libsignal.js +163 -313
  35. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  36. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +19 -4
  39. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  40. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  41. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  42. package/lib/Socket/Client/web-socket-client.js +62 -0
  43. package/lib/Socket/business.d.ts +171 -0
  44. package/lib/Socket/business.js +242 -359
  45. package/lib/Socket/chats.d.ts +267 -0
  46. package/lib/Socket/chats.js +935 -846
  47. package/lib/Socket/dugong.d.ts +254 -0
  48. package/lib/Socket/dugong.js +484 -0
  49. package/lib/Socket/groups.d.ts +115 -0
  50. package/lib/Socket/groups.js +309 -304
  51. package/lib/Socket/index.d.ts +173 -0
  52. package/lib/Socket/index.js +10 -15
  53. package/lib/Socket/messages-recv.d.ts +161 -0
  54. package/lib/Socket/messages-recv.js +1054 -1107
  55. package/lib/Socket/messages-send.d.ts +149 -0
  56. package/lib/Socket/messages-send.js +447 -706
  57. package/lib/Socket/newsletter.d.ts +134 -0
  58. package/lib/Socket/newsletter.js +314 -199
  59. package/lib/Socket/registration.d.ts +267 -0
  60. package/lib/Socket/registration.js +166 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +650 -777
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +70 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +10 -6
  67. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  68. package/lib/Store/make-cache-manager-store.js +81 -73
  69. package/lib/Store/make-in-memory-store.d.ts +118 -0
  70. package/lib/Store/make-in-memory-store.js +423 -286
  71. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  72. package/lib/Store/make-ordered-dictionary.js +79 -77
  73. package/lib/Store/object-repository.d.ts +10 -0
  74. package/lib/Store/object-repository.js +26 -24
  75. package/lib/Types/Auth.d.ts +110 -0
  76. package/lib/Types/Auth.js +2 -3
  77. package/lib/Types/Call.d.ts +13 -0
  78. package/lib/Types/Call.js +2 -3
  79. package/lib/Types/Chat.d.ts +102 -0
  80. package/lib/Types/Chat.js +4 -9
  81. package/lib/Types/Contact.d.ts +19 -0
  82. package/lib/Types/Contact.js +2 -3
  83. package/lib/Types/Events.d.ts +157 -0
  84. package/lib/Types/Events.js +2 -3
  85. package/lib/Types/GroupMetadata.d.ts +55 -0
  86. package/lib/Types/GroupMetadata.js +2 -3
  87. package/lib/Types/Label.d.ts +35 -0
  88. package/lib/Types/Label.js +26 -24
  89. package/lib/Types/LabelAssociation.d.ts +29 -0
  90. package/lib/Types/LabelAssociation.js +8 -6
  91. package/lib/Types/Message.d.ts +273 -0
  92. package/lib/Types/Message.js +9 -12
  93. package/lib/Types/Newsletter.d.ts +103 -0
  94. package/lib/Types/Newsletter.js +38 -33
  95. package/lib/Types/Product.d.ts +78 -0
  96. package/lib/Types/Product.js +2 -3
  97. package/lib/Types/Signal.d.ts +57 -0
  98. package/lib/Types/Signal.js +2 -3
  99. package/lib/Types/Socket.d.ts +111 -0
  100. package/lib/Types/Socket.js +2 -4
  101. package/lib/Types/State.d.ts +27 -0
  102. package/lib/Types/State.js +2 -11
  103. package/lib/Types/USync.d.ts +25 -0
  104. package/lib/Types/USync.js +2 -3
  105. package/lib/Types/index.d.ts +57 -0
  106. package/lib/Types/index.js +41 -27
  107. package/lib/Utils/auth-utils.d.ts +18 -0
  108. package/lib/Utils/auth-utils.js +198 -211
  109. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  110. package/lib/Utils/baileys-event-stream.js +61 -42
  111. package/lib/Utils/business.d.ts +22 -0
  112. package/lib/Utils/business.js +214 -213
  113. package/lib/Utils/chat-utils.d.ts +71 -0
  114. package/lib/Utils/chat-utils.js +687 -710
  115. package/lib/Utils/crypto.d.ts +41 -0
  116. package/lib/Utils/crypto.js +133 -112
  117. package/lib/Utils/decode-wa-message.d.ts +19 -0
  118. package/lib/Utils/decode-wa-message.js +183 -252
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +496 -510
  121. package/lib/Utils/generics.d.ts +92 -0
  122. package/lib/Utils/generics.js +387 -319
  123. package/lib/Utils/history.d.ts +15 -0
  124. package/lib/Utils/history.js +92 -83
  125. package/lib/Utils/index.d.ts +17 -0
  126. package/lib/Utils/index.js +33 -21
  127. package/lib/Utils/link-preview.d.ts +21 -0
  128. package/lib/Utils/link-preview.js +83 -71
  129. package/lib/Utils/logger.d.ts +4 -0
  130. package/lib/Utils/logger.js +7 -5
  131. package/lib/Utils/lt-hash.d.ts +12 -0
  132. package/lib/Utils/lt-hash.js +46 -40
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +41 -34
  135. package/lib/Utils/messages-media.d.ts +116 -0
  136. package/lib/Utils/messages-media.js +768 -550
  137. package/lib/Utils/messages.d.ts +77 -0
  138. package/lib/Utils/messages.js +263 -362
  139. package/lib/Utils/noise-handler.d.ts +21 -0
  140. package/lib/Utils/noise-handler.js +149 -138
  141. package/lib/Utils/process-message.d.ts +41 -0
  142. package/lib/Utils/process-message.js +303 -323
  143. package/lib/Utils/signal.d.ts +32 -0
  144. package/lib/Utils/signal.js +141 -149
  145. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +103 -95
  147. package/lib/Utils/validate-connection.d.ts +11 -0
  148. package/lib/Utils/validate-connection.js +220 -183
  149. package/lib/WABinary/constants.d.ts +30 -0
  150. package/lib/WABinary/constants.js +35 -1298
  151. package/lib/WABinary/decode.d.ts +7 -0
  152. package/lib/WABinary/decode.js +249 -237
  153. package/lib/WABinary/encode.d.ts +3 -0
  154. package/lib/WABinary/encode.js +260 -213
  155. package/lib/WABinary/generic-utils.d.ts +17 -0
  156. package/lib/WABinary/generic-utils.js +65 -56
  157. package/lib/WABinary/index.d.ts +5 -0
  158. package/lib/WABinary/index.js +21 -7
  159. package/lib/WABinary/jid-utils.d.ts +31 -0
  160. package/lib/WABinary/jid-utils.js +58 -89
  161. package/lib/WABinary/types.d.ts +18 -0
  162. package/lib/WABinary/types.js +2 -3
  163. package/lib/WAM/BinaryInfo.d.ts +17 -0
  164. package/lib/WAM/BinaryInfo.js +12 -10
  165. package/lib/WAM/constants.d.ts +38 -0
  166. package/lib/WAM/constants.js +15348 -22851
  167. package/lib/WAM/encode.d.ts +3 -0
  168. package/lib/WAM/encode.js +136 -135
  169. package/lib/WAM/index.d.ts +3 -0
  170. package/lib/WAM/index.js +19 -5
  171. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  172. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -28
  173. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -49
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  176. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +28 -27
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -36
  179. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  180. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  181. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  182. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +20 -26
  183. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  184. package/lib/WAUSync/Protocols/index.js +20 -6
  185. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  186. package/lib/WAUSync/USyncQuery.js +85 -86
  187. package/lib/WAUSync/USyncUser.d.ts +12 -0
  188. package/lib/WAUSync/USyncUser.js +25 -23
  189. package/lib/WAUSync/index.d.ts +3 -0
  190. package/lib/WAUSync/index.js +19 -5
  191. package/lib/index.d.ts +12 -0
  192. package/lib/index.js +36 -24
  193. package/package.json +106 -98
  194. package/LICENSE +0 -21
  195. package/WAProto/WAProto.proto +0 -5311
  196. package/lib/KeyDB/BinarySearch.js +0 -20
  197. package/lib/KeyDB/KeyedDB.js +0 -167
  198. package/lib/KeyDB/index.js +0 -4
  199. package/lib/Signal/lid-mapping.js +0 -155
  200. package/lib/Socket/Client/types.js +0 -13
  201. package/lib/Socket/Client/websocket.js +0 -52
  202. package/lib/Socket/Client/websocket.js.bak +0 -53
  203. package/lib/Socket/communities.js +0 -413
  204. package/lib/Socket/mex.js +0 -45
  205. package/lib/Types/Bussines.js +0 -3
  206. package/lib/Types/Newsletter.js.bak +0 -33
  207. package/lib/Utils/browser-utils.js +0 -25
  208. package/lib/Utils/message-retry-manager.js +0 -113
  209. package/lib/Utils/messages.js.bak +0 -907
  210. package/lib/Utils/pre-key-manager.js +0 -85
@@ -1,1163 +1,1110 @@
1
- //=======================================================//
2
- import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from "../Utils/index.js";
3
- import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from "../WABinary/index.js";
4
- import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from "../Defaults/index.js";
5
- import { WAMessageStatus, WAMessageStubType } from "../Types/index.js";
6
- import { makeMessagesSocket } from "./messages-send.js";
7
- import { makeMutex } from "../Utils/make-mutex.js";
8
- import { extractGroupMetadata } from "./groups.js";
9
- import NodeCache from "@cacheable/node-cache";
10
- import { proto } from "../../WAProto/index.js";
11
- import { randomBytes } from "crypto";
12
- import { Boom } from "@hapi/boom";
13
- import Long from "long";
14
- //=======================================================//
15
- export const makeMessagesRecvSocket = (config) => {
16
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
17
- const sock = makeMessagesSocket(config);
18
- const { ev, authState, ws, processingMutex, signalRepository, query, generateMessageTag, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
19
- const retryMutex = makeMutex();
20
- const msgRetryCache = config.msgRetryCounterCache ||
21
- new NodeCache({
22
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
23
- useClones: false
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesRecvSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const crypto_1 = require("crypto");
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Types_1 = require("../Types");
13
+ const Utils_1 = require("../Utils");
14
+ const make_mutex_1 = require("../Utils/make-mutex");
15
+ const WABinary_1 = require("../WABinary");
16
+ const groups_1 = require("./groups");
17
+ const messages_send_1 = require("./messages-send");
18
+ const makeMessagesRecvSocket = (config) => {
19
+ const {
20
+ logger,
21
+ retryRequestDelayMs,
22
+ maxMsgRetryCount,
23
+ getMessage,
24
+ shouldIgnoreJid
25
+ } = config;
26
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
27
+ const {
28
+ ev,
29
+ authState,
30
+ ws,
31
+ processingMutex,
32
+ signalRepository,
33
+ query,
34
+ upsertMessage,
35
+ resyncAppState,
36
+ groupMetadata,
37
+ onUnexpectedError,
38
+ assertSessions,
39
+ sendNode,
40
+ relayMessage,
41
+ sendReceipt,
42
+ uploadPreKeys,
43
+ createParticipantNodes,
44
+ getUSyncDevices,
45
+ sendPeerDataOperationMessage
46
+ } = sock;
47
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
48
+ const retryMutex = (0, make_mutex_1.makeMutex)();
49
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
50
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
51
+ useClones: false
24
52
  });
25
- const callOfferCache = config.callOfferCache ||
26
- new NodeCache({
27
- stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
28
- useClones: false
53
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
54
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
55
+ useClones: false
29
56
  });
30
- const placeholderResendCache = config.placeholderResendCache ||
31
- new NodeCache({
32
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
33
- useClones: false
57
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
58
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
59
+ useClones: false
34
60
  });
35
- let sendActiveReceipts = false;
36
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
37
- if (!authState.creds.me?.id) {
38
- throw new Boom("Not authenticated");
39
- }
40
- const pdoMessage = {
41
- historySyncOnDemandRequest: {
42
- chatJid: oldestMsgKey.remoteJid,
43
- oldestMsgFromMe: oldestMsgKey.fromMe,
44
- oldestMsgId: oldestMsgKey.id,
45
- oldestMsgTimestampMs: oldestMsgTimestamp,
46
- onDemandMsgCount: count
47
- },
48
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
49
- };
50
- return sendPeerDataOperationMessage(pdoMessage);
51
- };
52
- const requestPlaceholderResend = async (messageKey) => {
53
- if (!authState.creds.me?.id) {
54
- throw new Boom("Not authenticated");
55
- }
56
- if (placeholderResendCache.get(messageKey?.id)) {
57
- logger.debug({ messageKey }, "already requested resend");
58
- return;
59
- }
60
- else {
61
- placeholderResendCache.set(messageKey?.id, true);
62
- }
63
- await delay(5000);
64
- if (!placeholderResendCache.get(messageKey?.id)) {
65
- logger.debug({ messageKey }, "message received while resend requested");
66
- return "RESOLVED";
67
- }
68
- const pdoMessage = {
69
- placeholderMessageResendRequest: [
70
- {
71
- messageKey
61
+ let sendActiveReceipts = false;
62
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
63
+ const stanza = {
64
+ tag: 'ack',
65
+ attrs: {
66
+ id: attrs.id,
67
+ to: attrs.from,
68
+ class: tag
69
+ }
72
70
  }
73
- ],
74
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
75
- };
76
- setTimeout(() => {
77
- if (placeholderResendCache.get(messageKey?.id)) {
78
- logger.debug({ messageKey }, "PDO message without response after 15 seconds. Phone possibly offline");
79
- placeholderResendCache.del(messageKey?.id);
80
- }
81
- }, 15000);
82
- return sendPeerDataOperationMessage(pdoMessage);
83
- };
84
- const handleMexNewsletterNotification = async (node) => {
85
- const mexNode = getBinaryNodeChild(node, "mex");
86
- if (!mexNode?.content) {
87
- logger.warn({ node }, "Invalid mex newsletter notification");
88
- return;
89
- }
90
- let data;
91
- try {
92
- data = JSON.parse(mexNode.content.toString());
93
- }
94
- catch (error) {
95
- logger.error({ err: error, node }, "Failed to parse mex newsletter notification");
96
- return;
97
- }
98
- const operation = data?.operation;
99
- const updates = data?.updates;
100
- if (!updates || !operation) {
101
- logger.warn({ data }, "Invalid mex newsletter notification content");
102
- return;
103
- }
104
- logger.info({ operation, updates }, "got mex newsletter notification");
105
- switch (operation) {
106
- case "NotificationNewsletterUpdate":
107
- for (const update of updates) {
108
- if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
109
- ev.emit("newsletter-settings.update", {
110
- id: update.jid,
111
- update: update.settings
112
- });
113
- }
71
+ if (!!errorCode) {
72
+ stanza.attrs.error = errorCode.toString();
114
73
  }
115
- break;
116
- case "NotificationNewsletterAdminPromote":
117
- for (const update of updates) {
118
- if (update.jid && update.user) {
119
- ev.emit("newsletter-participants.update", {
120
- id: update.jid,
121
- author: node.attrs.from,
122
- user: update.user,
123
- new_role: "ADMIN",
124
- action: "promote"
125
- });
126
- }
74
+ if (!!attrs.participant) {
75
+ stanza.attrs.participant = attrs.participant;
127
76
  }
128
- break;
129
- default:
130
- logger.info({ operation, data }, "Unhandled mex newsletter notification");
131
- break;
132
- }
133
- };
134
- const handleNewsletterNotification = async (node) => {
135
- const from = node.attrs.from;
136
- const child = getAllBinaryNodeChildren(node)[0];
137
- const author = node.attrs.participant;
138
- logger.info({ from, child }, "got newsletter notification");
139
- switch (child.tag) {
140
- case "reaction":
141
- const reactionUpdate = {
142
- id: from,
143
- server_id: child.attrs.message_id,
144
- reaction: {
145
- code: getBinaryNodeChildString(child, "reaction"),
146
- count: 1
147
- }
148
- };
149
- ev.emit("newsletter.reaction", reactionUpdate);
150
- break;
151
- case "view":
152
- const viewUpdate = {
153
- id: from,
154
- server_id: child.attrs.message_id,
155
- count: parseInt(child.content?.toString() || "0", 10)
156
- };
157
- ev.emit("newsletter.view", viewUpdate);
158
- break;
159
- case "participant":
160
- const participantUpdate = {
161
- id: from,
162
- author,
163
- user: child.attrs.jid,
164
- action: child.attrs.action,
165
- new_role: child.attrs.role
166
- };
167
- ev.emit("newsletter-participants.update", participantUpdate);
168
- break;
169
- case "update":
170
- const settingsNode = getBinaryNodeChild(child, "settings");
171
- if (settingsNode) {
172
- const update = {};
173
- const nameNode = getBinaryNodeChild(settingsNode, "name");
174
- if (nameNode?.content)
175
- update.name = nameNode.content.toString();
176
- const descriptionNode = getBinaryNodeChild(settingsNode, "description");
177
- if (descriptionNode?.content)
178
- update.description = descriptionNode.content.toString();
179
- ev.emit("newsletter-settings.update", {
180
- id: from,
181
- update
182
- });
77
+ if (!!attrs.recipient) {
78
+ stanza.attrs.recipient = attrs.recipient;
183
79
  }
184
- break;
185
- case "message":
186
- const plaintextNode = getBinaryNodeChild(child, "plaintext");
187
- if (plaintextNode?.content) {
188
- try {
189
- const contentBuf = typeof plaintextNode.content === "string"
190
- ? Buffer.from(plaintextNode.content, "binary")
191
- : Buffer.from(plaintextNode.content);
192
- const messageProto = proto.Message.decode(contentBuf).toJSON();
193
- const fullMessage = proto.WebMessageInfo.fromObject({
194
- key: {
195
- remoteJid: from,
196
- id: child.attrs.message_id || child.attrs.server_id,
197
- fromMe: false
198
- },
199
- message: messageProto,
200
- messageTimestamp: +child.attrs.t
201
- }).toJSON();
202
- await upsertMessage(fullMessage, "append");
203
- logger.info("Processed plaintext newsletter message");
204
- }
205
- catch (error) {
206
- logger.error({ error }, "Failed to decode plaintext newsletter message");
207
- }
80
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
81
+ stanza.attrs.type = attrs.type;
208
82
  }
209
- break;
210
- default:
211
- logger.warn({ node }, "Unknown newsletter notification");
212
- break;
213
- }
214
- };
215
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
216
- const stanza = {
217
- tag: "ack",
218
- attrs: {
219
- id: attrs.id,
220
- to: attrs.from,
221
- class: tag
222
- }
223
- };
224
- if (!!errorCode) {
225
- stanza.attrs.error = errorCode.toString();
226
- }
227
- if (!!attrs.participant) {
228
- stanza.attrs.participant = attrs.participant;
229
- }
230
- if (!!attrs.recipient) {
231
- stanza.attrs.recipient = attrs.recipient;
232
- }
233
- if (!!attrs.type &&
234
- (tag !== "message" || getBinaryNodeChild({ tag, attrs, content }, "unavailable") || errorCode !== 0)) {
235
- stanza.attrs.type = attrs.type;
236
- }
237
- if (tag === "message" && getBinaryNodeChild({ tag, attrs, content }, "unavailable")) {
238
- stanza.attrs.from = authState.creds.me.id;
239
- }
240
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, "sent ack");
241
- await sendNode(stanza);
242
- };
243
- const rejectCall = async (callId, callFrom) => {
244
- const stanza = {
245
- tag: "call",
246
- attrs: {
247
- from: authState.creds.me.id,
248
- to: callFrom
249
- },
250
- content: [
251
- {
252
- tag: "reject",
253
- attrs: {
254
- "call-id": callId,
255
- "call-creator": callFrom,
256
- count: "0"
257
- },
258
- content: undefined
83
+ if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
84
+ stanza.attrs.from = authState.creds.me.id;
259
85
  }
260
- ]
86
+ logger.debug({
87
+ recv: {
88
+ tag,
89
+ attrs
90
+ },
91
+ sent: stanza.attrs }, 'sent ack');
92
+ await sendNode(stanza);
261
93
  };
262
- await query(stanza);
263
- };
264
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
265
- const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || "");
266
- const { key: msgKey } = fullMessage;
267
- const msgId = msgKey.id;
268
- if (messageRetryManager) {
269
- if (messageRetryManager.hasExceededMaxRetries(msgId)) {
270
- logger.debug({ msgId }, "reached retry limit with new retry manager, clearing");
271
- messageRetryManager.markRetryFailed(msgId);
272
- return;
273
- }
274
- const retryCount = messageRetryManager.incrementRetryCount(msgId);
275
- const key = `${msgId}:${msgKey?.participant}`;
276
- msgRetryCache.set(key, retryCount);
277
- }
278
- else {
279
- const key = `${msgId}:${msgKey?.participant}`;
280
- let retryCount = (await msgRetryCache.get(key)) || 0;
281
- if (retryCount >= maxMsgRetryCount) {
282
- logger.debug({ retryCount, msgId }, "reached retry limit, clearing");
283
- msgRetryCache.del(key);
284
- return;
285
- }
286
- retryCount += 1;
287
- await msgRetryCache.set(key, retryCount);
288
- }
289
- const key = `${msgId}:${msgKey?.participant}`;
290
- const retryCount = (await msgRetryCache.get(key)) || 1;
291
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
292
- const fromJid = node.attrs.from;
293
- let shouldRecreateSession = false;
294
- let recreateReason = "";
295
- if (enableAutoSessionRecreation && messageRetryManager) {
296
- try {
297
- const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
298
- const hasSession = await signalRepository.validateSession(fromJid);
299
- const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists);
300
- shouldRecreateSession = result.recreate;
301
- recreateReason = result.reason;
302
- if (shouldRecreateSession) {
303
- logger.debug({ fromJid, retryCount, reason: recreateReason }, "recreating session for retry");
304
- await authState.keys.set({ session: { [sessionId]: null } });
305
- forceIncludeKeys = true;
94
+ const offerCall = async (toJid, isVideo = false) => {
95
+ const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
96
+ const offerContent = [];
97
+ offerContent.push({
98
+ tag: 'audio',
99
+ attrs: {
100
+ enc: 'opus',
101
+ rate: '16000'
102
+ }, content: undefined
103
+ });
104
+ offerContent.push({
105
+ tag: 'audio',
106
+ attrs: {
107
+ enc: 'opus',
108
+ rate: '8000'
109
+ }, content: undefined
110
+ });
111
+ if (isVideo) {
112
+ offerContent.push({
113
+ tag: 'video',
114
+ attrs: {
115
+ orientation: '0',
116
+ 'screen_width': '1920',
117
+ 'screen_height': '1080',
118
+ 'device_orientation': '0',
119
+ enc: 'vp8',
120
+ dec: 'vp8',
121
+ }
122
+ });
306
123
  }
307
- }
308
- catch (error) {
309
- logger.warn({ error, fromJid }, "failed to check session recreation");
310
- }
311
- }
312
- if (retryCount <= 2) {
313
- if (messageRetryManager) {
314
- messageRetryManager.schedulePhoneRequest(msgId, async () => {
315
- try {
316
- const requestId = await requestPlaceholderResend(msgKey);
317
- logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
318
- }
319
- catch (error) {
320
- logger.warn({ error, msgId }, "failed to send scheduled phone request");
321
- }
124
+ offerContent.push({
125
+ tag: 'net',
126
+ attrs: {
127
+ medium: '3'
128
+ }, content: undefined
322
129
  });
323
- }
324
- else {
325
- const msgId = await requestPlaceholderResend(msgKey);
326
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
327
- }
328
- }
329
- const deviceIdentity = encodeSignedDeviceIdentity(account, true);
330
- await authState.keys.transaction(async () => {
331
- const receipt = {
332
- tag: "receipt",
333
- attrs: {
334
- id: msgId,
335
- type: "retry",
336
- to: node.attrs.from
337
- },
338
- content: [
339
- {
340
- tag: "retry",
130
+ offerContent.push({
131
+ tag: 'capability',
341
132
  attrs: {
342
- count: retryCount.toString(),
343
- id: node.attrs.id,
344
- t: node.attrs.t,
345
- v: "1",
346
- error: "0"
133
+ ver: '1'
134
+ }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
135
+ offerContent.push({
136
+ tag: 'encopt',
137
+ attrs: {
138
+ keygen: '2'
139
+ }, content: undefined
140
+ })
141
+ const encKey = (0, crypto_1.randomBytes)(32);
142
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
143
+ await assertSessions(devices, true);
144
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
145
+ call: {
146
+ callKey: encKey
347
147
  }
348
- },
349
- {
350
- tag: "registration",
351
- attrs: {},
352
- content: encodeBigEndian(authState.creds.registrationId)
353
- }
354
- ]
355
- };
356
- if (node.attrs.recipient) {
357
- receipt.attrs.recipient = node.attrs.recipient;
358
- }
359
- if (node.attrs.participant) {
360
- receipt.attrs.participant = node.attrs.participant;
361
- }
362
- if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
363
- const { update, preKeys } = await getNextPreKeys(authState, 1);
364
- const [keyId] = Object.keys(preKeys);
365
- const key = preKeys[+keyId];
366
- const content = receipt.content;
367
- content.push({
368
- tag: "keys",
369
- attrs: {},
370
- content: [
371
- { tag: "type", attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
372
- { tag: "identity", attrs: {}, content: identityKey.public },
373
- xmppPreKey(key, +keyId),
374
- xmppSignedPreKey(signedPreKey),
375
- { tag: "device-identity", attrs: {}, content: deviceIdentity }
376
- ]
377
148
  });
378
- ev.emit("creds.update", update);
379
- }
380
- await sendNode(receipt);
381
- logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt");
382
- }, authState?.creds?.me?.id || "sendRetryRequest");
383
- };
384
- const handleEncryptNotification = async (node) => {
385
- const from = node.attrs.from;
386
- if (from === S_WHATSAPP_NET) {
387
- const countChild = getBinaryNodeChild(node, "count");
388
- const count = +countChild.attrs.value;
389
- const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
390
- logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count");
391
- if (shouldUploadMorePreKeys) {
392
- await uploadPreKeys();
393
- }
394
- }
395
- else {
396
- const identityNode = getBinaryNodeChild(node, "identity");
397
- if (identityNode) {
398
- logger.info({ jid: from }, "identity changed");
399
- }
400
- else {
401
- logger.info({ node }, "unknown encrypt notification");
402
- }
403
- }
404
- };
405
- const handleGroupNotification = (fullNode, child, msg) => {
406
- const actingParticipantLid = fullNode.attrs.participant;
407
- const actingParticipantPn = fullNode.attrs.participant_pn;
408
- const affectedParticipantLid = getBinaryNodeChild(child, "participant")?.attrs?.jid || actingParticipantLid;
409
- const affectedParticipantPn = getBinaryNodeChild(child, "participant")?.attrs?.phone_number || actingParticipantPn;
410
- switch (child?.tag) {
411
- case "create":
412
- const metadata = extractGroupMetadata(child);
413
- msg.messageStubType = WAMessageStubType.GROUP_CREATE;
414
- msg.messageStubParameters = [metadata.subject];
415
- msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
416
- ev.emit("chats.upsert", [
417
- {
418
- id: metadata.id,
419
- name: metadata.subject,
420
- conversationTimestamp: metadata.creation
421
- }
422
- ]);
423
- ev.emit("groups.upsert", [
424
- {
425
- ...metadata,
426
- author: actingParticipantLid,
427
- authorPn: actingParticipantPn
428
- }
429
- ]);
430
- break;
431
- case "ephemeral":
432
- case "not_ephemeral":
433
- msg.message = {
434
- protocolMessage: {
435
- type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
436
- ephemeralExpiration: +(child.attrs.expiration || 0)
437
- }
149
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
150
+ if (shouldIncludeDeviceIdentity) {
151
+ offerContent.push({
152
+ tag: 'device-identity',
153
+ attrs: {},
154
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
155
+ });
156
+ }
157
+ const stanza = ({
158
+ tag: 'call',
159
+ attrs: {
160
+ to: toJid,
161
+ },
162
+ content: [{
163
+ tag: 'offer',
164
+ attrs: {
165
+ 'call-id': callId,
166
+ 'call-creator': authState.creds.me.id,
167
+ },
168
+ content: offerContent,
169
+ }],
170
+ });
171
+ await query(stanza);
172
+ return {
173
+ callId,
174
+ toJid,
175
+ isVideo,
438
176
  };
439
- break;
440
- case "modify":
441
- const oldNumber = getBinaryNodeChildren(child, "participant").map(p => p.attrs.jid);
442
- msg.messageStubParameters = oldNumber || [];
443
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
444
- break;
445
- case "promote":
446
- case "demote":
447
- case "remove":
448
- case "add":
449
- case "leave":
450
- const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
451
- msg.messageStubType = WAMessageStubType[stubType];
452
- const participants = getBinaryNodeChildren(child, "participant").map(({ attrs }) => {
453
- return {
454
- id: attrs.jid,
455
- phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
456
- lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
457
- admin: (attrs.type || null)
458
- };
177
+ };
178
+ const rejectCall = async (callId, callFrom) => {
179
+ const stanza = ({
180
+ tag: 'call',
181
+ attrs: {
182
+ from: authState.creds.me.id,
183
+ to: callFrom,
184
+ },
185
+ content: [{
186
+ tag: 'reject',
187
+ attrs: {
188
+ 'call-id': callId,
189
+ 'call-creator': callFrom,
190
+ count: '0',
191
+ },
192
+ content: undefined,
193
+ }],
459
194
  });
460
- if (participants.length === 1 &&
461
- (areJidsSameUser(participants[0].id, actingParticipantLid) ||
462
- areJidsSameUser(participants[0].id, actingParticipantPn)) &&
463
- child.tag === "remove") {
464
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
195
+ await query(stanza);
196
+ };
197
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
198
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
199
+ const { key: msgKey } = fullMessage;
200
+ const msgId = msgKey.id;
201
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
202
+ let retryCount = msgRetryCache.get(key) || 0;
203
+ if (retryCount >= maxMsgRetryCount) {
204
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
205
+ msgRetryCache.del(key);
206
+ return;
465
207
  }
466
- msg.messageStubParameters = participants.map(a => JSON.stringify(a));
467
- break;
468
- case "subject":
469
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
470
- msg.messageStubParameters = [child.attrs.subject];
471
- break;
472
- case "description":
473
- const description = getBinaryNodeChild(child, "body")?.content?.toString();
474
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
475
- msg.messageStubParameters = description ? [description] : undefined;
476
- break;
477
- case "announcement":
478
- case "not_announcement":
479
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
480
- msg.messageStubParameters = [child.tag === "announcement" ? "on" : "off"];
481
- break;
482
- case "locked":
483
- case "unlocked":
484
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
485
- msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"];
486
- break;
487
- case "invite":
488
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
489
- msg.messageStubParameters = [child.attrs.code];
490
- break;
491
- case "member_add_mode":
492
- const addMode = child.content;
493
- if (addMode) {
494
- msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
495
- msg.messageStubParameters = [addMode.toString()];
208
+ retryCount += 1;
209
+ msgRetryCache.set(key, retryCount);
210
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
211
+ if (retryCount === 1) {
212
+ //request a resend via phone
213
+ const msgId = await requestPlaceholderResend(msgKey);
214
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
496
215
  }
497
- break;
498
- case "membership_approval_mode":
499
- const approvalMode = getBinaryNodeChild(child, "group_join");
500
- if (approvalMode) {
501
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
502
- msg.messageStubParameters = [approvalMode.attrs.state];
216
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
217
+ await authState.keys.transaction(async () => {
218
+ const receipt = {
219
+ tag: 'receipt',
220
+ attrs: {
221
+ id: msgId,
222
+ type: 'retry',
223
+ to: node.attrs.from
224
+ },
225
+ content: [
226
+ {
227
+ tag: 'retry',
228
+ attrs: {
229
+ count: retryCount.toString(),
230
+ id: node.attrs.id,
231
+ t: node.attrs.t,
232
+ v: '1'
233
+ }
234
+ },
235
+ {
236
+ tag: 'registration',
237
+ attrs: {},
238
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
239
+ }
240
+ ]
241
+ };
242
+ if (node.attrs.recipient) {
243
+ receipt.attrs.recipient = node.attrs.recipient;
244
+ }
245
+ if (node.attrs.participant) {
246
+ receipt.attrs.participant = node.attrs.participant;
247
+ }
248
+ if (retryCount > 1 || forceIncludeKeys) {
249
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
250
+ const [keyId] = Object.keys(preKeys);
251
+ const key = preKeys[+keyId];
252
+ const content = receipt.content;
253
+ content.push({
254
+ tag: 'keys',
255
+ attrs: {},
256
+ content: [
257
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
258
+ { tag: 'identity', attrs: {}, content: identityKey.public },
259
+ (0, Utils_1.xmppPreKey)(key, +keyId),
260
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
261
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
262
+ ]
263
+ });
264
+ ev.emit('creds.update', update);
265
+ }
266
+ await sendNode(receipt);
267
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
268
+ });
269
+ };
270
+ const handleEncryptNotification = async (node) => {
271
+ const from = node.attrs.from;
272
+ if (from === WABinary_1.S_WHATSAPP_NET) {
273
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
274
+ const count = +countChild.attrs.value;
275
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
276
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
277
+ if (shouldUploadMorePreKeys) {
278
+ await uploadPreKeys();
279
+ }
503
280
  }
504
- break;
505
- case "created_membership_requests":
506
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
507
- msg.messageStubParameters = [
508
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
509
- "created",
510
- child.attrs.request_method
511
- ];
512
- break;
513
- case "revoked_membership_requests":
514
- const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
515
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
516
- msg.messageStubParameters = [
517
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
518
- isDenied ? "revoked" : "rejected"
519
- ];
520
- break;
521
- }
522
- };
523
- const processNotification = async (node) => {
524
- const result = {};
525
- const [child] = getAllBinaryNodeChildren(node);
526
- const nodeType = node.attrs.type;
527
- const from = jidNormalizedUser(node.attrs.from);
528
- switch (nodeType) {
529
- case "privacy_token":
530
- const tokenList = getBinaryNodeChildren(child, "token");
531
- for (const { attrs, content } of tokenList) {
532
- const jid = attrs.jid;
533
- ev.emit("chats.update", [
534
- {
535
- id: jid,
536
- tcToken: content
281
+ else {
282
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
283
+ if (identityNode) {
284
+ logger.info({ jid: from }, 'identity changed');
285
+ // not handling right now
286
+ // signal will override new identity anyway
287
+ }
288
+ else {
289
+ logger.info({ node }, 'unknown encrypt notification');
537
290
  }
538
- ]);
539
- logger.debug({ jid }, "got privacy token update");
540
291
  }
541
- break;
542
- case "newsletter":
543
- await handleNewsletterNotification(node);
544
- break;
545
- case "mex":
546
- await handleMexNewsletterNotification(node);
547
- break;
548
- case "w:gp2":
549
- handleGroupNotification(node, child, result);
550
- break;
551
- case "mediaretry":
552
- const event = decodeMediaRetryNode(node);
553
- ev.emit("messages.media-update", [event]);
554
- break;
555
- case "encrypt":
556
- await handleEncryptNotification(node);
557
- break;
558
- case "devices":
559
- const devices = getBinaryNodeChildren(child, "device");
560
- if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
561
- areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
562
- const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
563
- logger.info({ deviceData }, "my own devices changed");
292
+ };
293
+ const handleGroupNotification = (participant, child, msg) => {
294
+ var _a, _b, _c, _d;
295
+ const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
296
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
297
+ case 'create':
298
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
299
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
300
+ msg.messageStubParameters = [metadata.subject];
301
+ msg.key = { participant: metadata.owner };
302
+ ev.emit('chats.upsert', [{
303
+ id: metadata.id,
304
+ name: metadata.subject,
305
+ conversationTimestamp: metadata.creation,
306
+ }]);
307
+ ev.emit('groups.upsert', [{
308
+ ...metadata,
309
+ author: participant
310
+ }]);
311
+ break;
312
+ case 'ephemeral':
313
+ case 'not_ephemeral':
314
+ msg.message = {
315
+ protocolMessage: {
316
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
317
+ ephemeralExpiration: +(child.attrs.expiration || 0)
318
+ }
319
+ };
320
+ break;
321
+ case 'modify':
322
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
323
+ msg.messageStubParameters = oldNumber || [];
324
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
325
+ break;
326
+ case 'promote':
327
+ case 'demote':
328
+ case 'remove':
329
+ case 'add':
330
+ case 'leave':
331
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
332
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
333
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
334
+ if (participants.length === 1 &&
335
+ // if recv. "remove" message and sender removed themselves
336
+ // mark as left
337
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
338
+ child.tag === 'remove') {
339
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
340
+ }
341
+ msg.messageStubParameters = participants;
342
+ break;
343
+ case 'subject':
344
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
345
+ msg.messageStubParameters = [child.attrs.subject];
346
+ break;
347
+ case 'description':
348
+ const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
349
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
350
+ msg.messageStubParameters = description ? [description] : undefined;
351
+ break;
352
+ case 'announcement':
353
+ case 'not_announcement':
354
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
355
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
356
+ break;
357
+ case 'locked':
358
+ case 'unlocked':
359
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
360
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
361
+ break;
362
+ case 'invite':
363
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
364
+ msg.messageStubParameters = [child.attrs.code];
365
+ break;
366
+ case 'member_add_mode':
367
+ const addMode = child.content;
368
+ if (addMode) {
369
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
370
+ msg.messageStubParameters = [addMode.toString()];
371
+ }
372
+ break;
373
+ case 'membership_approval_mode':
374
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
375
+ if (approvalMode) {
376
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
377
+ msg.messageStubParameters = [approvalMode.attrs.state];
378
+ }
379
+ break;
380
+ case 'created_membership_requests':
381
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
382
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
383
+ break;
384
+ case 'revoked_membership_requests':
385
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
386
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
387
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
388
+ break;
389
+ break;
390
+ default:
391
+ // console.log("BAILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
564
392
  }
565
- break;
566
- case "server_sync":
567
- const update = getBinaryNodeChild(node, "collection");
568
- if (update) {
569
- const name = update.attrs.name;
570
- await resyncAppState([name], false);
393
+ };
394
+ const handleNewsletterNotification = (id, node) => {
395
+ const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
396
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
397
+ const serverId = message.attrs.server_id;
398
+ const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
399
+ const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
400
+ if (reactionsList) {
401
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
402
+ if (reactions.length === 0) {
403
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
404
+ }
405
+ reactions.forEach(item => {
406
+ var _a, _b;
407
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { code: (_a = item.attrs) === null || _a === void 0 ? void 0 : _a.code, count: +((_b = item.attrs) === null || _b === void 0 ? void 0 : _b.count) } });
408
+ });
571
409
  }
572
- break;
573
- case "picture":
574
- const setPicture = getBinaryNodeChild(node, "set");
575
- const delPicture = getBinaryNodeChild(node, "delete");
576
- ev.emit("contacts.update", [
577
- {
578
- id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || "",
579
- imgUrl: setPicture ? "changed" : "removed"
580
- }
581
- ]);
582
- if (isJidGroup(from)) {
583
- const node = setPicture || delPicture;
584
- result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
585
- if (setPicture) {
586
- result.messageStubParameters = [setPicture.attrs.id];
587
- }
588
- result.participant = node?.attrs.author;
589
- result.key = {
590
- ...(result.key || {}),
591
- participant: setPicture?.attrs.author
592
- };
410
+ if (viewsList.length) {
411
+ viewsList.forEach(item => {
412
+ ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
413
+ });
593
414
  }
594
- break;
595
- case "account_sync":
596
- if (child.tag === "disappearing_mode") {
597
- const newDuration = +child.attrs.duration;
598
- const timestamp = +child.attrs.t;
599
- logger.info({ newDuration }, "updated account disappearing mode");
600
- ev.emit("creds.update", {
601
- accountSettings: {
602
- ...authState.creds.accountSettings,
603
- defaultDisappearingMode: {
604
- ephemeralExpiration: newDuration,
605
- ephemeralSettingTimestamp: timestamp
606
- }
415
+ };
416
+ const handleMexNewsletterNotification = (id, node) => {
417
+ var _a;
418
+ const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
419
+ const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
420
+ let contentPath;
421
+ if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
422
+ let action;
423
+ if (operation === Types_1.MexOperations.PROMOTE) {
424
+ action = 'promote';
425
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
607
426
  }
608
- });
427
+ if (operation === Types_1.MexOperations.DEMOTE) {
428
+ action = 'demote';
429
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
430
+ }
431
+ ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
609
432
  }
610
- else if (child.tag === "blocklist") {
611
- const blocklists = getBinaryNodeChildren(child, "item");
612
- for (const { attrs } of blocklists) {
613
- const blocklist = [attrs.jid];
614
- const type = attrs.action === "block" ? "add" : "remove";
615
- ev.emit("blocklist.update", { blocklist, type });
616
- }
433
+ if (operation === Types_1.MexOperations.UPDATE) {
434
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
435
+ ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
617
436
  }
618
- break;
619
- case "link_code_companion_reg":
620
- const linkCodeCompanionReg = getBinaryNodeChild(node, "link_code_companion_reg");
621
- const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, "link_code_pairing_ref"));
622
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, "primary_identity_pub"));
623
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, "link_code_pairing_wrapped_primary_ephemeral_pub"));
624
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
625
- const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
626
- const random = randomBytes(32);
627
- const linkCodeSalt = randomBytes(32);
628
- const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
629
- salt: linkCodeSalt,
630
- info: "link_code_pairing_key_bundle_encryption_key"
631
- });
632
- const encryptPayload = Buffer.concat([
633
- Buffer.from(authState.creds.signedIdentityKey.public),
634
- primaryIdentityPublicKey,
635
- random
636
- ]);
637
- const encryptIv = randomBytes(12);
638
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
639
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
640
- const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
641
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
642
- authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: "adv_secret" })).toString("base64");
643
- await query({
644
- tag: "iq",
645
- attrs: {
646
- to: S_WHATSAPP_NET,
647
- type: "set",
648
- id: sock.generateMessageTag(),
649
- xmlns: "md"
650
- },
651
- content: [
652
- {
653
- tag: "link_code_companion_reg",
654
- attrs: {
655
- jid: authState.creds.me.id,
656
- stage: "companion_finish"
657
- },
658
- content: [
659
- {
660
- tag: "link_code_pairing_wrapped_key_bundle",
661
- attrs: {},
662
- content: encryptedPayload
663
- },
664
- {
665
- tag: "companion_identity_public",
666
- attrs: {},
667
- content: authState.creds.signedIdentityKey.public
668
- },
669
- {
670
- tag: "link_code_pairing_ref",
671
- attrs: {},
672
- content: ref
437
+ };
438
+ const processNotification = async (node) => {
439
+ var _a, _b;
440
+ const result = {};
441
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
442
+ const nodeType = node.attrs.type;
443
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
444
+ switch (nodeType) {
445
+ case 'privacy_token':
446
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
447
+ for (const { attrs, content } of tokenList) {
448
+ const jid = attrs.jid;
449
+ ev.emit('chats.update', [
450
+ {
451
+ id: jid,
452
+ tcToken: content
453
+ }
454
+ ]);
455
+ logger.debug({ jid }, 'got privacy token update');
673
456
  }
674
- ]
675
- }
676
- ]
677
- });
678
- authState.creds.registered = true;
679
- ev.emit("creds.update", authState.creds);
680
- }
681
- if (Object.keys(result).length) {
682
- return result;
683
- }
684
- };
685
- async function decipherLinkPublicKey(data) {
686
- const buffer = toRequiredBuffer(data);
687
- const salt = buffer.slice(0, 32);
688
- const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
689
- const iv = buffer.slice(32, 48);
690
- const payload = buffer.slice(48, 80);
691
- return aesDecryptCTR(payload, secretKey, iv);
692
- }
693
- function toRequiredBuffer(data) {
694
- if (data === undefined) {
695
- throw new Boom("Invalid buffer", { statusCode: 400 });
696
- }
697
- return data instanceof Buffer ? data : Buffer.from(data);
698
- }
699
- const willSendMessageAgain = async (id, participant) => {
700
- const key = `${id}:${participant}`;
701
- const retryCount = (await msgRetryCache.get(key)) || 0;
702
- return retryCount < maxMsgRetryCount;
703
- };
704
- const updateSendMessageAgainCount = async (id, participant) => {
705
- const key = `${id}:${participant}`;
706
- const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
707
- await msgRetryCache.set(key, newValue);
708
- };
709
- const sendMessagesAgain = async (key, ids, retryNode) => {
710
- const remoteJid = key.remoteJid;
711
- const participant = key.participant || remoteJid;
712
- const retryCount = +retryNode.attrs.count || 1;
713
- const msgs = [];
714
- for (const id of ids) {
715
- let msg;
716
- if (messageRetryManager) {
717
- const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
718
- if (cachedMsg) {
719
- msg = cachedMsg.message;
720
- logger.debug({ jid: remoteJid, id }, "found message in retry cache");
721
- messageRetryManager.markRetrySuccess(id);
722
- }
723
- }
724
- if (!msg) {
725
- msg = await getMessage({ ...key, id });
726
- if (msg) {
727
- logger.debug({ jid: remoteJid, id }, "found message via getMessage");
728
- if (messageRetryManager) {
729
- messageRetryManager.markRetrySuccess(id);
730
- }
457
+ break;
458
+ case 'newsletter':
459
+ handleNewsletterNotification(node.attrs.from, child);
460
+ break;
461
+ case 'mex':
462
+ handleMexNewsletterNotification(node.attrs.from, child);
463
+ break;
464
+ case 'w:gp2':
465
+ handleGroupNotification(node.attrs.participant, child, result);
466
+ break;
467
+ case 'mediaretry':
468
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
469
+ ev.emit('messages.media-update', [event]);
470
+ break;
471
+ case 'encrypt':
472
+ await handleEncryptNotification(node);
473
+ break;
474
+ case 'devices':
475
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
476
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
477
+ const deviceJids = devices.map(d => d.attrs.jid);
478
+ logger.info({ deviceJids }, 'got my own devices');
479
+ }
480
+ break;
481
+ case 'server_sync':
482
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
483
+ if (update) {
484
+ const name = update.attrs.name;
485
+ await resyncAppState([name], false);
486
+ }
487
+ break;
488
+ case 'picture':
489
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
490
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
491
+ ev.emit('contacts.update', [{
492
+ id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
493
+ imgUrl: setPicture ? 'changed' : 'removed'
494
+ }]);
495
+ if ((0, WABinary_1.isJidGroup)(from)) {
496
+ const node = setPicture || delPicture;
497
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
498
+ if (setPicture) {
499
+ result.messageStubParameters = [setPicture.attrs.id];
500
+ }
501
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
502
+ result.key = {
503
+ ...result.key || {},
504
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
505
+ };
506
+ }
507
+ break;
508
+ case 'account_sync':
509
+ if (child.tag === 'disappearing_mode') {
510
+ const newDuration = +child.attrs.duration;
511
+ const timestamp = +child.attrs.t;
512
+ logger.info({ newDuration }, 'updated account disappearing mode');
513
+ ev.emit('creds.update', {
514
+ accountSettings: {
515
+ ...authState.creds.accountSettings,
516
+ defaultDisappearingMode: {
517
+ ephemeralExpiration: newDuration,
518
+ ephemeralSettingTimestamp: timestamp,
519
+ },
520
+ }
521
+ });
522
+ }
523
+ else if (child.tag === 'blocklist') {
524
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
525
+ for (const { attrs } of blocklists) {
526
+ const blocklist = [attrs.jid];
527
+ const type = (attrs.action === 'block') ? 'add' : 'remove';
528
+ ev.emit('blocklist.update', { blocklist, type });
529
+ }
530
+ }
531
+ break;
532
+ case 'link_code_companion_reg':
533
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
534
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
535
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
536
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
537
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
538
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
539
+ const random = (0, crypto_1.randomBytes)(32);
540
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
541
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
542
+ salt: linkCodeSalt,
543
+ info: 'link_code_pairing_key_bundle_encryption_key'
544
+ });
545
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
546
+ const encryptIv = (0, crypto_1.randomBytes)(12);
547
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
548
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
549
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
550
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
551
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
552
+ await query({
553
+ tag: 'iq',
554
+ attrs: {
555
+ to: WABinary_1.S_WHATSAPP_NET,
556
+ type: 'set',
557
+ id: sock.generateMessageTag(),
558
+ xmlns: 'md'
559
+ },
560
+ content: [
561
+ {
562
+ tag: 'link_code_companion_reg',
563
+ attrs: {
564
+ jid: authState.creds.me.id,
565
+ stage: 'companion_finish',
566
+ },
567
+ content: [
568
+ {
569
+ tag: 'link_code_pairing_wrapped_key_bundle',
570
+ attrs: {},
571
+ content: encryptedPayload
572
+ },
573
+ {
574
+ tag: 'companion_identity_public',
575
+ attrs: {},
576
+ content: authState.creds.signedIdentityKey.public
577
+ },
578
+ {
579
+ tag: 'link_code_pairing_ref',
580
+ attrs: {},
581
+ content: ref
582
+ }
583
+ ]
584
+ }
585
+ ]
586
+ });
587
+ authState.creds.registered = true;
588
+ ev.emit('creds.update', authState.creds);
731
589
  }
732
- }
733
- msgs.push(msg);
734
- }
735
- const sendToAll = !jidDecode(participant)?.device;
736
- let shouldRecreateSession = false;
737
- let recreateReason = "";
738
- if (enableAutoSessionRecreation && messageRetryManager) {
739
- try {
740
- const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
741
- const hasSession = await signalRepository.validateSession(participant);
742
- const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists);
743
- shouldRecreateSession = result.recreate;
744
- recreateReason = result.reason;
745
- if (shouldRecreateSession) {
746
- logger.debug({ participant, retryCount, reason: recreateReason }, "recreating session for outgoing retry");
747
- await authState.keys.set({ session: { [sessionId]: null } });
590
+ if (Object.keys(result).length) {
591
+ return result;
748
592
  }
749
- }
750
- catch (error) {
751
- logger.warn({ error, participant }, "failed to check session recreation for outgoing retry");
752
- }
753
- }
754
- await assertSessions([participant]);
755
- if (isJidGroup(remoteJid)) {
756
- await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } });
593
+ };
594
+ async function decipherLinkPublicKey(data) {
595
+ const buffer = toRequiredBuffer(data);
596
+ const salt = buffer.slice(0, 32);
597
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
598
+ const iv = buffer.slice(32, 48);
599
+ const payload = buffer.slice(48, 80);
600
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
757
601
  }
758
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, "forced new session for retry recp");
759
- for (const [i, msg] of msgs.entries()) {
760
- if (!ids[i])
761
- continue;
762
- if (msg && (await willSendMessageAgain(ids[i], participant))) {
763
- updateSendMessageAgainCount(ids[i], participant);
764
- const msgRelayOpts = { messageId: ids[i] };
765
- if (sendToAll) {
766
- msgRelayOpts.useUserDevicesCache = false;
767
- }
768
- else {
769
- msgRelayOpts.participant = {
770
- jid: participant,
771
- count: +retryNode.attrs.count
772
- };
602
+ function toRequiredBuffer(data) {
603
+ if (data === undefined) {
604
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
773
605
  }
774
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
775
- }
776
- else {
777
- logger.debug({ jid: key.remoteJid, id: ids[i] }, "recv retry request, but message not available");
778
- }
606
+ return data instanceof Buffer ? data : Buffer.from(data);
779
607
  }
780
- };
781
- const handleReceipt = async (node) => {
782
- const { attrs, content } = node;
783
- const isLid = attrs.from.includes("lid");
784
- const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
785
- const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
786
- const fromMe = !attrs.recipient || ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe);
787
- const key = {
788
- remoteJid,
789
- id: "",
790
- fromMe,
791
- participant: attrs.participant
608
+ const willSendMessageAgain = (id, participant) => {
609
+ const key = `${id}:${participant}`;
610
+ const retryCount = msgRetryCache.get(key) || 0;
611
+ return retryCount < maxMsgRetryCount;
792
612
  };
793
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
794
- logger.debug({ remoteJid }, "ignoring receipt from jid");
795
- await sendMessageAck(node);
796
- return;
797
- }
798
- const ids = [attrs.id];
799
- if (Array.isArray(content)) {
800
- const items = getBinaryNodeChildren(content[0], "item");
801
- ids.push(...items.map(i => i.attrs.id));
802
- }
803
- try {
804
- await Promise.all([
805
- processingMutex.mutex(async () => {
806
- const status = getStatusFromReceiptType(attrs.type);
807
- if (typeof status !== "undefined" &&
808
- (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
809
- if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
810
- if (attrs.participant) {
811
- const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? "receiptTimestamp" : "readTimestamp";
812
- ev.emit("message-receipt.update", ids.map(id => ({
813
- key: { ...key, id },
814
- receipt: {
815
- userJid: jidNormalizedUser(attrs.participant),
816
- [updateKey]: +attrs.t
817
- }
818
- })));
819
- }
820
- }
821
- else {
822
- ev.emit("messages.update", ids.map(id => ({
823
- key: { ...key, id },
824
- update: { status }
825
- })));
826
- }
827
- }
828
- if (attrs.type === "retry") {
829
- key.participant = key.participant || attrs.from;
830
- const retryNode = getBinaryNodeChild(node, "retry");
831
- if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
832
- if (key.fromMe) {
833
- try {
834
- updateSendMessageAgainCount(ids[0], key.participant);
835
- logger.debug({ attrs, key }, "recv retry request");
836
- await sendMessagesAgain(key, ids, retryNode);
613
+ const updateSendMessageAgainCount = (id, participant) => {
614
+ const key = `${id}:${participant}`;
615
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
616
+ msgRetryCache.set(key, newValue);
617
+ };
618
+ const sendMessagesAgain = async (key, ids, retryNode) => {
619
+ var _a;
620
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
621
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
622
+ const remoteJid = key.remoteJid;
623
+ const participant = key.participant || remoteJid;
624
+ // if it's the primary jid sending the request
625
+ // just re-send the message to everyone
626
+ // prevents the first message decryption failure
627
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
628
+ await assertSessions([participant], true);
629
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
630
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
631
+ }
632
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
633
+ for (const [i, msg] of msgs.entries()) {
634
+ if (msg) {
635
+ updateSendMessageAgainCount(ids[i], participant);
636
+ const msgRelayOpts = { messageId: ids[i] };
637
+ if (sendToAll) {
638
+ msgRelayOpts.useUserDevicesCache = false;
837
639
  }
838
- catch (error) {
839
- logger.error({ key, ids, trace: error instanceof Error ? error.stack : "Unknown error" }, "error in sending message again");
640
+ else {
641
+ msgRelayOpts.participant = {
642
+ jid: participant,
643
+ count: +retryNode.attrs.count
644
+ };
840
645
  }
841
- }
842
- else {
843
- logger.info({ attrs, key }, "recv retry for not fromMe message");
844
- }
646
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
845
647
  }
846
648
  else {
847
- logger.info({ attrs, key }, "will not send message again, as sent too many times");
649
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
848
650
  }
849
- }
850
- })
851
- ]);
852
- }
853
- finally {
854
- await sendMessageAck(node);
855
- }
856
- };
857
- const handleNotification = async (node) => {
858
- const remoteJid = node.attrs.from;
859
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
860
- logger.debug({ remoteJid, id: node.attrs.id }, "ignored notification");
861
- await sendMessageAck(node);
862
- return;
863
- }
864
- try {
865
- await Promise.all([
866
- processingMutex.mutex(async () => {
867
- const msg = await processNotification(node);
868
- if (msg) {
869
- const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
870
- const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
871
- msg.key = {
872
- remoteJid,
873
- fromMe,
874
- participant: node.attrs.participant,
875
- participantAlt,
876
- addressingMode,
877
- id: node.attrs.id,
878
- ...(msg.key || {})
879
- };
880
- msg.participant ?? (msg.participant = node.attrs.participant);
881
- msg.messageTimestamp = +node.attrs.t;
882
- const fullMsg = proto.WebMessageInfo.fromObject(msg);
883
- await upsertMessage(fullMsg, "append");
884
- }
885
- })
886
- ]);
887
- }
888
- finally {
889
- await sendMessageAck(node);
890
- }
891
- };
892
- const handleMessage = async (node) => {
893
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
894
- logger.debug({ key: node.attrs.key }, "ignored message");
895
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
896
- return;
897
- }
898
- const encNode = getBinaryNodeChild(node, "enc");
899
- if (encNode && encNode.attrs.type === "msmsg") {
900
- logger.debug({ key: node.attrs.key }, "ignored msmsg");
901
- await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
902
- return;
903
- }
904
- const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || "", signalRepository, logger);
905
- const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
906
- if (!!alt) {
907
- const altServer = jidDecode(alt)?.server;
908
- const primaryJid = msg.key.participant || msg.key.remoteJid;
909
- if (altServer === "lid") {
910
- if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
911
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
912
- await signalRepository.migrateSession(primaryJid, alt);
913
651
  }
914
- }
915
- else {
916
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
917
- await signalRepository.migrateSession(alt, primaryJid);
918
- }
919
- }
920
- if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
921
- messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
922
- logger.debug({
923
- jid: msg.key.remoteJid,
924
- id: msg.key.id
925
- }, "Added message to recent cache for retry receipts");
926
- }
927
- try {
928
- await processingMutex.mutex(async () => {
929
- await decrypt();
930
- if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
931
- if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
932
- return sendMessageAck(node, NACK_REASONS.ParsingError);
933
- }
934
- const errorMessage = msg?.messageStubParameters?.[0] || "";
935
- const isPreKeyError = errorMessage.includes("PreKey");
936
- logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
937
- retryMutex.mutex(async () => {
938
- try {
939
- if (!ws.isOpen) {
940
- logger.debug({ node }, "Connection closed, skipping retry");
652
+ };
653
+ const handleReceipt = async (node) => {
654
+ var _a, _b;
655
+ const { attrs, content } = node;
656
+ const isLid = attrs.from.includes('lid');
657
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, isLid ? (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.lid : (_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
658
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
659
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
660
+ const key = {
661
+ remoteJid,
662
+ id: '',
663
+ fromMe,
664
+ participant: attrs.participant
665
+ };
666
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
667
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
668
+ await sendMessageAck(node);
669
+ return;
670
+ }
671
+ const ids = [attrs.id];
672
+ if (Array.isArray(content)) {
673
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
674
+ ids.push(...items.map(i => i.attrs.id));
675
+ }
676
+ try {
677
+ await Promise.all([
678
+ processingMutex.mutex(async () => {
679
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
680
+ if (typeof status !== 'undefined' &&
681
+ (
682
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
683
+ // or another device of ours has read some messages
684
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
685
+ !isNodeFromMe)) {
686
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
687
+ if (attrs.participant) {
688
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
689
+ ev.emit('message-receipt.update', ids.map(id => ({
690
+ key: { ...key, id },
691
+ receipt: {
692
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
693
+ [updateKey]: +attrs.t
694
+ }
695
+ })));
696
+ }
697
+ }
698
+ else {
699
+ ev.emit('messages.update', ids.map(id => ({
700
+ key: { ...key, id },
701
+ update: { status }
702
+ })));
703
+ }
704
+ }
705
+ if (attrs.type === 'retry') {
706
+ // correctly set who is asking for the retry
707
+ key.participant = key.participant || attrs.from;
708
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
709
+ if (willSendMessageAgain(ids[0], key.participant)) {
710
+ if (key.fromMe) {
711
+ try {
712
+ logger.debug({ attrs, key }, 'recv retry request');
713
+ await sendMessagesAgain(key, ids, retryNode);
714
+ }
715
+ catch (error) {
716
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
717
+ }
718
+ }
719
+ else {
720
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
721
+ }
722
+ }
723
+ else {
724
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
725
+ }
726
+ }
727
+ })
728
+ ]);
729
+ }
730
+ finally {
731
+ await sendMessageAck(node);
732
+ }
733
+ };
734
+ const handleNotification = async (node) => {
735
+ const remoteJid = node.attrs.from;
736
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
737
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
738
+ await sendMessageAck(node);
739
+ return;
740
+ }
741
+ try {
742
+ await Promise.all([
743
+ processingMutex.mutex(async () => {
744
+ var _a;
745
+ const msg = await processNotification(node);
746
+ if (msg) {
747
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
748
+ msg.key = {
749
+ remoteJid,
750
+ fromMe,
751
+ participant: node.attrs.participant,
752
+ id: node.attrs.id,
753
+ ...(msg.key || {})
754
+ };
755
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
756
+ msg.messageTimestamp = +node.attrs.t;
757
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
758
+ await upsertMessage(fullMsg, 'append');
759
+ }
760
+ })
761
+ ]);
762
+ }
763
+ finally {
764
+ await sendMessageAck(node);
765
+ }
766
+ };
767
+ const handleMessage = async (node) => {
768
+ var _a, _b, _c;
769
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
770
+ logger.debug({ key: node.attrs.key }, 'ignored message');
771
+ await sendMessageAck(node);
772
+ return;
773
+ }
774
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
775
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
776
+ if (encNode && encNode.attrs.type === 'msmsg') {
777
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
778
+ await sendMessageAck(node);
779
+ return;
780
+ }
781
+ let response;
782
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
783
+ await sendMessageAck(node);
784
+ const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
785
+ response = await requestPlaceholderResend(key);
786
+ if (response === 'RESOLVED') {
941
787
  return;
942
- }
943
- if (isPreKeyError) {
944
- logger.info({ error: errorMessage }, "PreKey error detected, uploading and retrying");
945
- try {
946
- logger.debug("Uploading pre-keys for error recovery");
947
- await uploadPreKeys(5);
948
- logger.debug("Waiting for server to process new pre-keys");
949
- await delay(1000);
950
- }
951
- catch (uploadErr) {
952
- logger.error({ uploadErr }, "Pre-key upload failed, proceeding with retry anyway");
953
- }
954
- }
955
- const encNode = getBinaryNodeChild(node, "enc");
956
- await sendRetryRequest(node, !encNode);
957
- if (retryRequestDelayMs) {
958
- await delay(retryRequestDelayMs);
959
- }
960
788
  }
961
- catch (err) {
962
- logger.error({ err, isPreKeyError }, "Failed to handle retry, attempting basic retry");
963
- try {
964
- const encNode = getBinaryNodeChild(node, "enc");
965
- await sendRetryRequest(node, !encNode);
966
- }
967
- catch (retryErr) {
968
- logger.error({ retryErr }, "Failed to send retry after error handling");
969
- }
789
+ logger.debug('received unavailable message, acked and requested resend from phone');
790
+ }
791
+ else {
792
+ if (placeholderResendCache.get(node.attrs.id)) {
793
+ placeholderResendCache.del(node.attrs.id);
970
794
  }
971
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
972
- });
795
+ }
796
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
797
+ if (response && ((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
798
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
799
+ }
800
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
801
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
802
+ }
803
+ try {
804
+ await Promise.all([
805
+ processingMutex.mutex(async () => {
806
+ var _a, _b, _c, _d, _e, _f;
807
+ await decrypt();
808
+ // message failed to decrypt
809
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
810
+ if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
811
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
812
+ }
813
+ retryMutex.mutex(async () => {
814
+ if (ws.isOpen) {
815
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
816
+ return;
817
+ }
818
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
819
+ await sendRetryRequest(node, !encNode);
820
+ if (retryRequestDelayMs) {
821
+ await (0, Utils_1.delay)(retryRequestDelayMs);
822
+ }
823
+ }
824
+ else {
825
+ logger.debug({ node }, 'connection closed, ignoring retry req');
826
+ }
827
+ });
828
+ }
829
+ else {
830
+ // no type in the receipt => message delivered
831
+ let type = undefined;
832
+ if ((_b = msg.key.participant) === null || _b === void 0 ? void 0 : _b.endsWith('@lid')) {
833
+ msg.key.participant = node.attrs.participant_pn || authState.creds.me.id;
834
+ }
835
+ if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid) && ((_f = (_e = (_d = (_c = msg.message) === null || _c === void 0 ? void 0 : _c.extendedTextMessage) === null || _d === void 0 ? void 0 : _d.contextInfo) === null || _e === void 0 ? void 0 : _e.participant) === null || _f === void 0 ? void 0 : _f.endsWith('@lid'))) {
836
+ if (msg.message.extendedTextMessage.contextInfo) {
837
+ const metadata = await groupMetadata(msg.key.remoteJid);
838
+ const sender = msg.message.extendedTextMessage.contextInfo.participant;
839
+ const found = metadata.participants.find(p => p.id === sender);
840
+ msg.message.extendedTextMessage.contextInfo.participant = (found === null || found === void 0 ? void 0 : found.jid) || sender;
841
+ }
842
+ }
843
+ if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
844
+ msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
845
+ }
846
+ let participant = msg.key.participant;
847
+ if (category === 'peer') { // special peer message
848
+ type = 'peer_msg';
849
+ }
850
+ else if (msg.key.fromMe) { // message was sent by us from a different device
851
+ type = 'sender';
852
+ // need to specially handle this case
853
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
854
+ participant = author;
855
+ }
856
+ }
857
+ else if (!sendActiveReceipts) {
858
+ type = 'inactive';
859
+ }
860
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
861
+ // send ack for history message
862
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
863
+ if (isAnyHistoryMsg) {
864
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
865
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
866
+ }
867
+ }
868
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
869
+ await sendMessageAck(node);
870
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
871
+ })
872
+ ]);
873
+ }
874
+ catch (error) {
875
+ logger.error({ error, node }, 'error in handling message');
876
+ }
877
+ };
878
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
879
+ var _a;
880
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
881
+ throw new boom_1.Boom('Not authenticated');
882
+ }
883
+ const pdoMessage = {
884
+ historySyncOnDemandRequest: {
885
+ chatJid: oldestMsgKey.remoteJid,
886
+ oldestMsgFromMe: oldestMsgKey.fromMe,
887
+ oldestMsgId: oldestMsgKey.id,
888
+ oldestMsgTimestampMs: oldestMsgTimestamp,
889
+ onDemandMsgCount: count
890
+ },
891
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
892
+ };
893
+ return sendPeerDataOperationMessage(pdoMessage);
894
+ };
895
+ const requestPlaceholderResend = async (messageKey) => {
896
+ var _a;
897
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
898
+ throw new boom_1.Boom('Not authenticated');
899
+ }
900
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
901
+ logger.debug({ messageKey }, 'already requested resend');
902
+ return;
973
903
  }
974
904
  else {
975
- let type = undefined;
976
- let participant = msg.key.participant;
977
- if (category === "peer") {
978
- type = "peer_msg";
979
- }
980
- else if (msg.key.fromMe) {
981
- type = "sender";
982
- if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
983
- participant = author;
905
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
906
+ }
907
+ await (0, Utils_1.delay)(5000);
908
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
909
+ logger.debug({ messageKey }, 'message received while resend requested');
910
+ return 'RESOLVED';
911
+ }
912
+ const pdoMessage = {
913
+ placeholderMessageResendRequest: [{
914
+ messageKey
915
+ }],
916
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
917
+ };
918
+ setTimeout(() => {
919
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
920
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
921
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
984
922
  }
985
- }
986
- else if (!sendActiveReceipts) {
987
- type = "inactive";
988
- }
989
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
990
- const isAnyHistoryMsg = getHistoryMsg(msg.message);
991
- if (isAnyHistoryMsg) {
992
- const jid = jidNormalizedUser(msg.key.remoteJid);
993
- await sendReceipt(jid, undefined, [msg.key.id], "hist_sync");
994
- }
923
+ }, 15000);
924
+ return sendPeerDataOperationMessage(pdoMessage);
925
+ };
926
+ const handleCall = async (node) => {
927
+ const { attrs } = node;
928
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
929
+ const callId = infoChild.attrs['call-id'];
930
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
931
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
932
+ const call = {
933
+ chatId: attrs.from,
934
+ from,
935
+ id: callId,
936
+ date: new Date(+attrs.t * 1000),
937
+ offline: !!attrs.offline,
938
+ status,
939
+ };
940
+ if (status === 'offer') {
941
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
942
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
943
+ call.groupJid = infoChild.attrs['group-jid'];
944
+ callOfferCache.set(call.id, call);
995
945
  }
996
- cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
997
- await upsertMessage(msg, node.attrs.offline ? "append" : "notify");
998
- });
999
- }
1000
- catch (error) {
1001
- logger.error({ error, node: binaryNodeToString(node) }, "error in handling message");
1002
- }
1003
- };
1004
- const handleCall = async (node) => {
1005
- const { attrs } = node;
1006
- const [infoChild] = getAllBinaryNodeChildren(node);
1007
- const status = getCallStatusFromNode(infoChild);
1008
- if (!infoChild) {
1009
- throw new Boom("Missing call info in call node");
1010
- }
1011
- const callId = infoChild.attrs["call-id"];
1012
- const from = infoChild.attrs.from || infoChild.attrs["call-creator"];
1013
- const call = {
1014
- chatId: attrs.from,
1015
- from,
1016
- id: callId,
1017
- date: new Date(+attrs.t * 1000),
1018
- offline: !!attrs.offline,
1019
- status
946
+ const existingCall = callOfferCache.get(call.id);
947
+ // use existing call info to populate this event
948
+ if (existingCall) {
949
+ call.isVideo = existingCall.isVideo;
950
+ call.isGroup = existingCall.isGroup;
951
+ }
952
+ // delete data once call has ended
953
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
954
+ callOfferCache.del(call.id);
955
+ }
956
+ ev.emit('call', [call]);
957
+ await sendMessageAck(node);
1020
958
  };
1021
- if (status === "offer") {
1022
- call.isVideo = !!getBinaryNodeChild(infoChild, "video");
1023
- call.isGroup = infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"];
1024
- call.groupJid = infoChild.attrs["group-jid"];
1025
- await callOfferCache.set(call.id, call);
1026
- }
1027
- const existingCall = await callOfferCache.get(call.id);
1028
- if (existingCall) {
1029
- call.isVideo = existingCall.isVideo;
1030
- call.isGroup = existingCall.isGroup;
1031
- }
1032
- if (status === "reject" || status === "accept" || status === "timeout" || status === "terminate") {
1033
- await callOfferCache.del(call.id);
1034
- }
1035
- ev.emit("call", [call]);
1036
- await sendMessageAck(node);
1037
- };
1038
- const handleBadAck = async ({ attrs }) => {
1039
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1040
- if (attrs.error) {
1041
- logger.warn({ attrs }, "received error in ack");
1042
- ev.emit("messages.update", [
1043
- {
1044
- key,
1045
- update: {
1046
- status: WAMessageStatus.ERROR,
1047
- messageStubParameters: [attrs.error]
1048
- }
959
+ const handleBadAck = async ({ attrs }) => {
960
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
961
+ // current hypothesis is that if pash is sent in the ack
962
+ // it means -- the message hasn't reached all devices yet
963
+ // we'll retry sending the message here
964
+ if (attrs.phash) {
965
+ logger.info({ attrs }, 'received phash in ack, resending message...');
966
+ const cacheKey = `${key.remoteJid}:${key.id}`;
967
+ if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
968
+ logger.warn({ attrs }, 'reached max retry count, not sending message again');
969
+ msgRetryCache.del(cacheKey);
970
+ return;
971
+ }
972
+ const retryCount = msgRetryCache.get(cacheKey) || 0;
973
+ const msg = await getMessage(key);
974
+ if (msg) {
975
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
976
+ msgRetryCache.set(cacheKey, retryCount + 1);
977
+ }
978
+ else {
979
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
980
+ }
1049
981
  }
1050
- ]);
1051
- }
1052
- };
1053
- const processNodeWithBuffer = async (node, identifier, exec) => {
1054
- ev.buffer();
1055
- await execTask();
1056
- ev.flush();
1057
- function execTask() {
1058
- return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1059
- }
1060
- };
1061
- const makeOfflineNodeProcessor = () => {
1062
- const nodeProcessorMap = new Map([
1063
- ["message", handleMessage],
1064
- ["call", handleCall],
1065
- ["receipt", handleReceipt],
1066
- ["notification", handleNotification]
1067
- ]);
1068
- const nodes = [];
1069
- let isProcessing = false;
1070
- const enqueue = (type, node) => {
1071
- nodes.push({ type, node });
1072
- if (isProcessing) {
1073
- return;
1074
- }
1075
- isProcessing = true;
1076
- const promise = async () => {
1077
- while (nodes.length && ws.isOpen) {
1078
- const { type, node } = nodes.shift();
1079
- const nodeProcessor = nodeProcessorMap.get(type);
1080
- if (!nodeProcessor) {
1081
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), "processing offline node");
1082
- continue;
1083
- }
1084
- await nodeProcessor(node);
982
+ // error in acknowledgement,
983
+ // device could not display the message
984
+ if (attrs.error) {
985
+ logger.warn({ attrs }, 'received error in ack');
986
+ ev.emit('messages.update', [
987
+ {
988
+ key,
989
+ update: {
990
+ status: Types_1.WAMessageStatus.ERROR,
991
+ messageStubParameters: [
992
+ attrs.error
993
+ ]
994
+ }
995
+ }
996
+ ]);
1085
997
  }
1086
- isProcessing = false;
1087
- };
1088
- promise().catch(error => onUnexpectedError(error, "processing offline nodes"));
1089
998
  };
1090
- return { enqueue };
1091
- };
1092
- const offlineNodeProcessor = makeOfflineNodeProcessor();
1093
- const processNode = (type, node, identifier, exec) => {
1094
- const isOffline = !!node.attrs.offline;
1095
- if (isOffline) {
1096
- offlineNodeProcessor.enqueue(type, node);
1097
- }
1098
- else {
1099
- processNodeWithBuffer(node, identifier, exec);
1100
- }
1101
- };
1102
- ws.on("CB:message", (node) => {
1103
- processNode("message", node, "processing message", handleMessage);
1104
- });
1105
- ws.on("CB:call", async (node) => {
1106
- processNode("call", node, "handling call", handleCall);
1107
- });
1108
- ws.on("CB:receipt", node => {
1109
- processNode("receipt", node, "handling receipt", handleReceipt);
1110
- });
1111
- ws.on("CB:notification", async (node) => {
1112
- processNode("notification", node, "handling notification", handleNotification);
1113
- });
1114
- ws.on("CB:ack,class:message", (node) => {
1115
- handleBadAck(node).catch(error => onUnexpectedError(error, "handling bad ack"));
1116
- });
1117
- ev.on("call", ([call]) => {
1118
- if (!call) {
1119
- return;
1120
- }
1121
- if (call.status === "timeout" || (call.status === "offer" && call.isGroup)) {
1122
- const msg = {
1123
- key: {
1124
- remoteJid: call.chatId,
1125
- id: call.id,
1126
- fromMe: false
1127
- },
1128
- messageTimestamp: unixTimestampSeconds(call.date)
1129
- };
1130
- if (call.status === "timeout") {
1131
- if (call.isGroup) {
1132
- msg.messageStubType = call.isVideo
1133
- ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1134
- : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
999
+ /// processes a node with the given function
1000
+ /// and adds the task to the existing buffer if we're buffering events
1001
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1002
+ ev.buffer();
1003
+ await execTask();
1004
+ ev.flush();
1005
+ function execTask() {
1006
+ return exec(node, false)
1007
+ .catch(err => onUnexpectedError(err, identifier));
1008
+ }
1009
+ };
1010
+ const makeOfflineNodeProcessor = () => {
1011
+ const nodeProcessorMap = new Map([
1012
+ ['message', handleMessage],
1013
+ ['call', handleCall],
1014
+ ['receipt', handleReceipt],
1015
+ ['notification', handleNotification]
1016
+ ]);
1017
+ const nodes = [];
1018
+ let isProcessing = false;
1019
+ const enqueue = (type, node) => {
1020
+ nodes.push({ type, node });
1021
+ if (isProcessing) {
1022
+ return;
1023
+ }
1024
+ isProcessing = true;
1025
+ const promise = async () => {
1026
+ while (nodes.length && ws.isOpen) {
1027
+ const { type, node } = nodes.shift();
1028
+ const nodeProcessor = nodeProcessorMap.get(type);
1029
+ if (!nodeProcessor) {
1030
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1031
+ continue;
1032
+ }
1033
+ await nodeProcessor(node);
1034
+ }
1035
+ isProcessing = false;
1036
+ };
1037
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1038
+ };
1039
+ return { enqueue };
1040
+ };
1041
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1042
+ const processNode = (type, node, identifier, exec) => {
1043
+ const isOffline = !!node.attrs.offline;
1044
+ if (isOffline) {
1045
+ offlineNodeProcessor.enqueue(type, node);
1135
1046
  }
1136
1047
  else {
1137
- msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1048
+ processNodeWithBuffer(node, identifier, exec);
1138
1049
  }
1139
- }
1140
- else {
1141
- msg.message = { call: { callKey: Buffer.from(call.id) } };
1142
- }
1143
- const protoMsg = proto.WebMessageInfo.fromObject(msg);
1144
- upsertMessage(protoMsg, call.offline ? "append" : "notify");
1145
- }
1146
- });
1147
- ev.on("connection.update", ({ isOnline }) => {
1148
- if (typeof isOnline !== "undefined") {
1149
- sendActiveReceipts = isOnline;
1150
- logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1151
- }
1152
- });
1153
- return {
1154
- ...sock,
1155
- sendMessageAck,
1156
- sendRetryRequest,
1157
- rejectCall,
1158
- fetchMessageHistory,
1159
- requestPlaceholderResend,
1160
- messageRetryManager
1161
- };
1050
+ };
1051
+ // recv a message
1052
+ ws.on('CB:message', (node) => {
1053
+ processNode('message', node, 'processing message', handleMessage);
1054
+ });
1055
+ ws.on('CB:call', async (node) => {
1056
+ processNode('call', node, 'handling call', handleCall);
1057
+ });
1058
+ ws.on('CB:receipt', node => {
1059
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1060
+ });
1061
+ ws.on('CB:notification', async (node) => {
1062
+ processNode('notification', node, 'handling notification', handleNotification);
1063
+ });
1064
+ ws.on('CB:ack,class:message', (node) => {
1065
+ handleBadAck(node)
1066
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
1067
+ });
1068
+ ev.on('call', ([call]) => {
1069
+ // missed call + group call notification message generation
1070
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1071
+ const msg = {
1072
+ key: {
1073
+ remoteJid: call.chatId,
1074
+ id: call.id,
1075
+ fromMe: false
1076
+ },
1077
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
1078
+ };
1079
+ if (call.status === 'timeout') {
1080
+ if (call.isGroup) {
1081
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1082
+ }
1083
+ else {
1084
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1085
+ }
1086
+ }
1087
+ else {
1088
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1089
+ }
1090
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1091
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1092
+ }
1093
+ });
1094
+ ev.on('connection.update', ({ isOnline }) => {
1095
+ if (typeof isOnline !== 'undefined') {
1096
+ sendActiveReceipts = isOnline;
1097
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1098
+ }
1099
+ });
1100
+ return {
1101
+ ...sock,
1102
+ sendMessageAck,
1103
+ sendRetryRequest,
1104
+ rejectCall,
1105
+ offerCall,
1106
+ fetchMessageHistory,
1107
+ requestPlaceholderResend,
1108
+ };
1162
1109
  };
1163
- //=======================================================//
1110
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;