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
  };
@@ -8,27 +17,25 @@ const boom_1 = require("@hapi/boom");
8
17
  const node_cache_1 = __importDefault(require("node-cache"));
9
18
  const WAProto_1 = require("../../WAProto");
10
19
  const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
20
  const Utils_1 = require("../Utils");
13
21
  const link_preview_1 = require("../Utils/link-preview");
14
22
  const WABinary_1 = require("../WABinary");
15
- const WAUSync_1 = require("../WAUSync");
16
23
  const newsletter_1 = require("./newsletter");
17
24
  var ListType = WAProto_1.proto.Message.ListMessage.ListType;
18
25
  const makeMessagesSocket = (config) => {
19
26
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
20
27
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
21
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupQuery, newsletterWMexQuery, groupToggleEphemeral } = sock;
28
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral } = sock;
22
29
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
23
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
30
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
24
31
  useClones: false
25
32
  });
26
33
  let mediaConn;
27
- const refreshMediaConn = async (forceGet = false) => {
28
- const media = await mediaConn;
34
+ const refreshMediaConn = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (forceGet = false) {
35
+ const media = yield mediaConn;
29
36
  if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
30
- mediaConn = (async () => {
31
- const result = await query({
37
+ mediaConn = (() => __awaiter(void 0, void 0, void 0, function* () {
38
+ const result = yield query({
32
39
  tag: 'iq',
33
40
  attrs: {
34
41
  type: 'set',
@@ -49,15 +56,15 @@ const makeMessagesSocket = (config) => {
49
56
  };
50
57
  logger.debug('fetched media conn');
51
58
  return node;
52
- })();
59
+ }))();
53
60
  }
54
61
  return mediaConn;
55
- };
62
+ });
56
63
  /**
57
64
  * generic send receipt function
58
65
  * used for receipts of phone call, read, delivery etc.
59
66
  * */
60
- const sendReceipt = async (jid, participant, messageIds, type) => {
67
+ const sendReceipt = (jid, participant, messageIds, type) => __awaiter(void 0, void 0, void 0, function* () {
61
68
  const node = {
62
69
  tag: 'receipt',
63
70
  attrs: {
@@ -95,110 +102,93 @@ const makeMessagesSocket = (config) => {
95
102
  ];
96
103
  }
97
104
  logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
98
- await sendNode(node);
99
- };
105
+ yield sendNode(node);
106
+ });
100
107
  /** Correctly bulk send receipts to multiple chats, participants */
101
- const sendReceipts = async (keys, type) => {
108
+ const sendReceipts = (keys, type) => __awaiter(void 0, void 0, void 0, function* () {
102
109
  const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
103
110
  for (const { jid, participant, messageIds } of recps) {
104
- await sendReceipt(jid, participant, messageIds, type);
111
+ yield sendReceipt(jid, participant, messageIds, type);
105
112
  }
106
- };
113
+ });
107
114
  /** Bulk read messages. Keys can be from different chats & participants */
108
- const readMessages = async (keys) => {
109
- const privacySettings = await fetchPrivacySettings();
115
+ const readMessages = (keys) => __awaiter(void 0, void 0, void 0, function* () {
116
+ const privacySettings = yield fetchPrivacySettings();
110
117
  // based on privacy settings, we have to change the read type
111
118
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
112
- await sendReceipts(keys, readType);
113
- };
114
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
115
- var _a, _b, _c, _d;
116
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
117
- if ((0, WABinary_1.isJidNewsLetter)(jid)) {
118
- const node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
119
- input: {
120
- key: jid,
121
- type: "JID",
122
- 'view_role': 'GUEST'
123
- },
124
- 'fetch_viewer_metadata': true,
125
- 'fetch_full_image': true,
126
- 'fetch_creation_time': true
127
- });
128
- const result = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(node, 'result')) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.toString();
129
- const metadataPath = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER];
130
- const pictype = type === 'image' ? 'picture' : 'preview';
131
- const directPath = (_c = metadataPath === null || metadataPath === void 0 ? void 0 : metadataPath.thread_metadata[pictype]) === null || _c === void 0 ? void 0 : _c.direct_path;
132
- return directPath ? (0, Utils_1.getUrlFromDirectPath)(directPath) : null;
133
- }
134
- else {
135
- const result = await query({
136
- tag: 'iq',
137
- attrs: {
138
- target: jid,
139
- to: WABinary_1.S_WHATSAPP_NET,
140
- type: 'get',
141
- xmlns: 'w:profile:picture'
142
- },
143
- content: [
144
- { tag: 'picture', attrs: { type, query: 'url' } }
145
- ]
146
- }, timeoutMs);
147
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
148
- return (_d = child === null || child === void 0 ? void 0 : child.attrs) === null || _d === void 0 ? void 0 : _d.url;
149
- }
150
- };
119
+ yield sendReceipts(keys, readType);
120
+ });
151
121
  /** Fetch all the devices we've to send a message to */
