gifted-baileys 1.5.4 → 1.5.6

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 (252) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +88 -969
  3. package/WAProto/index.d.ts +1256 -13195
  4. package/WAProto/index.js +74730 -125106
  5. package/package.json +9 -27
  6. package/src/Defaults/baileys-version.json +3 -0
  7. package/{lib → src}/Defaults/index.js +14 -7
  8. package/src/Defaults/index.ts +131 -0
  9. package/src/README.md +1 -0
  10. package/src/Signal/libsignal.js +180 -0
  11. package/src/Signal/libsignal.ts +141 -0
  12. package/src/Socket/Client/abstract-socket-client.ts +19 -0
  13. package/{lib → src}/Socket/Client/index.js +3 -2
  14. package/src/Socket/Client/index.ts +3 -0
  15. package/src/Socket/Client/mobile-socket-client.js +78 -0
  16. package/src/Socket/Client/mobile-socket-client.ts +66 -0
  17. package/src/Socket/Client/web-socket-client.js +75 -0
  18. package/src/Socket/Client/web-socket-client.ts +57 -0
  19. package/{lib → src}/Socket/business.js +33 -28
  20. package/src/Socket/business.ts +281 -0
  21. package/{lib → src}/Socket/chats.js +176 -174
  22. package/src/Socket/chats.ts +1030 -0
  23. package/{lib → src}/Socket/groups.js +68 -80
  24. package/src/Socket/groups.ts +356 -0
  25. package/{lib → src}/Socket/index.js +1 -4
  26. package/src/Socket/index.ts +13 -0
  27. package/{lib → src}/Socket/messages-recv.js +211 -378
  28. package/src/Socket/messages-recv.ts +985 -0
  29. package/{lib → src}/Socket/messages-send.js +177 -452
  30. package/src/Socket/messages-send.ts +871 -0
  31. package/{lib → src}/Socket/newsletter.js +98 -107
  32. package/src/Socket/newsletter.ts +282 -0
  33. package/{lib → src}/Socket/registration.js +48 -56
  34. package/src/Socket/registration.ts +250 -0
  35. package/{lib → src}/Socket/socket.js +77 -77
  36. package/src/Socket/socket.ts +777 -0
  37. package/src/Store/index.ts +3 -0
  38. package/{lib → src}/Store/make-cache-manager-store.js +34 -25
  39. package/src/Store/make-cache-manager-store.ts +100 -0
  40. package/{lib → src}/Store/make-in-memory-store.js +32 -36
  41. package/src/Store/make-in-memory-store.ts +475 -0
  42. package/src/Store/make-ordered-dictionary.ts +86 -0
  43. package/{lib → src}/Store/object-repository.js +1 -1
  44. package/src/Store/object-repository.ts +32 -0
  45. package/src/Tests/test.app-state-sync.js +204 -0
  46. package/src/Tests/test.app-state-sync.ts +207 -0
  47. package/src/Tests/test.event-buffer.js +270 -0
  48. package/src/Tests/test.event-buffer.ts +319 -0
  49. package/src/Tests/test.key-store.js +76 -0
  50. package/src/Tests/test.key-store.ts +92 -0
  51. package/src/Tests/test.libsignal.js +141 -0
  52. package/src/Tests/test.libsignal.ts +186 -0
  53. package/src/Tests/test.media-download.js +93 -0
  54. package/src/Tests/test.media-download.ts +76 -0
  55. package/src/Tests/test.messages.js +33 -0
  56. package/src/Tests/test.messages.ts +37 -0
  57. package/src/Tests/utils.js +34 -0
  58. package/src/Tests/utils.ts +36 -0
  59. package/src/Types/Auth.ts +113 -0
  60. package/src/Types/Call.ts +15 -0
  61. package/src/Types/Chat.ts +106 -0
  62. package/{lib/Types/Contact.d.ts → src/Types/Contact.ts} +9 -8
  63. package/src/Types/Events.ts +93 -0
  64. package/src/Types/GroupMetadata.ts +53 -0
  65. package/src/Types/Label.ts +36 -0
  66. package/{lib/Types/LabelAssociation.d.ts → src/Types/LabelAssociation.ts} +22 -16
  67. package/src/Types/Message.ts +288 -0
  68. package/src/Types/Newsletter.ts +98 -0
  69. package/src/Types/Product.ts +85 -0
  70. package/src/Types/Signal.ts +68 -0
  71. package/{lib/Types/Socket.d.ts → src/Types/Socket.ts} +68 -61
  72. package/src/Types/State.ts +29 -0
  73. package/src/Types/index.ts +59 -0
  74. package/{lib → src}/Utils/auth-utils.js +90 -73
  75. package/src/Utils/auth-utils.ts +222 -0
  76. package/src/Utils/baileys-event-stream.js +92 -0
  77. package/src/Utils/baileys-event-stream.ts +66 -0
  78. package/{lib → src}/Utils/business.js +43 -15
  79. package/src/Utils/business.ts +275 -0
  80. package/{lib → src}/Utils/chat-utils.js +94 -87
  81. package/src/Utils/chat-utils.ts +860 -0
  82. package/{lib → src}/Utils/crypto.js +2 -4
  83. package/src/Utils/crypto.ts +131 -0
  84. package/src/Utils/decode-wa-message.js +211 -0
  85. package/src/Utils/decode-wa-message.ts +228 -0
  86. package/{lib → src}/Utils/event-buffer.js +13 -4
  87. package/src/Utils/event-buffer.ts +613 -0
  88. package/{lib → src}/Utils/generics.js +86 -67
  89. package/src/Utils/generics.ts +434 -0
  90. package/{lib → src}/Utils/history.js +39 -13
  91. package/src/Utils/history.ts +112 -0
  92. package/src/Utils/index.ts +17 -0
  93. package/{lib → src}/Utils/link-preview.js +54 -17
  94. package/src/Utils/link-preview.ts +122 -0
  95. package/src/Utils/logger.ts +3 -0
  96. package/src/Utils/lt-hash.ts +61 -0
  97. package/{lib → src}/Utils/make-mutex.js +13 -4
  98. package/src/Utils/make-mutex.ts +44 -0
  99. package/{lib → src}/Utils/messages-media.js +255 -193
  100. package/src/Utils/messages-media.ts +847 -0
  101. package/{lib → src}/Utils/messages.js +118 -588
  102. package/src/Utils/messages.ts +956 -0
  103. package/src/Utils/noise-handler.ts +197 -0
  104. package/{lib → src}/Utils/process-message.js +30 -27
  105. package/src/Utils/process-message.ts +414 -0
  106. package/{lib → src}/Utils/signal.js +42 -25
  107. package/src/Utils/signal.ts +177 -0
  108. package/{lib → src}/Utils/use-multi-file-auth-state.js +28 -27
  109. package/src/Utils/use-multi-file-auth-state.ts +90 -0
  110. package/{lib → src}/Utils/validate-connection.js +9 -40
  111. package/src/Utils/validate-connection.ts +238 -0
  112. package/src/WABinary/constants.ts +42 -0
  113. package/src/WABinary/decode.ts +265 -0
  114. package/{lib → src}/WABinary/encode.js +10 -16
  115. package/src/WABinary/encode.ts +236 -0
  116. package/src/WABinary/generic-utils.ts +121 -0
  117. package/src/WABinary/index.ts +5 -0
  118. package/src/WABinary/jid-utils.ts +68 -0
  119. package/src/WABinary/types.ts +17 -0
  120. package/src/WAM/BinaryInfo.ts +12 -0
  121. package/src/WAM/constants.ts +15382 -0
  122. package/src/WAM/encode.ts +174 -0
  123. package/src/WAM/index.ts +3 -0
  124. package/{lib → src}/index.js +0 -1
  125. package/src/index.ts +13 -0
  126. package/README.md +0 -1645
  127. package/lib/Defaults/baileys-version.json +0 -3
  128. package/lib/Defaults/index.d.ts +0 -284
  129. package/lib/Signal/libsignal.d.ts +0 -3
  130. package/lib/Signal/libsignal.js +0 -161
  131. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -15
  132. package/lib/Socket/Client/index.d.ts +0 -2
  133. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -12
  134. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  135. package/lib/Socket/Client/types.d.ts +0 -17
  136. package/lib/Socket/Client/types.js +0 -13
  137. package/lib/Socket/Client/websocket.d.ts +0 -12
  138. package/lib/Socket/Client/websocket.js +0 -62
  139. package/lib/Socket/business.d.ts +0 -170
  140. package/lib/Socket/chats.d.ts +0 -81
  141. package/lib/Socket/groups.d.ts +0 -115
  142. package/lib/Socket/index.d.ts +0 -172
  143. package/lib/Socket/messages-recv.d.ts +0 -158
  144. package/lib/Socket/messages-send.d.ts +0 -155
  145. package/lib/Socket/newsletter.d.ts +0 -132
  146. package/lib/Socket/registration.d.ts +0 -264
  147. package/lib/Socket/socket.d.ts +0 -44
  148. package/lib/Socket/usync.d.ts +0 -37
  149. package/lib/Socket/usync.js +0 -70
  150. package/lib/Store/index.d.ts +0 -3
  151. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  152. package/lib/Store/make-in-memory-store.d.ts +0 -118
  153. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  154. package/lib/Store/object-repository.d.ts +0 -10
  155. package/lib/Types/Auth.d.ts +0 -109
  156. package/lib/Types/Call.d.ts +0 -13
  157. package/lib/Types/Chat.d.ts +0 -107
  158. package/lib/Types/Events.d.ts +0 -172
  159. package/lib/Types/GroupMetadata.d.ts +0 -56
  160. package/lib/Types/Label.d.ts +0 -46
  161. package/lib/Types/Message.d.ts +0 -433
  162. package/lib/Types/Newsletter.d.ts +0 -92
  163. package/lib/Types/Product.d.ts +0 -78
  164. package/lib/Types/Signal.d.ts +0 -57
  165. package/lib/Types/State.d.ts +0 -27
  166. package/lib/Types/USync.d.ts +0 -25
  167. package/lib/Types/USync.js +0 -2
  168. package/lib/Types/index.d.ts +0 -66
  169. package/lib/Utils/auth-utils.d.ts +0 -18
  170. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  171. package/lib/Utils/baileys-event-stream.js +0 -63
  172. package/lib/Utils/business.d.ts +0 -22
  173. package/lib/Utils/chat-utils.d.ts +0 -70
  174. package/lib/Utils/crypto.d.ts +0 -40
  175. package/lib/Utils/decode-wa-message.d.ts +0 -36
  176. package/lib/Utils/decode-wa-message.js +0 -226
  177. package/lib/Utils/event-buffer.d.ts +0 -35
  178. package/lib/Utils/generics.d.ts +0 -88
  179. package/lib/Utils/history.d.ts +0 -19
  180. package/lib/Utils/index.d.ts +0 -17
  181. package/lib/Utils/link-preview.d.ts +0 -21
  182. package/lib/Utils/logger.d.ts +0 -2
  183. package/lib/Utils/lt-hash.d.ts +0 -12
  184. package/lib/Utils/make-mutex.d.ts +0 -7
  185. package/lib/Utils/messages-media.d.ts +0 -113
  186. package/lib/Utils/messages.d.ts +0 -77
  187. package/lib/Utils/noise-handler.d.ts +0 -20
  188. package/lib/Utils/process-message.d.ts +0 -41
  189. package/lib/Utils/signal.d.ts +0 -33
  190. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  191. package/lib/Utils/validate-connection.d.ts +0 -11
  192. package/lib/WABinary/constants.d.ts +0 -27
  193. package/lib/WABinary/decode.d.ts +0 -6
  194. package/lib/WABinary/encode.d.ts +0 -2
  195. package/lib/WABinary/generic-utils.d.ts +0 -14
  196. package/lib/WABinary/index.d.ts +0 -5
  197. package/lib/WABinary/jid-utils.d.ts +0 -31
  198. package/lib/WABinary/types.d.ts +0 -18
  199. package/lib/WAM/BinaryInfo.d.ts +0 -8
  200. package/lib/WAM/constants.d.ts +0 -38
  201. package/lib/WAM/encode.d.ts +0 -2
  202. package/lib/WAM/index.d.ts +0 -3
  203. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  204. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  205. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  206. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  207. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  208. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  209. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  210. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  211. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  212. package/lib/WAUSync/Protocols/index.js +0 -20
  213. package/lib/WAUSync/USyncQuery.d.ts +0 -26
  214. package/lib/WAUSync/USyncQuery.js +0 -79
  215. package/lib/WAUSync/USyncUser.d.ts +0 -10
  216. package/lib/WAUSync/USyncUser.js +0 -22
  217. package/lib/WAUSync/index.d.ts +0 -3
  218. package/lib/WAUSync/index.js +0 -19
  219. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
  220. /package/{lib → src}/Socket/Client/abstract-socket-client.js +0 -0
  221. /package/{lib → src}/Store/index.js +0 -0
  222. /package/{lib → src}/Store/make-ordered-dictionary.js +0 -0
  223. /package/{lib → src}/Types/Auth.js +0 -0
  224. /package/{lib → src}/Types/Call.js +0 -0
  225. /package/{lib → src}/Types/Chat.js +0 -0
  226. /package/{lib → src}/Types/Contact.js +0 -0
  227. /package/{lib → src}/Types/Events.js +0 -0
  228. /package/{lib → src}/Types/GroupMetadata.js +0 -0
  229. /package/{lib → src}/Types/Label.js +0 -0
  230. /package/{lib → src}/Types/LabelAssociation.js +0 -0
  231. /package/{lib → src}/Types/Message.js +0 -0
  232. /package/{lib → src}/Types/Newsletter.js +0 -0
  233. /package/{lib → src}/Types/Product.js +0 -0
  234. /package/{lib → src}/Types/Signal.js +0 -0
  235. /package/{lib → src}/Types/Socket.js +0 -0
  236. /package/{lib → src}/Types/State.js +0 -0
  237. /package/{lib → src}/Types/index.js +0 -0
  238. /package/{lib → src}/Utils/index.js +0 -0
  239. /package/{lib → src}/Utils/logger.js +0 -0
  240. /package/{lib → src}/Utils/lt-hash.js +0 -0
  241. /package/{lib → src}/Utils/noise-handler.js +0 -0
  242. /package/{lib → src}/WABinary/constants.js +0 -0
  243. /package/{lib → src}/WABinary/decode.js +0 -0
  244. /package/{lib → src}/WABinary/generic-utils.js +0 -0
  245. /package/{lib → src}/WABinary/index.js +0 -0
  246. /package/{lib → src}/WABinary/jid-utils.js +0 -0
  247. /package/{lib → src}/WABinary/types.js +0 -0
  248. /package/{lib → src}/WAM/BinaryInfo.js +0 -0
  249. /package/{lib → src}/WAM/constants.js +0 -0
  250. /package/{lib → src}/WAM/encode.js +0 -0
  251. /package/{lib → src}/WAM/index.js +0 -0
  252. /package/{lib → src}/gifted +0 -0
@@ -1,4 +1,13 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
@@ -19,7 +28,7 @@ const messages_send_1 = require("./messages-send");
19
28
  const makeMessagesRecvSocket = (config) => {
20
29
  const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
21
30
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
22
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, sendPeerDataOperationMessage, createParticipantNodes } = sock;
31
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, createParticipantNodes } = sock;
23
32
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
24
33
  const retryMutex = (0, make_mutex_1.makeMutex)();
25
34
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
@@ -30,39 +39,32 @@ const makeMessagesRecvSocket = (config) => {
30
39
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
31
40
  useClones: false
32
41
  });
33
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
34
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
35
- useClones: false
36
- });
37
42
  let sendActiveReceipts = false;
38
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
43
+ const sendMessageAck = (_a) => __awaiter(void 0, [_a], void 0, function* ({ tag, attrs, content }) {
39
44
  const stanza = {
40
45
  tag: 'ack',
41
46
  attrs: {
42
47
  id: attrs.id,
43
48
  to: attrs.from,
44
- class: tag
49
+ class: tag,
45
50
  }
46
51
  };
47
- if (!!errorCode) {
48
- stanza.attrs.error = errorCode.toString();
49
- }
50
52
  if (!!attrs.participant) {
51
53
  stanza.attrs.participant = attrs.participant;
52
54
  }
53
55
  if (!!attrs.recipient) {
54
56
  stanza.attrs.recipient = attrs.recipient;
55
57
  }
56
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
58
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable'))) {
57
59
  stanza.attrs.type = attrs.type;
58
60
  }
59
61
  if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
60
62
  stanza.attrs.from = authState.creds.me.id;
61
63
  }