152
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
122
+ const getUSyncDevices = (jids, useCache, ignoreZeroDevices) => __awaiter(void 0, void 0, void 0, function* () {
153
123
  var _a;
154
124
  const deviceResults = [];
155
125
  if (!useCache) {
156
126
  logger.debug('not using cache for devices');
157
127
  }
158
- const toFetch = [];
128
+ const users = [];
159
129
  jids = Array.from(new Set(jids));
160
130
  for (let jid of jids) {
161
131
  const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
162
132
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
163
- if (useCache) {
164
- const devices = userDevicesCache.get(user);
165
- if (devices) {
166
- deviceResults.push(...devices);
167
- logger.trace({ user }, 'using cache for devices');
168
- }
169
- else {
170
- toFetch.push(jid);
171
- }
133
+ const devices = userDevicesCache.get(user);
134
+ if (devices && useCache) {
135
+ deviceResults.push(...devices);
136
+ logger.trace({ user }, 'using cache for devices');
172
137
  }
173
138
  else {
174
- toFetch.push(jid);
139
+ users.push({ tag: 'user', attrs: { jid } });
175
140
  }
176
141
  }
177
- if (!toFetch.length) {
142
+ if (!users.length) {
178
143
  return deviceResults;
179
144
  }
180
- const query = new WAUSync_1.USyncQuery()
181
- .withContext('message')
182
- .withDeviceProtocol();
183
- for (const jid of toFetch) {
184
- query.withUser(new WAUSync_1.USyncUser().withId(jid));
185
- }
186
- const result = await sock.executeUSyncQuery(query);
187
- if (result) {
188
- const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
189
- const deviceMap = {};
190
- for (const item of extracted) {
191
- deviceMap[item.user] = deviceMap[item.user] || [];
192
- deviceMap[item.user].push(item);
193
- deviceResults.push(item);
194
- }
195
- for (const key in deviceMap) {
196
- userDevicesCache.set(key, deviceMap[key]);
197
- }
145
+ const iq = {
146
+ tag: 'iq',
147
+ attrs: {
148
+ to: WABinary_1.S_WHATSAPP_NET,
149
+ type: 'get',
150
+ xmlns: 'usync',
151
+ },
152
+ content: [
153
+ {
154
+ tag: 'usync',
155
+ attrs: {
156
+ sid: generateMessageTag(),
157
+ mode: 'query',
158
+ last: 'true',
159
+ index: '0',
160
+ context: 'message',
161
+ },
162
+ content: [
163
+ {
164
+ tag: 'query',
165
+ attrs: {},
166
+ content: [
167
+ {
168
+ tag: 'devices',
169
+ attrs: { version: '2' }
170
+ }
171
+ ]
172
+ },
173
+ { tag: 'list', attrs: {}, content: users }
174
+ ]
175
+ },
176
+ ],
177
+ };
178
+ const result = yield query(iq);
179
+ const extracted = (0, Utils_1.extractDeviceJids)(result, authState.creds.me.id, ignoreZeroDevices);
180
+ const deviceMap = {};
181
+ for (const item of extracted) {
182
+ deviceMap[item.user] = deviceMap[item.user] || [];
183
+ deviceMap[item.user].push(item);
184
+ deviceResults.push(item);
185
+ }
186
+ for (const key in deviceMap) {
187
+ userDevicesCache.set(key, deviceMap[key]);
198
188
  }
199
189
  return deviceResults;
200
- };
201
- const assertSessions = async (jids, force) => {
190
+ });
191
+ const assertSessions = (jids, force) => __awaiter(void 0, void 0, void 0, function* () {
202
192
  let didFetchNewSession = false;
203
193
  let jidsRequiringFetch = [];
204
194
  if (force) {
@@ -207,7 +197,7 @@ const makeMessagesSocket = (config) => {
207
197
  else {
208
198
  const addrs = jids.map(jid => (signalRepository
209
199
  .jidToSignalProtocolAddress(jid)));
210
- const sessions = await authState.keys.get('session', addrs);
200
+ const sessions = yield authState.keys.get('session', addrs);
211
201
  for (const jid of jids) {
212
202
  const signalId = signalRepository
213
203
  .jidToSignalProtocolAddress(jid);
@@ -218,7 +208,7 @@ const makeMessagesSocket = (config) => {
218
208
  }
219
209
  if (jidsRequiringFetch.length) {
220
210
  logger.debug({ jidsRequiringFetch }, 'fetching sessions');
221
- const result = await query({
211
+ const result = yield query({
222
212
  tag: 'iq',
223
213
  attrs: {
224
214
  xmlns: 'encrypt',
@@ -236,39 +226,17 @@ const makeMessagesSocket = (config) => {
236
226
  }
237
227
  ]
238
228
  });
239
- await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
229
+ yield (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
240
230
  didFetchNewSession = true;
241
231
  }
242
232
  return didFetchNewSession;
243
- };
244
- const sendPeerDataOperationMessage = async (pdoMessage) => {
245
- var _a;
246
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
247
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
248
- throw new boom_1.Boom('Not authenticated');
249
- }
250
- const protocolMessage = {
251
- protocolMessage: {
252
- peerDataOperationRequestMessage: pdoMessage,
253
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
254
- }
255
- };
256
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
257
- const msgId = await relayMessage(meJid, protocolMessage, {
258
- additionalAttributes: {
259
- category: 'peer',
260
- // eslint-disable-next-line camelcase
261
- push_priority: 'high_force',
262
- },
263
- });
264
- return msgId;
265
- };
266
- const createParticipantNodes = async (jids, message, extraAttrs) => {
267
- const patched = await patchMessageBeforeSending(message, jids);
233
+ });
234
+ const createParticipantNodes = (jids, message, extraAttrs) => __awaiter(void 0, void 0, void 0, function* () {
235
+ const patched = yield patchMessageBeforeSending(message, jids);
268
236
  const bytes = (0, Utils_1.encodeWAMessage)(patched);
269
237
  let shouldIncludeDeviceIdentity = false;
270
- const nodes = await Promise.all(jids.map(async (jid) => {
271
- const { type, ciphertext } = await signalRepository
238
+ const nodes = yield Promise.all(jids.map((jid) => __awaiter(void 0, void 0, void 0, function* () {
239
+ const { type, ciphertext } = yield signalRepository
272
240
  .encryptMessage({ jid, data: bytes });
273
241
  if (type === 'pkmsg') {
274
242
  shouldIncludeDeviceIdentity = true;
@@ -278,19 +246,15 @@ const makeMessagesSocket = (config) => {
278
246
  attrs: { jid },
279
247
  content: [{
280
248
  tag: 'enc',
281
- attrs: {
282
- v: '2',
283
- type,
284
- ...extraAttrs || {}
285
- },
249
+ attrs: Object.assign({ v: '2', type }, extraAttrs || {}),
286
250
  content: ciphertext
287
251
  }]
288
252
  };
289
253
  return node;
290
- }));
254
+ })));
291
255
  return { nodes, shouldIncludeDeviceIdentity };
292
- }; //apela
293
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, statusJidList }) => {
256
+ }); //apela
257
+ const relayMessage = (jid_1, message_1, _a) => __awaiter(void 0, [jid_1, message_1, _a], void 0, function* (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, statusJidList }) {
294
258
  const meId = authState.creds.me.id;
295
259
  let shouldIncludeDeviceIdentity = false;
296
260
  const { user, server } = (0, WABinary_1.jidDecode)(jid);
@@ -298,7 +262,6 @@ const makeMessagesSocket = (config) => {
298
262
  const isGroup = server === 'g.us';
299
263
  const isStatus = jid === statusJid;
300
264
  const isLid = server === 'lid';
301
- const isPrivate = server === 's.whatsapp.net';
302
265
  const isNewsletter = server === 'newsletter';
303
266
  msgId = msgId || (0, Utils_1.generateMessageID)();
304
267
  useUserDevicesCache = useUserDevicesCache !== false;
@@ -317,45 +280,45 @@ const makeMessagesSocket = (config) => {
317
280
  // only send to the specific device that asked for a retry
318
281
  // otherwise the message is sent out to every device that should be a recipient
319
282
  if (!isGroup && !isStatus) {
320
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
283
+ additionalAttributes = Object.assign(Object.assign({}, additionalAttributes), { 'device_fanout': 'false' });
321
284
  }
322
285
  const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
323
286
  devices.push({ user, device });
324
287
  }
325
- await authState.keys.transaction(async () => {
288
+ yield authState.keys.transaction(() => __awaiter(void 0, void 0, void 0, function* () {
326
289
  var _a, _b, _c, _d, _e, _f;
327
290
  const mediaType = getMediaType(message);
328
291
  if (isGroup || isStatus) {
329
- const [groupData, senderKeyMap] = await Promise.all([
330
- (async () => {
331
- let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
292
+ const [groupData, senderKeyMap] = yield Promise.all([
293
+ (() => __awaiter(void 0, void 0, void 0, function* () {
294
+ let groupData = cachedGroupMetadata ? yield cachedGroupMetadata(jid) : undefined;
332
295
  if (groupData) {
333
296
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
334
297
  }
335
298
  if (!groupData && !isStatus) {
336
- groupData = await groupMetadata(jid);
299
+ groupData = yield groupMetadata(jid);
337
300
  }
338
301
  return groupData;
339
- })(),
340
- (async () => {
302
+ }))(),
303
+ (() => __awaiter(void 0, void 0, void 0, function* () {
341
304
  if (!participant && !isStatus) {
342
- const result = await authState.keys.get('sender-key-memory', [jid]);
305
+ const result = yield authState.keys.get('sender-key-memory', [jid]);
343
306
  return result[jid] || {};
344
307
  }
345
308
  return {};
346
- })()
309
+ }))()
347
310
  ]);
348
311
  if (!participant) {
349
312
  const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
350
313
  if (isStatus && statusJidList) {
351
314
  participantsList.push(...statusJidList);
352
315
  }
353
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
316
+ const additionalDevices = yield getUSyncDevices(participantsList, !!useUserDevicesCache, false);
354
317
  devices.push(...additionalDevices);
355
318
  }
356
- const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', d.device)));
319
+ const patched = yield patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
357
320
  const bytes = (0, Utils_1.encodeWAMessage)(patched);
358
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
321
+ const { ciphertext, senderKeyDistributionMessage } = yield signalRepository.encryptGroupMessage({
359
322
  group: destinationJid,
360
323
  data: bytes,
361
324
  meId,
@@ -380,8 +343,8 @@ const makeMessagesSocket = (config) => {
380
343
  groupId: destinationJid
381
344
  }
382
345
  };
383
- await assertSessions(senderKeyJids, false);
384
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
346
+ yield assertSessions(senderKeyJids, false);
347
+ const result = yield createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
385
348
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
386
349
  participants.push(...result.nodes);
387
350
  }
@@ -390,7 +353,7 @@ const makeMessagesSocket = (config) => {
390
353
  attrs: { v: '2', type: 'skmsg' },
391
354
  content: ciphertext
392
355
  });
393
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
356
+ yield authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
394
357
  }
395
358
  else if (isNewsletter) {
396
359
  // Message edit
@@ -403,7 +366,7 @@ const makeMessagesSocket = (config) => {
403
366
  msgId = (_d = message.protocolMessage.key) === null || _d === void 0 ? void 0 : _d.id;
404
367
  message = {};
405
368
  }
406
- const patched = await patchMessageBeforeSending(message, []);
369
+ const patched = yield patchMessageBeforeSending(message, []);
407
370
  const bytes = WAProto_1.proto.Message.encode(patched).finish();
408
371
  binaryNodeContent.push({
409
372
  tag: 'plaintext',
@@ -419,7 +382,7 @@ const makeMessagesSocket = (config) => {
419
382
  if (meDevice !== undefined && meDevice !== 0) {
420
383
  devices.push({ user: meUser });
421
384
  }
422
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
385
+ const additionalDevices = yield getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
423
386
  devices.push(...additionalDevices);
424
387
  }
425
388
  const allJids = [];
@@ -427,7 +390,7 @@ const makeMessagesSocket = (config) => {
427
390
  const otherJids = [];
428
391
  for (const { user, device } of devices) {
429
392
  const isMe = user === meUser;
430
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_f = (_e = authState.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.lid.split(':')[0]) || user : user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', device);
393
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_f = (_e = authState.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
431
394
  if (isMe) {
432
395
  meJids.push(jid);
433
396
  }
@@ -436,8 +399,8 @@ const makeMessagesSocket = (config) => {
436
399
  }
437
400
  allJids.push(jid);
438
401
  }
439
- await assertSessions(allJids, false);
440
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
402
+ yield assertSessions(allJids, false);
403
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = yield Promise.all([
441
404
  createParticipantNodes(meJids, meMsg, mediaType ? { mediatype: mediaType } : undefined),
442
405
  createParticipantNodes(otherJids, message, mediaType ? { mediatype: mediaType } : undefined)
443
406
  ]);
@@ -454,11 +417,7 @@ const makeMessagesSocket = (config) => {
454
417
  }
455
418
  const stanza = {
456
419
  tag: 'message',
457
- attrs: {
458
- id: msgId,
459
- type: isNewsletter ? getTypeMessage(message) : 'text',
460
- ...(additionalAttributes || {})
461
- },
420
+ attrs: Object.assign({ id: msgId, type: isNewsletter ? getTypeMessage(message) : 'text' }, (additionalAttributes || {})),
462
421
  content: binaryNodeContent
463
422
  };
464
423
  // if the participant to send to is explicitly specified (generally retry recp)
@@ -491,92 +450,44 @@ const makeMessagesSocket = (config) => {
491
450
  if (additionalNodes && additionalNodes.length > 0) {
492
451
  stanza.content.push(...additionalNodes);
493
452
  }
494
- const inMsg = (0, Utils_1.normalizeMessageContent)(message) || null;
495
- const key = inMsg ? (0, Utils_1.getContentType)(inMsg) : null;
496
- if (!isNewsletter && (key === 'interactiveMessage' || key === 'buttonsMessage')) {
497
- const nativeNode = {
498
- tag: 'biz',
499
- attrs: {},
500
- content: [{
501
- tag: 'interactive',
502
- attrs: {
503
- type: 'native_flow',
504
- v: '1'
505
- },
506
- content: [{
507
- tag: 'native_flow',
508
- attrs: {
509
- name: 'quick_reply'
510
- }
511
- }]
512
- }]
513
- };
514
- const resultNativeNode = filterNativeNode(additionalNodes);
515
- if (resultNativeNode && additionalNodes && additionalNodes.length > 0) {
516
- stanza.content.push(...resultNativeNode);
517
- }
518
- else {
519
- stanza.content.push(nativeNode);
520
- }
521
- }
522
- if (isPrivate) {
523
- const botNode = {
524
- tag: 'bot',
525
- attrs: { biz_bot: '1' }
526
- };
527
- const resultBotNode = filterBotNode(additionalNodes);
528
- if (resultBotNode && additionalNodes && additionalNodes.length > 0) {
529
- stanza.content.push(...resultBotNode);
530
- }
531
- else {
532
- stanza.content.push(botNode);
453
+ else {
454
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && ((message === null || message === void 0 ? void 0 : message.viewOnceMessage) ? message === null || message === void 0 ? void 0 : message.viewOnceMessage : (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) ? message === null || message === void 0 ? void 0 : message.viewOnceMessageV2 : (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) ? message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension : (message === null || message === void 0 ? void 0 : message.ephemeralMessage) ? message === null || message === void 0 ? void 0 : message.ephemeralMessage : (message === null || message === void 0 ? void 0 : message.templateMessage) ? message === null || message === void 0 ? void 0 : message.templateMessage : (message === null || message === void 0 ? void 0 : message.interactiveMessage) ? message === null || message === void 0 ? void 0 : message.interactiveMessage : message === null || message === void 0 ? void 0 : message.buttonsMessage)) {
455
+ stanza.content.push({
456
+ tag: 'biz',
457
+ attrs: {},
458
+ content: [{
459
+ tag: 'interactive',
460
+ attrs: {
461
+ type: 'native_flow',
462
+ v: '1'
463
+ },
464
+ content: [{
465
+ tag: 'native_flow',
466
+ attrs: { name: 'quick_reply' }
467
+ }]
468
+ }]
469
+ });
533
470
  }
534
471
  }
535
- if (message && message.listMessage) {
472
+ const buttonType = getButtonType(message);
473
+ if (buttonType) {
536
474
  stanza.content.push({
537
475
  tag: 'biz',
538
476
  attrs: {},
539
477
  content: [
540
478
  {
541
- tag: 'list',
542
- attrs: getButtonArgs(message)
479
+ tag: buttonType,
480
+ attrs: getButtonArgs(message),
543
481
  }
544
482
  ]
545
483
  });
546
484
  logger.debug({ jid }, 'adding business node');
547
485
  }
548
486
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
549
- await sendNode(stanza);
550
- });
487
+ yield sendNode(stanza);
488
+ }));
551
489
  return msgId;
552
- };
553
- const filterNativeNode = (nodeContent) => {
554
- if (Array.isArray(nodeContent)) {
555
- return nodeContent.filter((item) => {
556
- var _a, _b, _c, _d, _e, _f, _g, _h;
557
- if (item.tag === 'biz' && ((_a = item === null || item === void 0 ? void 0 : item.content[0]) === null || _a === void 0 ? void 0 : _a.tag) === 'interactive' && ((_c = (_b = item === null || item === void 0 ? void 0 : item.content[0]) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.type) === 'native_flow' && ((_e = (_d = item === null || item === void 0 ? void 0 : item.content[0]) === null || _d === void 0 ? void 0 : _d.content[0]) === null || _e === void 0 ? void 0 : _e.tag) === 'native_flow' && ((_h = (_g = (_f = item === null || item === void 0 ? void 0 : item.content[0]) === null || _f === void 0 ? void 0 : _f.content[0]) === null || _g === void 0 ? void 0 : _g.attrs) === null || _h === void 0 ? void 0 : _h.name) === 'quick_reply') {
558
- return false;
559
- }
560
- return true;
561
- });
562
- }
563
- else {
564
- return nodeContent;
565
- }
566
- };
567
- const filterBotNode = (nodeContent) => {
568
- if (Array.isArray(nodeContent)) {
569
- return nodeContent.filter((item) => {
570
- if (item.tag === 'bot' && item.attrs.biz_bot === '1') {
571
- return false;
572
- }
573
- return true;
574
- });
575
- }
576
- else {
577
- return nodeContent;
578
- }
579
- };
490
+ });
580
491
  const getTypeMessage = (msg) => {
581
492
  if (msg.viewOnceMessage) {
582
493
  return getTypeMessage(msg.viewOnceMessage.message);
@@ -597,7 +508,7 @@ const makeMessagesSocket = (config) => {
597
508
  return 'reaction';
598
509
  }
599
510
  else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
600
- return 'poll';
511
+ return 'reaction';
601
512
  }
602
513
  else if (getMediaType(msg)) {
603
514
  return 'media';
@@ -649,8 +560,22 @@ const makeMessagesSocket = (config) => {
649
560
  else if (message.interactiveResponseMessage) {
650
561
  return 'native_flow_response';
651
562
  }
652
- else if (message.groupInviteMessage) {
653
- return 'url';
563
+ };
564
+ const getButtonType = (message) => {
565
+ if (message.buttonsMessage) {
566
+ return 'buttons';
567
+ }
568
+ else if (message.buttonsResponseMessage) {
569
+ return 'buttons_response';
570
+ }
571
+ else if (message.interactiveResponseMessage) {
572
+ return 'interactive_response';
573
+ }
574
+ else if (message.listMessage) {
575
+ return 'list';
576
+ }
577
+ else if (message.listResponseMessage) {
578
+ return 'list_response';
654
579
  }
655
580
  };
656
581
  const getButtonArgs = (message) => {
@@ -669,9 +594,9 @@ const makeMessagesSocket = (config) => {
669
594
  return {};
670
595
  }
671
596
  };
672
- const getPrivacyTokens = async (jids) => {
597
+ const getPrivacyTokens = (jids) => __awaiter(void 0, void 0, void 0, function* () {
673
598
  const t = (0, Utils_1.unixTimestampSeconds)().toString();
674
- const result = await query({
599
+ const result = yield query({
675
600
  tag: 'iq',
676
601
  attrs: {
677
602
  to: WABinary_1.S_WHATSAPP_NET,
@@ -694,12 +619,10 @@ const makeMessagesSocket = (config) => {
694
619
  ]
695
620
  });
696
621
  return result;
697
- };
622
+ });
698
623
  const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
699
624
  const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
700
- return {
701
- ...sock,
702
- getPrivacyTokens,
625
+ return Object.assign(Object.assign({}, sock), { getPrivacyTokens,
703
626
  assertSessions,
704
627
  relayMessage,
705
628
  sendReceipt,
@@ -708,18 +631,15 @@ const makeMessagesSocket = (config) => {
708
631
  readMessages,
709
632
  refreshMediaConn,
710
633
  getUSyncDevices,
711
- sendPeerDataOperationMessage,
712
634
  createParticipantNodes,
713
- profilePictureUrl,
714
635
  waUploadToServer,
715
- fetchPrivacySettings,
716
- updateMediaMessage: async (message) => {
636
+ fetchPrivacySettings, updateMediaMessage: (message) => __awaiter(void 0, void 0, void 0, function* () {
717
637
  const content = (0, Utils_1.assertMediaContent)(message.message);
718
638
  const mediaKey = content.mediaKey;
719
639
  const meId = authState.creds.me.id;
720
640
  const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
721
641
  let error = undefined;
722
- await Promise.all([
642
+ yield Promise.all([
723
643
  sendNode(node),
724
644
  waitForMsgMediaUpdate(update => {
725
645
  const result = update.find(c => c.key.id === message.key.id);
@@ -730,7 +650,7 @@ const makeMessagesSocket = (config) => {
730
650
  else {
731
651
  try {
732
652
  const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
733
- if (media && media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
653
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
734
654
  const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
735
655
  throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
736
656
  }
@@ -753,168 +673,8 @@ const makeMessagesSocket = (config) => {
753
673
  { key: message.key, update: { message: message.message } }
754
674
  ]);
755
675
  return message;
756
- },
757
- sendStatusMentions: async (content, jids = []) => {
758
- const userJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
759
- let allUsers = [];
760
- for (const id of jids) {
761
- const { user, server } = (0, WABinary_1.jidDecode)(id);
762
- const isGroup = server === 'g.us';
763
- const isPrivate = server === 's.whatsapp.net';
764
- if (isGroup) {
765
- let userId = await groupMetadata(id);
766
- let participant = await userId.participants;
767
- let users = await Promise.all(participant.map(u => (0, WABinary_1.jidNormalizedUser)(u.id)));
768
- allUsers = [...allUsers, ...users];
769
- }
770
- else if (isPrivate) {
771
- let users = await Promise.all(jids.map(id => id.replace(/\b\d{18}@.{4}\b/g, '')));
772
- allUsers = [...allUsers, ...users];
773
- }
774
- if (!allUsers.find(user => user.includes(userJid))) {
775
- allUsers.push(userJid);
776
- }
777
- }
778
- ;
779
- const getRandomHexColor = () => {
780
- return "#" + Math.floor(Math.random() * 16777215)
781
- .toString(16)
782
- .padStart(6, "0");
783
- };
784
- let mediaHandle;
785
- let msg = await (0, Utils_1.generateWAMessage)(WABinary_1.STORIES_JID, content, {
786
- logger,
787
- userJid,
788
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
789
- thumbnailWidth: linkPreviewImageThumbnailWidth,
790
- fetchOpts: {
791
- timeout: 3000,
792
- ...axiosOptions || {}
793
- },
794
- logger,
795
- uploadImage: generateHighQualityLinkPreview
796
- ? waUploadToServer
797
- : undefined
798
- }),
799
- upload: async (readStream, opts) => {
800
- const up = await waUploadToServer(readStream, { ...opts });
801
- mediaHandle = up.handle;
802
- return up;
803
- },
804
- mediaCache: config.mediaCache,
805
- options: config.options,
806
- backgroundColor: getRandomHexColor(),
807
- font: Math.floor(Math.random() * 9),
808
- });
809
- await relayMessage(WABinary_1.STORIES_JID, msg.message, {
810
- messageId: msg.key.id,
811
- statusJidList: allUsers,
812
- additionalNodes: [
813
- {
814
- tag: 'meta',
815
- attrs: {},
816
- content: [
817
- {
818
- tag: 'mentioned_users',
819
- attrs: {},
820
- content: jids.map(jid => ({
821
- tag: 'to',
822
- attrs: { jid },
823
- content: undefined,
824
- })),
825
- },
826
- ],
827
- },
828
- ],
829
- });
830
- jids.forEach(async (id) => {
831
- id = (0, WABinary_1.jidNormalizedUser)(id);
832
- const { user, server } = (0, WABinary_1.jidDecode)(id);
833
- const isPrivate = server === 's.whatsapp.net';
834
- let type = isPrivate
835
- ? 'statusMentionMessage'
836
- : 'groupStatusMentionMessage';
837
- await relayMessage(id, {
838
- [type]: {
839
- message: {
840
- protocolMessage: {
841
- key: msg.key,
842
- type: 25,
843
- },
844
- },
845
- },
846
- }, {});
847
- await (0, Utils_1.delay)(2500);
848
- });
849
- return msg;
850
- },
851
- sendAlbumMessage: async (jid, medias, options = {}) => {
852
- const userJid = authState.creds.me.id;
853
- for (const media of medias) {
854
- if (!media.image && !media.video)
855
- throw new TypeError(`medias[i] must have image or video property`);
856
- }
857
- if (medias.length < 2)
858
- throw new RangeError("Minimum 2 media");
859
- const time = options.delay || 500;
860
- delete options.delay;
861
- const album = await (0, Utils_1.generateWAMessageFromContent)(jid, {
862
- albumMessage: {
863
- expectedImageCount: medias.filter(media => media.image).length,
864
- expectedVideoCount: medias.filter(media => media.video).length,
865
- ...options
866
- }
867
- }, { userJid, ...options });
868
- await relayMessage(jid, album.message, { messageId: album.key.id });
869
- let mediaHandle;
870
- let msg;
871
- for (const i in medias) {
872
- const media = medias[i];
873
- if (media.image) {
874
- msg = await (0, Utils_1.generateWAMessage)(jid, {
875
- image: media.image,
876
- ...media,
877
- ...options
878
- }, {
879
- userJid,
880
- upload: async (readStream, opts) => {
881
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
882
- mediaHandle = up.handle;
883
- return up;
884
- },
885
- ...options,
886
- });
887
- }
888
- else if (media.video) {
889
- msg = await (0, Utils_1.generateWAMessage)(jid, {
890
- video: media.video,
891
- ...media,
892
- ...options
893
- }, {
894
- userJid,
895
- upload: async (readStream, opts) => {
896
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
897
- mediaHandle = up.handle;
898
- return up;
899
- },
900
- ...options,
901
- });
902
- }
903
- if (msg) {
904
- msg.message.messageContextInfo = {
905
- messageAssociation: {
906
- associationType: 1,
907
- parentMessageKey: album.key
908
- }
909
- };
910
- }
911
- await relayMessage(jid, msg.message, { messageId: msg.key.id });
912
- await (0, Utils_1.delay)(time);
913
- }
914
- return album;
915
- },
916
- sendMessage: async (jid, content, options = {}) => {
917
- var _a, _b, _c;
676
+ }), sendMessage: (jid_1, content_1, ...args_1) => __awaiter(void 0, [jid_1, content_1, ...args_1], void 0, function* (jid, content, options = {}) {
677
+ var _a, _b;
918
678
  const userJid = authState.creds.me.id;
919
679
  if (typeof content === 'object' &&
920
680
  'disappearingMessagesInChat' in content &&
@@ -924,60 +684,32 @@ const makeMessagesSocket = (config) => {
924
684
  const value = typeof disappearingMessagesInChat === 'boolean' ?
925
685
  (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
926
686
  disappearingMessagesInChat;
927
- await groupToggleEphemeral(jid, value);
687
+ yield groupToggleEphemeral(jid, value);
928
688
  }
929
689
  else {
930
690
  let mediaHandle;
931
- const { server } = (0, WABinary_1.jidDecode)(jid);
932
- const isGroup = server === 'g.us';
933
- let eph;
934
- if (isGroup) {
935
- const disappearingNode = await groupQuery(jid, 'get', [
936
- {
937
- tag: 'query',
938
- attrs: { request: 'interactive' }
939
- }
940
- ]);
941
- const group = (0, WABinary_1.getBinaryNodeChild)(disappearingNode, 'group');
942
- const expiration = (0, WABinary_1.getBinaryNodeChild)(group, 'ephemeral');
943
- eph = (_a = expiration === null || expiration === void 0 ? void 0 : expiration.attrs) === null || _a === void 0 ? void 0 : _a.expiration;
944
- }
945
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
946
- logger,
947
- userJid,
948
- ephemeralExpiration: (options.ephemeralExpiration && options.ephemeralExpiration > 0) ? options.ephemeralExpiration : eph,
949
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
691
+ const fullMsg = yield (0, Utils_1.generateWAMessage)(jid, content, Object.assign({ logger,
692
+ userJid, getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
950
693
  thumbnailWidth: linkPreviewImageThumbnailWidth,
951
- fetchOpts: {
952
- timeout: 3000,
953
- ...axiosOptions || {}
954
- },
694
+ fetchOpts: Object.assign({ timeout: 3000 }, axiosOptions || {}),
955
695
  logger,
956
696
  uploadImage: generateHighQualityLinkPreview
957
697
  ? waUploadToServer
958
698
  : undefined
959
- }),
960
- upload: async (readStream, opts) => {
961
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
699
+ }), upload: (readStream, opts) => __awaiter(void 0, void 0, void 0, function* () {
700
+ const up = yield waUploadToServer(readStream, Object.assign(Object.assign({}, opts), { newsletter: (0, WABinary_1.isJidNewsLetter)(jid) }));
962
701
  mediaHandle = up.handle;
963
702
  return up;
964
- },
965
- mediaCache: config.mediaCache,
966
- options: config.options,
967
- ...options,
968
- });
969
- const isAiMsg = 'ai' in content && !!content.ai;
970
- const isPinMsg = 'pin' in content && !!content.pin;
971
- const isKeepMsg = 'keep' in content && content.keep;
972
- const isPollMsg = 'poll' in content && !!content.poll;
973
- const isEditMsg = 'edit' in content && !!content.edit;
703
+ }), mediaCache: config.mediaCache, options: config.options }, options));
974
704
  const isDeleteMsg = 'delete' in content && !!content.delete;
705
+ const isEditMsg = 'edit' in content && !!content.edit;
706
+ const isAiMsg = 'ai' in content && !!content.ai;
975
707
  const additionalAttributes = {};
976
708
  const additionalNodes = [];
977
709
  // required for delete
978
710
  if (isDeleteMsg) {
979
711
  // if the chat is a group, and I am not the author, then delete the message as an admin
980
- if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsLetter)(jid)) {
712
+ if (((0, WABinary_1.isJidGroup)((_a = content.delete) === null || _a === void 0 ? void 0 : _a.remoteJid) && !((_b = content.delete) === null || _b === void 0 ? void 0 : _b.fromMe)) || (0, WABinary_1.isJidNewsLetter)(jid)) {
981
713
  additionalAttributes.edit = '8';
982
714
  }
983
715
  else {
@@ -987,19 +719,13 @@ const makeMessagesSocket = (config) => {
987
719
  else if (isEditMsg) {
988
720
  additionalAttributes.edit = (0, WABinary_1.isJidNewsLetter)(jid) ? '3' : '1';
989
721
  }
990
- else if (isPinMsg) {
991
- additionalAttributes.edit = '2';
992
- }
993
722
  else if (isAiMsg) {
994
723
  additionalNodes.push({
995
724
  attrs: {
996
725
  biz_bot: '1'
997
726
  },
998
- tag: 'bot'
727
+ tag: "bot"
999
728
  });
1000
- if (options.additionalNodes) {
1001
- additionalNodes.push(...options.additionalNodes);
1002
- }
1003
729
  }
1004
730
  if (mediaHandle) {
1005
731
  additionalAttributes['media_id'] = mediaHandle;
@@ -1007,7 +733,7 @@ const makeMessagesSocket = (config) => {
1007
733
  if ('cachedGroupMetadata' in options) {
1008
734
  console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1009
735
  }
1010
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
736
+ yield relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
1011
737
  if (config.emitOwnEvents) {
1012
738
  process.nextTick(() => {
1013
739
  processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
@@ -1015,7 +741,6 @@ const makeMessagesSocket = (config) => {
1015
741
  }
1016
742
  return fullMsg;
1017
743
  }
1018
- }
1019
- };
744
+ }) });
1020
745
  };
1021
746
  exports.makeMessagesSocket = makeMessagesSocket;