62
64
  logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
63
- await sendNode(stanza);
64
- };
65
- const offerCall = async (toJid, isVideo = false) => {
65
+ yield sendNode(stanza);
66
+ });
67
+ const offerCall = (toJid_1, ...args_1) => __awaiter(void 0, [toJid_1, ...args_1], void 0, function* (toJid, isVideo = false) {
66
68
  const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
67
69
  const offerContent = [];
68
70
  offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined });
@@ -78,9 +80,9 @@ const makeMessagesRecvSocket = (config) => {
78
80
  offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
79
81
  offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined });
80
82
  const encKey = (0, crypto_1.randomBytes)(32);
81
- const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
82
- await assertSessions(devices, true);
83
- const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
83
+ const devices = (yield getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
84
+ yield assertSessions(devices, true);
85
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = yield createParticipantNodes(devices, {
84
86
  call: {
85
87
  callKey: new Uint8Array(encKey)
86
88
  }
@@ -108,13 +110,13 @@ const makeMessagesRecvSocket = (config) => {
108
110
  content: offerContent,
109
111
  }],
110
112
  });
111
- await query(stanza);
113
+ yield query(stanza);
112
114
  return {
113
115
  id: callId,
114
116
  to: toJid
115
117
  };
116
- };
117
- const rejectCall = async (callId, callFrom) => {
118
+ });
119
+ const rejectCall = (callId, callFrom) => __awaiter(void 0, void 0, void 0, function* () {
118
120
  const stanza = ({
119
121
  tag: 'call',
120
122
  attrs: {
@@ -131,29 +133,21 @@ const makeMessagesRecvSocket = (config) => {
131
133
  content: undefined,
132
134
  }],
133
135
  });
134
- await query(stanza);
135
- };
136
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
137
- const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
138
- const { key: msgKey } = fullMessage;
139
- const msgId = msgKey.id;
140
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
141
- let retryCount = msgRetryCache.get(key) || 0;
136
+ yield query(stanza);
137
+ });
138
+ const sendRetryRequest = (node_1, ...args_1) => __awaiter(void 0, [node_1, ...args_1], void 0, function* (node, forceIncludeKeys = false) {
139
+ const msgId = node.attrs.id;
140
+ let retryCount = msgRetryCache.get(msgId) || 0;
142
141
  if (retryCount >= maxMsgRetryCount) {
143
142
  logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
144
- msgRetryCache.del(key);
143
+ msgRetryCache.del(msgId);
145
144
  return;
146
145
  }
147
146
  retryCount += 1;
148
- msgRetryCache.set(key, retryCount);
147
+ msgRetryCache.set(msgId, retryCount);
149
148
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
150
- if (retryCount === 1) {
151
- //request a resend via phone
152
- const msgId = await requestPlaceholderResend(msgKey);
153
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
154
- }
155
149
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
156
- await authState.keys.transaction(async () => {
150
+ yield authState.keys.transaction(() => __awaiter(void 0, void 0, void 0, function* () {
157
151
  const receipt = {
158
152
  tag: 'receipt',
159
153
  attrs: {
@@ -185,7 +179,7 @@ const makeMessagesRecvSocket = (config) => {
185
179
  receipt.attrs.participant = node.attrs.participant;
186
180
  }
187
181
  if (retryCount > 1 || forceIncludeKeys) {
188
- const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
182
+ const { update, preKeys } = yield (0, Utils_1.getNextPreKeys)(authState, 1);
189
183
  const [keyId] = Object.keys(preKeys);
190
184
  const key = preKeys[+keyId];
191
185
  const content = receipt.content;
@@ -202,11 +196,11 @@ const makeMessagesRecvSocket = (config) => {
202
196
  });
203
197
  ev.emit('creds.update', update);
204
198
  }
205
- await sendNode(receipt);
199
+ yield sendNode(receipt);
206
200
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
207
- });
208
- };
209
- const handleEncryptNotification = async (node) => {
201
+ }));
202
+ });
203
+ const handleEncryptNotification = (node) => __awaiter(void 0, void 0, void 0, function* () {
210
204
  const from = node.attrs.from;
211
205
  if (from === WABinary_1.S_WHATSAPP_NET) {
212
206
  const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
@@ -214,7 +208,7 @@ const makeMessagesRecvSocket = (config) => {
214
208
  const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
215
209
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
216
210
  if (shouldUploadMorePreKeys) {
217
- await uploadPreKeys();
211
+ yield uploadPreKeys();
218
212
  }
219
213
  }
220
214
  else {
@@ -228,10 +222,8 @@ const makeMessagesRecvSocket = (config) => {
228
222
  logger.info({ node }, 'unknown encrypt notification');
229
223
  }
230
224
  }
231
- };
225
+ });
232
226
  const handleGroupNotification = (participant, child, msg) => {
233
- var _a, _b, _c, _d;
234
- 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;
235
227
  switch (child === null || child === void 0 ? void 0 : child.tag) {
236
228
  case 'create':
237
229
  const metadata = (0, groups_1.extractGroupMetadata)(child);
@@ -243,10 +235,7 @@ const makeMessagesRecvSocket = (config) => {
243
235
  name: metadata.subject,
244
236
  conversationTimestamp: metadata.creation,
245
237
  }]);
246
- ev.emit('groups.upsert', [{
247
- ...metadata,
248
- author: participant
249
- }]);
238
+ ev.emit('groups.upsert', [Object.assign(Object.assign({}, metadata), { author: participant })]);
250
239
  break;
251
240
  case 'ephemeral':
252
241
  case 'not_ephemeral':
@@ -257,11 +246,6 @@ const makeMessagesRecvSocket = (config) => {
257
246
  }
258
247
  };
259
248
  break;
260
- case 'modify':
261
- const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
262
- msg.messageStubParameters = oldNumber || [];
263
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
264
- break;
265
249
  case 'promote':
266
250
  case 'demote':
267
251
  case 'remove':
@@ -283,11 +267,6 @@ const makeMessagesRecvSocket = (config) => {
283
267
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
284
268
  msg.messageStubParameters = [child.attrs.subject];
285
269
  break;
286
- case 'description':
287
- 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();
288
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
289
- msg.messageStubParameters = description ? [description] : undefined;
290
- break;
291
270
  case 'announcement':
292
271
  case 'not_announcement':
293
272
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
@@ -316,18 +295,9 @@ const makeMessagesRecvSocket = (config) => {
316
295
  msg.messageStubParameters = [approvalMode.attrs.state];
317
296
  }
318
297
  break;
319
- case 'created_membership_requests':
320
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
321
- msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
322
- break;
323
- case 'revoked_membership_requests':
324
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
325
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
326
- msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
327
- break;
328
298
  }
329
299
  };
330
- const processNotification = async (node) => {
300
+ const processNotification = (node) => __awaiter(void 0, void 0, void 0, function* () {
331
301
  var _a, _b, _c;
332
302
  const result = {};
333
303
  const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
@@ -355,7 +325,10 @@ const makeMessagesRecvSocket = (config) => {
355
325
  ev.emit('messages.media-update', [event]);
356
326
  break;
357
327
  case 'encrypt':
358
- await handleEncryptNotification(node);
328
+ yield handleEncryptNotification(node);
329
+ break;
330
+ case 'newsletter':
331
+ // TO DO
359
332
  break;
360
333
  case 'devices':
361
334
  const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
@@ -368,14 +341,14 @@ const makeMessagesRecvSocket = (config) => {
368
341
  const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
369
342
  if (update) {
370
343
  const name = update.attrs.name;
371
- await resyncAppState([name], false);
344
+ yield resyncAppState([name], false);
372
345
  }
373
346
  break;
374
347
  case 'picture':
375
348
  const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
376
349
  const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
377
350
  ev.emit('contacts.update', [{
378
- id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
351
+ id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.jid) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
379
352
  imgUrl: setPicture ? 'changed' : 'removed'
380
353
  }]);
381
354
  if ((0, WABinary_1.isJidGroup)(from)) {
@@ -385,10 +358,7 @@ const makeMessagesRecvSocket = (config) => {
385
358
  result.messageStubParameters = [setPicture.attrs.id];
386
359
  }
387
360
  result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
388
- result.key = {
389
- ...result.key || {},
390
- participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
391
- };
361
+ result.key = Object.assign(Object.assign({}, result.key || {}), { participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author });
392
362
  }
393
363
  break;
394
364
  case 'account_sync':
@@ -397,13 +367,10 @@ const makeMessagesRecvSocket = (config) => {
397
367
  const timestamp = +child.attrs.t;
398
368
  logger.info({ newDuration }, 'updated account disappearing mode');
399
369
  ev.emit('creds.update', {
400
- accountSettings: {
401
- ...authState.creds.accountSettings,
402
- defaultDisappearingMode: {
370
+ accountSettings: Object.assign(Object.assign({}, authState.creds.accountSettings), { defaultDisappearingMode: {
403
371
  ephemeralExpiration: newDuration,
404
372
  ephemeralSettingTimestamp: timestamp,
405
- },
406
- }
373
+ } })
407
374
  });
408
375
  }
409
376
  else if (child.tag === 'blocklist') {
@@ -420,7 +387,7 @@ const makeMessagesRecvSocket = (config) => {
420
387
  const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
421
388
  const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
422
389
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
423
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
390
+ const codePairingPublicKey = decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
424
391
  const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
425
392
  const random = (0, crypto_1.randomBytes)(32);
426
393
  const linkCodeSalt = (0, crypto_1.randomBytes)(32);
@@ -435,7 +402,7 @@ const makeMessagesRecvSocket = (config) => {
435
402
  const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
436
403
  const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
437
404
  authState.creds.advSecretKey = (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' }).toString('base64');
438
- await query({
405
+ yield query({
439
406
  tag: 'iq',
440
407
  attrs: {
441
408
  to: WABinary_1.S_WHATSAPP_NET,
@@ -476,11 +443,11 @@ const makeMessagesRecvSocket = (config) => {
476
443
  if (Object.keys(result).length) {
477
444
  return result;
478
445
  }
479
- };
480
- async function decipherLinkPublicKey(data) {
446
+ });
447
+ function decipherLinkPublicKey(data) {
481
448
  const buffer = toRequiredBuffer(data);
482
449
  const salt = buffer.slice(0, 32);
483
- const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
450
+ const secretKey = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
484
451
  const iv = buffer.slice(32, 48);
485
452
  const payload = buffer.slice(48, 80);
486
453
  return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
@@ -501,21 +468,22 @@ const makeMessagesRecvSocket = (config) => {
501
468
  const newValue = (msgRetryCache.get(key) || 0) + 1;
502
469
  msgRetryCache.set(key, newValue);
503
470
  };
504
- const sendMessagesAgain = async (key, ids, retryNode) => {
471
+ const sendMessagesAgain = (key, ids, retryNode) => __awaiter(void 0, void 0, void 0, function* () {
505
472
  var _a;
506
- const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
473
+ const msgs = yield Promise.all(ids.map(id => getMessage(Object.assign(Object.assign({}, key), { id }))));
507
474
  const remoteJid = key.remoteJid;
508
475
  const participant = key.participant || remoteJid;
509
476
  // if it's the primary jid sending the request
510
477
  // just re-send the message to everyone
511
478
  // prevents the first message decryption failure
512
479
  const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
513
- await assertSessions([participant], true);
480
+ yield assertSessions([participant], true);
514
481
  if ((0, WABinary_1.isJidGroup)(remoteJid)) {
515
- await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
482
+ yield authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
516
483
  }
517
484
  logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
518
- for (const [i, msg] of msgs.entries()) {
485
+ for (let i = 0; i < msgs.length; i++) {
486
+ const msg = msgs[i];
519
487
  if (msg) {
520
488
  updateSendMessageAgainCount(ids[i], participant);
521
489
  const msgRelayOpts = { messageId: ids[i] };
@@ -528,14 +496,14 @@ const makeMessagesRecvSocket = (config) => {
528
496
  count: +retryNode.attrs.count
529
497
  };
530
498
  }
531
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
499
+ yield relayMessage(key.remoteJid, msg, msgRelayOpts);
532
500
  }
533
501
  else {
534
502
  logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
535
503
  }
536
504
  }
537
- };
538
- const handleReceipt = async (node) => {
505
+ });
506
+ const handleReceipt = (node) => __awaiter(void 0, void 0, void 0, function* () {
539
507
  var _a, _b;
540
508
  const { attrs, content } = node;
541
509
  const isLid = attrs.from.includes('lid');
@@ -550,7 +518,7 @@ const makeMessagesRecvSocket = (config) => {
550
518
  };
551
519
  if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
552
520
  logger.debug({ remoteJid }, 'ignoring receipt from jid');
553
- await sendMessageAck(node);
521
+ yield sendMessageAck(node);
554
522
  return;
555
523
  }
556
524
  const ids = [attrs.id];
@@ -558,236 +526,147 @@ const makeMessagesRecvSocket = (config) => {
558
526
  const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
559
527
  ids.push(...items.map(i => i.attrs.id));
560
528
  }
561
- try {
562
- await Promise.all([
563
- processingMutex.mutex(async () => {
564
- const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
565
- if (typeof status !== 'undefined' &&
566
- (
567
- // basically, we only want to know when a message from us has been delivered to/read by the other person
568
- // or another device of ours has read some messages
569
- status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
570
- !isNodeFromMe)) {
571
- if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
572
- if (attrs.participant) {
573
- const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
574
- ev.emit('message-receipt.update', ids.map(id => ({
575
- key: { ...key, id },
576
- receipt: {
577
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
578
- [updateKey]: +attrs.t
579
- }
580
- })));
581
- }
582
- }
583
- else {
584
- ev.emit('messages.update', ids.map(id => ({
585
- key: { ...key, id },
586
- update: { status }
529
+ yield Promise.all([
530
+ processingMutex.mutex(() => __awaiter(void 0, void 0, void 0, function* () {
531
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
532
+ if (typeof status !== 'undefined' &&
533
+ (
534
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
535
+ // or another device of ours has read some messages
536
+ status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
537
+ !isNodeFromMe)) {
538
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
539
+ if (attrs.participant) {
540
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
541
+ ev.emit('message-receipt.update', ids.map(id => ({
542
+ key: Object.assign(Object.assign({}, key), { id }),
543
+ receipt: {
544
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
545
+ [updateKey]: +attrs.t
546
+ }
587
547
  })));
588
548
  }
589
549
  }
590
- if (attrs.type === 'retry') {
591
- // correctly set who is asking for the retry
592
- key.participant = key.participant || attrs.from;
593
- const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
594
- if (willSendMessageAgain(ids[0], key.participant)) {
595
- if (key.fromMe) {
596
- try {
597
- logger.debug({ attrs, key }, 'recv retry request');
598
- await sendMessagesAgain(key, ids, retryNode);
599
- }
600
- catch (error) {
601
- logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
602
- }
550
+ else {
551
+ ev.emit('messages.update', ids.map(id => ({
552
+ key: Object.assign(Object.assign({}, key), { id }),
553
+ update: { status }
554
+ })));
555
+ }
556
+ }
557
+ if (attrs.type === 'retry') {
558
+ // correctly set who is asking for the retry
559
+ key.participant = key.participant || attrs.from;
560
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
561
+ if (willSendMessageAgain(ids[0], key.participant)) {
562
+ if (key.fromMe) {
563
+ try {
564
+ logger.debug({ attrs, key }, 'recv retry request');
565
+ yield sendMessagesAgain(key, ids, retryNode);
603
566
  }
604
- else {
605
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
567
+ catch (error) {
568
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
606
569
  }
607
570
  }
608
571
  else {
609
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
572
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
610
573
  }
611
574
  }
612
- })
613
- ]);
614
- }
615
- finally {
616
- await sendMessageAck(node);
617
- }
618
- };
619
- const handleNotification = async (node) => {
575
+ else {
576
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
577
+ }
578
+ }
579
+ })),
580
+ sendMessageAck(node)
581
+ ]);
582
+ });
583
+ const handleNotification = (node) => __awaiter(void 0, void 0, void 0, function* () {
620
584
  const remoteJid = node.attrs.from;
621
585
  if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
622
586
  logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
623
- await sendMessageAck(node);
587
+ yield sendMessageAck(node);
624
588
  return;
625
589
  }
626
- try {
627
- await Promise.all([
628
- processingMutex.mutex(async () => {
629
- var _a;
630
- const msg = await processNotification(node);
631
- if (msg) {
632
- const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
633
- msg.key = {
634
- remoteJid,
635
- fromMe,
636
- participant: node.attrs.participant,
637
- id: node.attrs.id,
638
- ...(msg.key || {})
639
- };
640
- (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
641
- msg.messageTimestamp = +node.attrs.t;
642
- const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
643
- await upsertMessage(fullMsg, 'append');
644
- }
645
- })
646
- ]);
647
- }
648
- finally {
649
- await sendMessageAck(node);
650
- }
651
- };
652
- const handleMessage = async (node) => {
653
- var _a, _b, _c;
590
+ yield Promise.all([
591
+ processingMutex.mutex(() => __awaiter(void 0, void 0, void 0, function* () {
592
+ var _a;
593
+ const msg = yield processNotification(node);
594
+ if (msg) {
595
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
596
+ msg.key = Object.assign({ remoteJid,
597
+ fromMe, participant: node.attrs.participant, id: node.attrs.id }, (msg.key || {}));
598
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
599
+ msg.messageTimestamp = +node.attrs.t;
600
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
601
+ yield upsertMessage(fullMsg, 'append');
602
+ }
603
+ })),
604
+ sendMessageAck(node)
605
+ ]);
606
+ });
607
+ const handleMessage = (node) => __awaiter(void 0, void 0, void 0, function* () {
608
+ var _a, _b;
654
609
  if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
655
610
  logger.debug({ key: node.attrs.key }, 'ignored message');
656
- await sendMessageAck(node);
611
+ yield sendMessageAck(node);
657
612
  return;
658
613
  }
659
- let response;
660
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !(0, WABinary_1.getBinaryNodeChild)(node, 'enc')) {
661
- await sendMessageAck(node);
662
- const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
663
- response = await requestPlaceholderResend(key);
664
- if (response === 'RESOLVED') {
665
- return;
666
- }
667
- logger.debug('received unavailable message, acked and requested resend from phone');
668
- }
669
- else {
670
- if (placeholderResendCache.get(node.attrs.id)) {
671
- placeholderResendCache.del(node.attrs.id);
672
- }
673
- }
674
614
  const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
675
- 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) {
676
- msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
677
- }
678
- 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) {
679
- ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
615
+ if (((_b = (_a = msg.message) === null || _a === void 0 ? void 0 : _a.protocolMessage) === null || _b === void 0 ? void 0 : _b.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER) {
616
+ if (node.attrs.sender_pn) {
617
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
618
+ }
680
619
  }
681
- try {
682
- await Promise.all([
683
- processingMutex.mutex(async () => {
684
- var _a;
685
- await decrypt();
686
- // message failed to decrypt
687
- if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
688
- 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) {
689
- return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
690
- }
691
- retryMutex.mutex(async () => {
692
- if (ws.isOpen) {
693
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
694
- return;
695
- }
696
- const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
697
- await sendRetryRequest(node, !encNode);
698
- if (retryRequestDelayMs) {
699
- await (0, Utils_1.delay)(retryRequestDelayMs);
700
- }
701
- }
702
- else {
703
- logger.debug({ node }, 'connection closed, ignoring retry req');
704
- }
705
- });
706
- }
707
- else {
708
- // no type in the receipt => message delivered
709
- let type = undefined;
710
- let participant = msg.key.participant;
711
- if (category === 'peer') { // special peer message
712
- type = 'peer_msg';
713
- }
714
- else if (msg.key.fromMe) { // message was sent by us from a different device
715
- type = 'sender';
716
- // need to specially handle this case
717
- if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
718
- participant = author;
620
+ yield Promise.all([
621
+ processingMutex.mutex(() => __awaiter(void 0, void 0, void 0, function* () {
622
+ yield decrypt();
623
+ // message failed to decrypt
624
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
625
+ retryMutex.mutex(() => __awaiter(void 0, void 0, void 0, function* () {
626
+ if (ws.isOpen) {
627
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
628
+ yield sendRetryRequest(node, !encNode);
629
+ if (retryRequestDelayMs) {
630
+ yield (0, Utils_1.delay)(retryRequestDelayMs);
719
631
  }
720
632
  }
721
- else if (!sendActiveReceipts) {
722
- type = 'inactive';
633
+ else {
634
+ logger.debug({ node }, 'connection closed, ignoring retry req');
723
635
  }
724
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
725
- // send ack for history message
726
- const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
727
- if (isAnyHistoryMsg) {
728
- const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
729
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
636
+ }));
637
+ }
638
+ else {
639
+ // no type in the receipt => message delivered
640
+ let type = undefined;
641
+ let participant = msg.key.participant;
642
+ if (category === 'peer') { // special peer message
643
+ type = 'peer_msg';
644
+ }
645
+ else if (msg.key.fromMe) { // message was sent by us from a different device
646
+ type = 'sender';
647
+ // need to specially handle this case
648
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
649
+ participant = author;
730
650
  }
731
651
  }
732
- (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
733
- await sendMessageAck(node);
734
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
735
- })
736
- ]);
737
- }
738
- catch (error) {
739
- logger.error({ error, node }, 'error in handling message');
740
- }
741
- };
742
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
743
- var _a;
744
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
745
- throw new boom_1.Boom('Not authenticated');
746
- }
747
- const pdoMessage = {
748
- historySyncOnDemandRequest: {
749
- chatJid: oldestMsgKey.remoteJid,
750
- oldestMsgFromMe: oldestMsgKey.fromMe,
751
- oldestMsgId: oldestMsgKey.id,
752
- oldestMsgTimestampMs: oldestMsgTimestamp,
753
- onDemandMsgCount: count
754
- },
755
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
756
- };
757
- return sendPeerDataOperationMessage(pdoMessage);
758
- };
759
- const requestPlaceholderResend = async (messageKey) => {
760
- var _a;
761
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
762
- throw new boom_1.Boom('Not authenticated');
763
- }
764
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
765
- logger.debug('already requested resend', { messageKey });
766
- return;
767
- }
768
- else {
769
- placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
770
- }
771
- await (0, Utils_1.delay)(5000);
772
- if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
773
- logger.debug('message received while resend requested', { messageKey });
774
- return 'RESOLVED';
775
- }
776
- const pdoMessage = {
777
- placeholderMessageResendRequest: [{
778
- messageKey
779
- }],
780
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
781
- };
782
- setTimeout(() => {
783
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
784
- logger.debug('PDO message without response after 15 seconds. Phone possibly offline', { messageKey });
785
- placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
786
- }
787
- }, 15000);
788
- return sendPeerDataOperationMessage(pdoMessage);
789
- };
790
- const handleCall = async (node) => {
652
+ else if (!sendActiveReceipts) {
653
+ type = 'inactive';
654
+ }
655
+ yield sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
656
+ // send ack for history message
657
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
658
+ if (isAnyHistoryMsg) {
659
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
660
+ yield sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
661
+ }
662
+ }
663
+ (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
664
+ yield upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
665
+ })),
666
+ sendMessageAck(node)
667
+ ]);
668
+ });
669
+ const handleCall = (node) => __awaiter(void 0, void 0, void 0, function* () {
791
670
  const { attrs } = node;
792
671
  const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
793
672
  const callId = infoChild.attrs['call-id'];
@@ -814,27 +693,27 @@ const makeMessagesRecvSocket = (config) => {
814
693
  call.isGroup = existingCall.isGroup;
815
694
  }
816
695
  // delete data once call has ended
817
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
696
+ if (status === 'reject' || status === 'accept' || status === 'timeout') {
818
697
  callOfferCache.del(call.id);
819
698
  }
820
699
  ev.emit('call', [call]);
821
- await sendMessageAck(node);
822
- };
823
- const handleBadAck = async ({ attrs }) => {
700
+ yield sendMessageAck(node);
701
+ });
702
+ const handleBadAck = (_a) => __awaiter(void 0, [_a], void 0, function* ({ attrs }) {
824
703
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
825
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
826
- // // current hypothesis is that if pash is sent in the ack
827
- // // it means -- the message hasn't reached all devices yet
828
- // // we'll retry sending the message here
829
- // if(attrs.phash) {
830
- // logger.info({ attrs }, 'received phash in ack, resending message...')
831
- // const msg = await getMessage(key)
832
- // if(msg) {
833
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
834
- // } else {
835
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
836
- // }
837
- // }
704
+ // current hypothesis is that if pash is sent in the ack
705
+ // it means -- the message hasn't reached all devices yet
706
+ // we'll retry sending the message here
707
+ if (attrs.phash) {
708
+ logger.info({ attrs }, 'received phash in ack, resending message...');
709
+ const msg = yield getMessage(key);
710
+ if (msg) {
711
+ yield relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
712
+ }
713
+ else {
714
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
715
+ }
716
+ }
838
717
  // error in acknowledgement,
839
718
  // device could not display the message
840
719
  if (attrs.error) {
@@ -851,72 +730,31 @@ const makeMessagesRecvSocket = (config) => {
851
730
  }
852
731
  ]);
853
732
  }
854
- };
733
+ });
855
734
  /// processes a node with the given function
856
735
  /// and adds the task to the existing buffer if we're buffering events
857
- const processNodeWithBuffer = async (node, identifier, exec) => {
736
+ const processNodeWithBuffer = (node, identifier, exec) => __awaiter(void 0, void 0, void 0, function* () {
858
737
  ev.buffer();
859
- await execTask();
738
+ yield execTask();
860
739
  ev.flush();
861
740
  function execTask() {
862
- return exec(node, false)
741
+ return exec(node)
863
742
  .catch(err => onUnexpectedError(err, identifier));
864
743
  }
865
- };
866
- const makeOfflineNodeProcessor = () => {
867
- const nodeProcessorMap = new Map([
868
- ['message', handleMessage],
869
- ['call', handleCall],
870
- ['receipt', handleReceipt],
871
- ['notification', handleNotification]
872
- ]);
873
- const nodes = [];
874
- let isProcessing = false;
875
- const enqueue = (type, node) => {
876
- nodes.push({ type, node });
877
- if (isProcessing) {
878
- return;
879
- }
880
- isProcessing = true;
881
- const promise = async () => {
882
- while (nodes.length && ws.isOpen) {
883
- const { type, node } = nodes.shift();
884
- const nodeProcessor = nodeProcessorMap.get(type);
885
- if (!nodeProcessor) {
886
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
887
- continue;
888
- }
889
- await nodeProcessor(node);
890
- }
891
- isProcessing = false;
892
- };
893
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
894
- };
895
- return { enqueue };
896
- };
897
- const offlineNodeProcessor = makeOfflineNodeProcessor();
898
- const processNode = (type, node, identifier, exec) => {
899
- const isOffline = !!node.attrs.offline;
900
- if (isOffline) {
901
- offlineNodeProcessor.enqueue(type, node);
902
- }
903
- else {
904
- processNodeWithBuffer(node, identifier, exec);
905
- }
906
- };
744
+ });
907
745
  // recv a message
908
746
  ws.on('CB:message', (node) => {
909
- processNode('message', node, 'processing message', handleMessage);
910
- });
911
- ws.on('CB:call', async (node) => {
912
- processNode('call', node, 'handling call', handleCall);
747
+ processNodeWithBuffer(node, 'processing message', handleMessage);
913
748
  });
749
+ ws.on('CB:call', (node) => __awaiter(void 0, void 0, void 0, function* () {
750
+ processNodeWithBuffer(node, 'handling call', handleCall);
751
+ }));
914
752
  ws.on('CB:receipt', node => {
915
- processNode('receipt', node, 'handling receipt', handleReceipt);
916
- });
917
- ws.on('CB:notification', async (node) => {
918
- processNode('notification', node, 'handling notification', handleNotification);
753
+ processNodeWithBuffer(node, 'handling receipt', handleReceipt);
919
754
  });
755
+ ws.on('CB:notification', (node) => __awaiter(void 0, void 0, void 0, function* () {
756
+ processNodeWithBuffer(node, 'handling notification', handleNotification);
757
+ }));
920
758
  ws.on('CB:ack,class:message', (node) => {
921
759
  handleBadAck(node)
922
760
  .catch(error => onUnexpectedError(error, 'handling bad ack'));
@@ -953,14 +791,9 @@ const makeMessagesRecvSocket = (config) => {
953
791
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
954
792
  }
955
793
  });
956
- return {
957
- ...sock,
958
- sendMessageAck,
794
+ return Object.assign(Object.assign({}, sock), { sendMessageAck,
959
795
  sendRetryRequest,
960
796
  offerCall,
961
- rejectCall,
962
- fetchMessageHistory,
963
- requestPlaceholderResend,
964
- };
797
+ rejectCall });
965
798
  };
966
799
  exports.makeMessagesRecvSocket = makeMessagesRecvSocket;