gifted-baileys 1.5.5 → 1.5.7

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 (251) hide show
  1. package/README.md +6 -1642
  2. package/WAProto/WAProto.proto +969 -88
  3. package/WAProto/index.d.ts +13199 -1260
  4. package/WAProto/index.js +124901 -74525
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.d.ts +284 -0
  7. package/{src → lib}/Defaults/index.js +7 -14
  8. package/lib/Signal/libsignal.d.ts +3 -0
  9. package/lib/Signal/libsignal.js +161 -0
  10. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  11. package/lib/Socket/Client/index.d.ts +2 -0
  12. package/{src → lib}/Socket/Client/index.js +2 -3
  13. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  14. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  15. package/lib/Socket/Client/types.d.ts +17 -0
  16. package/lib/Socket/Client/types.js +13 -0
  17. package/lib/Socket/Client/websocket.d.ts +12 -0
  18. package/lib/Socket/Client/websocket.js +62 -0
  19. package/lib/Socket/business.d.ts +170 -0
  20. package/{src → lib}/Socket/business.js +28 -33
  21. package/lib/Socket/chats.d.ts +81 -0
  22. package/{src → lib}/Socket/chats.js +174 -176
  23. package/lib/Socket/groups.d.ts +115 -0
  24. package/{src → lib}/Socket/groups.js +80 -68
  25. package/lib/Socket/index.d.ts +172 -0
  26. package/{src → lib}/Socket/index.js +4 -1
  27. package/lib/Socket/messages-recv.d.ts +158 -0
  28. package/{src → lib}/Socket/messages-recv.js +378 -211
  29. package/lib/Socket/messages-send.d.ts +155 -0
  30. package/{src → lib}/Socket/messages-send.js +452 -177
  31. package/lib/Socket/newsletter.d.ts +132 -0
  32. package/{src → lib}/Socket/newsletter.js +107 -98
  33. package/lib/Socket/registration.d.ts +264 -0
  34. package/{src → lib}/Socket/registration.js +56 -48
  35. package/lib/Socket/socket.d.ts +44 -0
  36. package/{src → lib}/Socket/socket.js +77 -77
  37. package/lib/Socket/usync.d.ts +37 -0
  38. package/lib/Socket/usync.js +70 -0
  39. package/lib/Store/index.d.ts +3 -0
  40. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  41. package/{src → lib}/Store/make-cache-manager-store.js +25 -34
  42. package/lib/Store/make-in-memory-store.d.ts +118 -0
  43. package/{src → lib}/Store/make-in-memory-store.js +36 -32
  44. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  45. package/lib/Store/object-repository.d.ts +10 -0
  46. package/{src → lib}/Store/object-repository.js +1 -1
  47. package/lib/Types/Auth.d.ts +109 -0
  48. package/lib/Types/Call.d.ts +13 -0
  49. package/lib/Types/Chat.d.ts +107 -0
  50. package/{src/Types/Contact.ts → lib/Types/Contact.d.ts} +8 -9
  51. package/lib/Types/Events.d.ts +172 -0
  52. package/lib/Types/GroupMetadata.d.ts +56 -0
  53. package/lib/Types/Label.d.ts +46 -0
  54. package/{src/Types/LabelAssociation.ts → lib/Types/LabelAssociation.d.ts} +16 -22
  55. package/lib/Types/Message.d.ts +433 -0
  56. package/lib/Types/Newsletter.d.ts +92 -0
  57. package/lib/Types/Product.d.ts +78 -0
  58. package/lib/Types/Signal.d.ts +57 -0
  59. package/{src/Types/Socket.ts → lib/Types/Socket.d.ts} +61 -68
  60. package/lib/Types/State.d.ts +27 -0
  61. package/lib/Types/USync.d.ts +25 -0
  62. package/lib/Types/index.d.ts +66 -0
  63. package/lib/Utils/auth-utils.d.ts +18 -0
  64. package/{src → lib}/Utils/auth-utils.js +73 -90
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  66. package/lib/Utils/baileys-event-stream.js +63 -0
  67. package/lib/Utils/business.d.ts +22 -0
  68. package/{src → lib}/Utils/business.js +15 -43
  69. package/lib/Utils/chat-utils.d.ts +70 -0
  70. package/{src → lib}/Utils/chat-utils.js +87 -94
  71. package/lib/Utils/crypto.d.ts +40 -0
  72. package/{src → lib}/Utils/crypto.js +4 -2
  73. package/lib/Utils/decode-wa-message.d.ts +36 -0
  74. package/lib/Utils/decode-wa-message.js +226 -0
  75. package/lib/Utils/event-buffer.d.ts +35 -0
  76. package/{src → lib}/Utils/event-buffer.js +4 -13
  77. package/lib/Utils/generics.d.ts +88 -0
  78. package/{src → lib}/Utils/generics.js +67 -86
  79. package/lib/Utils/history.d.ts +19 -0
  80. package/{src → lib}/Utils/history.js +13 -39
  81. package/lib/Utils/index.d.ts +17 -0
  82. package/lib/Utils/link-preview.d.ts +21 -0
  83. package/{src → lib}/Utils/link-preview.js +17 -54
  84. package/lib/Utils/logger.d.ts +2 -0
  85. package/lib/Utils/lt-hash.d.ts +12 -0
  86. package/lib/Utils/make-mutex.d.ts +7 -0
  87. package/{src → lib}/Utils/make-mutex.js +4 -13
  88. package/lib/Utils/messages-media.d.ts +113 -0
  89. package/{src → lib}/Utils/messages-media.js +193 -255
  90. package/lib/Utils/messages.d.ts +77 -0
  91. package/{src → lib}/Utils/messages.js +588 -118
  92. package/lib/Utils/noise-handler.d.ts +20 -0
  93. package/lib/Utils/process-message.d.ts +41 -0
  94. package/{src → lib}/Utils/process-message.js +27 -30
  95. package/lib/Utils/signal.d.ts +33 -0
  96. package/{src → lib}/Utils/signal.js +25 -42
  97. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  98. package/{src → lib}/Utils/use-multi-file-auth-state.js +27 -28
  99. package/lib/Utils/validate-connection.d.ts +11 -0
  100. package/{src → lib}/Utils/validate-connection.js +40 -9
  101. package/lib/WABinary/constants.d.ts +27 -0
  102. package/lib/WABinary/decode.d.ts +6 -0
  103. package/lib/WABinary/encode.d.ts +2 -0
  104. package/{src → lib}/WABinary/encode.js +16 -10
  105. package/lib/WABinary/generic-utils.d.ts +14 -0
  106. package/lib/WABinary/index.d.ts +5 -0
  107. package/lib/WABinary/jid-utils.d.ts +31 -0
  108. package/lib/WABinary/types.d.ts +18 -0
  109. package/lib/WABinary/types.js +2 -0
  110. package/lib/WAM/BinaryInfo.d.ts +8 -0
  111. package/lib/WAM/constants.d.ts +38 -0
  112. package/lib/WAM/encode.d.ts +2 -0
  113. package/lib/WAM/index.d.ts +3 -0
  114. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  117. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  118. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  119. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  120. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  121. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  122. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  123. package/lib/WAUSync/Protocols/index.js +20 -0
  124. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  125. package/lib/WAUSync/USyncQuery.js +79 -0
  126. package/lib/WAUSync/USyncUser.d.ts +10 -0
  127. package/lib/WAUSync/USyncUser.js +22 -0
  128. package/lib/WAUSync/index.d.ts +3 -0
  129. package/lib/WAUSync/index.js +19 -0
  130. package/{src → lib}/index.js +1 -0
  131. package/package.json +26 -8
  132. package/LICENSE +0 -21
  133. package/src/Defaults/baileys-version.json +0 -3
  134. package/src/Defaults/index.ts +0 -131
  135. package/src/Signal/libsignal.js +0 -180
  136. package/src/Signal/libsignal.ts +0 -141
  137. package/src/Socket/Client/abstract-socket-client.ts +0 -19
  138. package/src/Socket/Client/index.ts +0 -3
  139. package/src/Socket/Client/mobile-socket-client.js +0 -78
  140. package/src/Socket/Client/mobile-socket-client.ts +0 -66
  141. package/src/Socket/Client/web-socket-client.js +0 -75
  142. package/src/Socket/Client/web-socket-client.ts +0 -57
  143. package/src/Socket/business.ts +0 -281
  144. package/src/Socket/chats.ts +0 -1030
  145. package/src/Socket/groups.ts +0 -356
  146. package/src/Socket/index.ts +0 -13
  147. package/src/Socket/messages-recv.ts +0 -985
  148. package/src/Socket/messages-send.ts +0 -871
  149. package/src/Socket/newsletter.ts +0 -282
  150. package/src/Socket/registration.ts +0 -250
  151. package/src/Socket/socket.ts +0 -777
  152. package/src/Store/index.ts +0 -3
  153. package/src/Store/make-cache-manager-store.ts +0 -100
  154. package/src/Store/make-in-memory-store.ts +0 -475
  155. package/src/Store/make-ordered-dictionary.ts +0 -86
  156. package/src/Store/object-repository.ts +0 -32
  157. package/src/Tests/test.app-state-sync.js +0 -204
  158. package/src/Tests/test.app-state-sync.ts +0 -207
  159. package/src/Tests/test.event-buffer.js +0 -270
  160. package/src/Tests/test.event-buffer.ts +0 -319
  161. package/src/Tests/test.key-store.js +0 -76
  162. package/src/Tests/test.key-store.ts +0 -92
  163. package/src/Tests/test.libsignal.js +0 -141
  164. package/src/Tests/test.libsignal.ts +0 -186
  165. package/src/Tests/test.media-download.js +0 -93
  166. package/src/Tests/test.media-download.ts +0 -76
  167. package/src/Tests/test.messages.js +0 -33
  168. package/src/Tests/test.messages.ts +0 -37
  169. package/src/Tests/utils.js +0 -34
  170. package/src/Tests/utils.ts +0 -36
  171. package/src/Types/Auth.ts +0 -113
  172. package/src/Types/Call.ts +0 -15
  173. package/src/Types/Chat.ts +0 -106
  174. package/src/Types/Events.ts +0 -93
  175. package/src/Types/GroupMetadata.ts +0 -53
  176. package/src/Types/Label.ts +0 -36
  177. package/src/Types/Message.ts +0 -288
  178. package/src/Types/Newsletter.ts +0 -98
  179. package/src/Types/Product.ts +0 -85
  180. package/src/Types/Signal.ts +0 -68
  181. package/src/Types/State.ts +0 -29
  182. package/src/Types/index.ts +0 -59
  183. package/src/Utils/auth-utils.ts +0 -222
  184. package/src/Utils/baileys-event-stream.js +0 -92
  185. package/src/Utils/baileys-event-stream.ts +0 -66
  186. package/src/Utils/business.ts +0 -275
  187. package/src/Utils/chat-utils.ts +0 -860
  188. package/src/Utils/crypto.ts +0 -131
  189. package/src/Utils/decode-wa-message.js +0 -211
  190. package/src/Utils/decode-wa-message.ts +0 -228
  191. package/src/Utils/event-buffer.ts +0 -613
  192. package/src/Utils/generics.ts +0 -434
  193. package/src/Utils/history.ts +0 -112
  194. package/src/Utils/index.ts +0 -17
  195. package/src/Utils/link-preview.ts +0 -122
  196. package/src/Utils/logger.ts +0 -3
  197. package/src/Utils/lt-hash.ts +0 -61
  198. package/src/Utils/make-mutex.ts +0 -44
  199. package/src/Utils/messages-media.ts +0 -847
  200. package/src/Utils/messages.ts +0 -956
  201. package/src/Utils/noise-handler.ts +0 -197
  202. package/src/Utils/process-message.ts +0 -414
  203. package/src/Utils/signal.ts +0 -177
  204. package/src/Utils/use-multi-file-auth-state.ts +0 -90
  205. package/src/Utils/validate-connection.ts +0 -238
  206. package/src/WABinary/constants.ts +0 -42
  207. package/src/WABinary/decode.ts +0 -265
  208. package/src/WABinary/encode.ts +0 -236
  209. package/src/WABinary/generic-utils.ts +0 -121
  210. package/src/WABinary/index.ts +0 -5
  211. package/src/WABinary/jid-utils.ts +0 -68
  212. package/src/WABinary/types.ts +0 -17
  213. package/src/WAM/BinaryInfo.ts +0 -12
  214. package/src/WAM/constants.ts +0 -15382
  215. package/src/WAM/encode.ts +0 -174
  216. package/src/WAM/index.ts +0 -3
  217. package/src/gifted +0 -1
  218. package/src/index.ts +0 -13
  219. /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
  220. /package/{src → lib}/Socket/Client/abstract-socket-client.js +0 -0
  221. /package/{src → lib}/Store/index.js +0 -0
  222. /package/{src → lib}/Store/make-ordered-dictionary.js +0 -0
  223. /package/{src → lib}/Types/Auth.js +0 -0
  224. /package/{src → lib}/Types/Call.js +0 -0
  225. /package/{src → lib}/Types/Chat.js +0 -0
  226. /package/{src → lib}/Types/Contact.js +0 -0
  227. /package/{src → lib}/Types/Events.js +0 -0
  228. /package/{src → lib}/Types/GroupMetadata.js +0 -0
  229. /package/{src → lib}/Types/Label.js +0 -0
  230. /package/{src → lib}/Types/LabelAssociation.js +0 -0
  231. /package/{src → lib}/Types/Message.js +0 -0
  232. /package/{src → lib}/Types/Newsletter.js +0 -0
  233. /package/{src → lib}/Types/Product.js +0 -0
  234. /package/{src → lib}/Types/Signal.js +0 -0
  235. /package/{src → lib}/Types/Socket.js +0 -0
  236. /package/{src → lib}/Types/State.js +0 -0
  237. /package/{src/WABinary/types.js → lib/Types/USync.js} +0 -0
  238. /package/{src → lib}/Types/index.js +0 -0
  239. /package/{src → lib}/Utils/index.js +0 -0
  240. /package/{src → lib}/Utils/logger.js +0 -0
  241. /package/{src → lib}/Utils/lt-hash.js +0 -0
  242. /package/{src → lib}/Utils/noise-handler.js +0 -0
  243. /package/{src → lib}/WABinary/constants.js +0 -0
  244. /package/{src → lib}/WABinary/decode.js +0 -0
  245. /package/{src → lib}/WABinary/generic-utils.js +0 -0
  246. /package/{src → lib}/WABinary/index.js +0 -0
  247. /package/{src → lib}/WABinary/jid-utils.js +0 -0
  248. /package/{src → lib}/WAM/BinaryInfo.js +0 -0
  249. /package/{src → lib}/WAM/constants.js +0 -0
  250. /package/{src → lib}/WAM/encode.js +0 -0
  251. /package/{src → lib}/WAM/index.js +0 -0
@@ -1,13 +1,4 @@
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
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -17,25 +8,27 @@ const boom_1 = require("@hapi/boom");
17
8
  const node_cache_1 = __importDefault(require("node-cache"));
18
9
  const WAProto_1 = require("../../WAProto");
19
10
  const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
20
12
  const Utils_1 = require("../Utils");
21
13
  const link_preview_1 = require("../Utils/link-preview");
22
14
  const WABinary_1 = require("../WABinary");
15
+ const WAUSync_1 = require("../WAUSync");
23
16
  const newsletter_1 = require("./newsletter");
24
17
  var ListType = WAProto_1.proto.Message.ListMessage.ListType;
25
18
  const makeMessagesSocket = (config) => {
26
19
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
27
20
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
28
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral } = sock;
21
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupQuery, newsletterWMexQuery, groupToggleEphemeral } = sock;
29
22
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
30
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
23
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
31
24
  useClones: false
32
25
  });
33
26
  let mediaConn;
34
- const refreshMediaConn = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (forceGet = false) {
35
- const media = yield mediaConn;
27
+ const refreshMediaConn = async (forceGet = false) => {
28
+ const media = await mediaConn;
36
29
  if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
37
- mediaConn = (() => __awaiter(void 0, void 0, void 0, function* () {
38
- const result = yield query({
30
+ mediaConn = (async () => {
31
+ const result = await query({
39
32
  tag: 'iq',
40
33
  attrs: {
41
34
  type: 'set',
@@ -56,15 +49,15 @@ const makeMessagesSocket = (config) => {
56
49
  };
57
50
  logger.debug('fetched media conn');
58
51
  return node;
59
- }))();
52
+ })();
60
53
  }
61
54
  return mediaConn;
62
- });
55
+ };
63
56
  /**
64
57
  * generic send receipt function
65
58
  * used for receipts of phone call, read, delivery etc.
66
59
  * */
67
- const sendReceipt = (jid, participant, messageIds, type) => __awaiter(void 0, void 0, void 0, function* () {
60
+ const sendReceipt = async (jid, participant, messageIds, type) => {
68
61
  const node = {
69
62
  tag: 'receipt',
70
63
  attrs: {
@@ -102,93 +95,110 @@ const makeMessagesSocket = (config) => {
102
95
  ];
103
96
  }
104
97
  logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
105
- yield sendNode(node);
106
- });
98
+ await sendNode(node);
99
+ };
107
100
  /** Correctly bulk send receipts to multiple chats, participants */
108
- const sendReceipts = (keys, type) => __awaiter(void 0, void 0, void 0, function* () {
101
+ const sendReceipts = async (keys, type) => {
109
102
  const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
110
103
  for (const { jid, participant, messageIds } of recps) {
111
- yield sendReceipt(jid, participant, messageIds, type);
104
+ await sendReceipt(jid, participant, messageIds, type);
112
105
  }
113
- });
106
+ };
114
107
  /** Bulk read messages. Keys can be from different chats & participants */
115
- const readMessages = (keys) => __awaiter(void 0, void 0, void 0, function* () {
116
- const privacySettings = yield fetchPrivacySettings();
108
+ const readMessages = async (keys) => {
109
+ const privacySettings = await fetchPrivacySettings();
117
110
  // based on privacy settings, we have to change the read type
118
111
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
119
- yield sendReceipts(keys, readType);
120
- });
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
+ };
121
151
  /** Fetch all the devices we've to send a message to */
122
- const getUSyncDevices = (jids, useCache, ignoreZeroDevices) => __awaiter(void 0, void 0, void 0, function* () {
152
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
123
153
  var _a;
124
154
  const deviceResults = [];
125
155
  if (!useCache) {
126
156
  logger.debug('not using cache for devices');
127
157
  }
128
- const users = [];
158
+ const toFetch = [];
129
159
  jids = Array.from(new Set(jids));
130
160
  for (let jid of jids) {
131
161
  const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
132
162
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
133
- const devices = userDevicesCache.get(user);
134
- if (devices && useCache) {
135
- deviceResults.push(...devices);
136
- logger.trace({ user }, 'using cache for devices');
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
+ }
137
172
  }
138
173
  else {
139
- users.push({ tag: 'user', attrs: { jid } });
174
+ toFetch.push(jid);
140
175
  }
141
176
  }
142
- if (!users.length) {
177
+ if (!toFetch.length) {
143
178
  return deviceResults;
144
179
  }
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]);
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
+ }
188
198
  }
189
199
  return deviceResults;
190
- });
191
- const assertSessions = (jids, force) => __awaiter(void 0, void 0, void 0, function* () {
200
+ };
201
+ const assertSessions = async (jids, force) => {
192
202
  let didFetchNewSession = false;
193
203
  let jidsRequiringFetch = [];
194
204
  if (force) {
@@ -197,7 +207,7 @@ const makeMessagesSocket = (config) => {
197
207
  else {
198
208
  const addrs = jids.map(jid => (signalRepository
199
209
  .jidToSignalProtocolAddress(jid)));
200
- const sessions = yield authState.keys.get('session', addrs);
210
+ const sessions = await authState.keys.get('session', addrs);
201
211
  for (const jid of jids) {
202
212
  const signalId = signalRepository
203
213
  .jidToSignalProtocolAddress(jid);
@@ -208,7 +218,7 @@ const makeMessagesSocket = (config) => {
208
218
  }
209
219
  if (jidsRequiringFetch.length) {
210
220
  logger.debug({ jidsRequiringFetch }, 'fetching sessions');
211
- const result = yield query({
221
+ const result = await query({
212
222
  tag: 'iq',
213
223
  attrs: {
214
224
  xmlns: 'encrypt',
@@ -226,17 +236,39 @@ const makeMessagesSocket = (config) => {
226
236
  }
227
237
  ]
228
238
  });
229
- yield (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
239
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
230
240
  didFetchNewSession = true;
231
241
  }
232
242
  return didFetchNewSession;
233
- });
234
- const createParticipantNodes = (jids, message, extraAttrs) => __awaiter(void 0, void 0, void 0, function* () {
235
- const patched = yield patchMessageBeforeSending(message, jids);
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);
236
268
  const bytes = (0, Utils_1.encodeWAMessage)(patched);
237
269
  let shouldIncludeDeviceIdentity = false;
238
- const nodes = yield Promise.all(jids.map((jid) => __awaiter(void 0, void 0, void 0, function* () {
239
- const { type, ciphertext } = yield signalRepository
270
+ const nodes = await Promise.all(jids.map(async (jid) => {
271
+ const { type, ciphertext } = await signalRepository
240
272
  .encryptMessage({ jid, data: bytes });
241
273
  if (type === 'pkmsg') {
242
274
  shouldIncludeDeviceIdentity = true;
@@ -246,15 +278,19 @@ const makeMessagesSocket = (config) => {
246
278
  attrs: { jid },
247
279
  content: [{
248
280
  tag: 'enc',
249
- attrs: Object.assign({ v: '2', type }, extraAttrs || {}),
281
+ attrs: {
282
+ v: '2',
283
+ type,
284
+ ...extraAttrs || {}
285
+ },
250
286
  content: ciphertext
251
287
  }]
252
288
  };
253
289
  return node;
254
- })));
290
+ }));
255
291
  return { nodes, shouldIncludeDeviceIdentity };
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 }) {
292
+ }; //apela
293
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, statusJidList }) => {
258
294
  const meId = authState.creds.me.id;
259
295
  let shouldIncludeDeviceIdentity = false;
260
296
  const { user, server } = (0, WABinary_1.jidDecode)(jid);
@@ -262,6 +298,7 @@ const makeMessagesSocket = (config) => {
262
298
  const isGroup = server === 'g.us';
263
299
  const isStatus = jid === statusJid;
264
300
  const isLid = server === 'lid';
301
+ const isPrivate = server === 's.whatsapp.net';
265
302
  const isNewsletter = server === 'newsletter';
266
303
  msgId = msgId || (0, Utils_1.generateMessageID)();
267
304
  useUserDevicesCache = useUserDevicesCache !== false;
@@ -280,45 +317,45 @@ const makeMessagesSocket = (config) => {
280
317
  // only send to the specific device that asked for a retry
281
318
  // otherwise the message is sent out to every device that should be a recipient
282
319
  if (!isGroup && !isStatus) {
283
- additionalAttributes = Object.assign(Object.assign({}, additionalAttributes), { 'device_fanout': 'false' });
320
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
284
321
  }
285
322
  const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
286
323
  devices.push({ user, device });
287
324
  }
288
- yield authState.keys.transaction(() => __awaiter(void 0, void 0, void 0, function* () {
325
+ await authState.keys.transaction(async () => {
289
326
  var _a, _b, _c, _d, _e, _f;
290
327
  const mediaType = getMediaType(message);
291
328
  if (isGroup || isStatus) {
292
- const [groupData, senderKeyMap] = yield Promise.all([
293
- (() => __awaiter(void 0, void 0, void 0, function* () {
294
- let groupData = cachedGroupMetadata ? yield cachedGroupMetadata(jid) : undefined;
329
+ const [groupData, senderKeyMap] = await Promise.all([
330
+ (async () => {
331
+ let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
295
332
  if (groupData) {
296
333
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
297
334
  }
298
335
  if (!groupData && !isStatus) {
299
- groupData = yield groupMetadata(jid);
336
+ groupData = await groupMetadata(jid);
300
337
  }
301
338
  return groupData;
302
- }))(),
303
- (() => __awaiter(void 0, void 0, void 0, function* () {
339
+ })(),
340
+ (async () => {
304
341
  if (!participant && !isStatus) {
305
- const result = yield authState.keys.get('sender-key-memory', [jid]);
342
+ const result = await authState.keys.get('sender-key-memory', [jid]);
306
343
  return result[jid] || {};
307
344
  }
308
345
  return {};
309
- }))()
346
+ })()
310
347
  ]);
311
348
  if (!participant) {
312
349
  const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
313
350
  if (isStatus && statusJidList) {
314
351
  participantsList.push(...statusJidList);
315
352
  }
316
- const additionalDevices = yield getUSyncDevices(participantsList, !!useUserDevicesCache, false);
353
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
317
354
  devices.push(...additionalDevices);
318
355
  }
319
- const patched = yield patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
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)));
320
357
  const bytes = (0, Utils_1.encodeWAMessage)(patched);
321
- const { ciphertext, senderKeyDistributionMessage } = yield signalRepository.encryptGroupMessage({
358
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
322
359
  group: destinationJid,
323
360
  data: bytes,
324
361
  meId,
@@ -343,8 +380,8 @@ const makeMessagesSocket = (config) => {
343
380
  groupId: destinationJid
344
381
  }
345
382
  };
346
- yield assertSessions(senderKeyJids, false);
347
- const result = yield createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
383
+ await assertSessions(senderKeyJids, false);
384
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
348
385
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
349
386
  participants.push(...result.nodes);
350
387
  }
@@ -353,7 +390,7 @@ const makeMessagesSocket = (config) => {
353
390
  attrs: { v: '2', type: 'skmsg' },
354
391
  content: ciphertext
355
392
  });
356
- yield authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
393
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
357
394
  }
358
395
  else if (isNewsletter) {
359
396
  // Message edit
@@ -366,7 +403,7 @@ const makeMessagesSocket = (config) => {
366
403
  msgId = (_d = message.protocolMessage.key) === null || _d === void 0 ? void 0 : _d.id;
367
404
  message = {};
368
405
  }
369
- const patched = yield patchMessageBeforeSending(message, []);
406
+ const patched = await patchMessageBeforeSending(message, []);
370
407
  const bytes = WAProto_1.proto.Message.encode(patched).finish();
371
408
  binaryNodeContent.push({
372
409
  tag: 'plaintext',
@@ -382,7 +419,7 @@ const makeMessagesSocket = (config) => {
382
419
  if (meDevice !== undefined && meDevice !== 0) {
383
420
  devices.push({ user: meUser });
384
421
  }
385
- const additionalDevices = yield getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
422
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
386
423
  devices.push(...additionalDevices);
387
424
  }
388
425
  const allJids = [];
@@ -390,7 +427,7 @@ const makeMessagesSocket = (config) => {
390
427
  const otherJids = [];
391
428
  for (const { user, device } of devices) {
392
429
  const isMe = user === meUser;
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);
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);
394
431
  if (isMe) {
395
432
  meJids.push(jid);
396
433
  }
@@ -399,8 +436,8 @@ const makeMessagesSocket = (config) => {
399
436
  }
400
437
  allJids.push(jid);
401
438
  }
402
- yield assertSessions(allJids, false);
403
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = yield Promise.all([
439
+ await assertSessions(allJids, false);
440
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
404
441
  createParticipantNodes(meJids, meMsg, mediaType ? { mediatype: mediaType } : undefined),
405
442
  createParticipantNodes(otherJids, message, mediaType ? { mediatype: mediaType } : undefined)
406
443
  ]);
@@ -417,7 +454,11 @@ const makeMessagesSocket = (config) => {
417
454
  }
418
455
  const stanza = {
419
456
  tag: 'message',
420
- attrs: Object.assign({ id: msgId, type: isNewsletter ? getTypeMessage(message) : 'text' }, (additionalAttributes || {})),
457
+ attrs: {
458
+ id: msgId,
459
+ type: isNewsletter ? getTypeMessage(message) : 'text',
460
+ ...(additionalAttributes || {})
461
+ },
421
462
  content: binaryNodeContent
422
463
  };
423
464
  // if the participant to send to is explicitly specified (generally retry recp)
@@ -450,44 +491,92 @@ const makeMessagesSocket = (config) => {
450
491
  if (additionalNodes && additionalNodes.length > 0) {
451
492
  stanza.content.push(...additionalNodes);
452
493
  }
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
- });
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);
470
533
  }
471
534
  }
472
- const buttonType = getButtonType(message);
473
- if (buttonType) {
535
+ if (message && message.listMessage) {
474
536
  stanza.content.push({
475
537
  tag: 'biz',
476
538
  attrs: {},
477
539
  content: [
478
540
  {
479
- tag: buttonType,
480
- attrs: getButtonArgs(message),
541
+ tag: 'list',
542
+ attrs: getButtonArgs(message)
481
543
  }
482
544
  ]
483
545
  });
484
546
  logger.debug({ jid }, 'adding business node');
485
547
  }
486
548
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
487
- yield sendNode(stanza);
488
- }));
549
+ await sendNode(stanza);
550
+ });
489
551
  return msgId;
490
- });
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
+ };
491
580
  const getTypeMessage = (msg) => {
492
581
  if (msg.viewOnceMessage) {
493
582
  return getTypeMessage(msg.viewOnceMessage.message);
@@ -508,7 +597,7 @@ const makeMessagesSocket = (config) => {
508
597
  return 'reaction';
509
598
  }
510
599
  else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
511
- return 'reaction';
600
+ return 'poll';
512
601
  }
513
602
  else if (getMediaType(msg)) {
514
603
  return 'media';
@@ -560,22 +649,8 @@ const makeMessagesSocket = (config) => {
560
649
  else if (message.interactiveResponseMessage) {
561
650
  return 'native_flow_response';
562
651
  }
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';
652
+ else if (message.groupInviteMessage) {
653
+ return 'url';
579
654
  }
580
655
  };
581
656
  const getButtonArgs = (message) => {
@@ -594,9 +669,9 @@ const makeMessagesSocket = (config) => {
594
669
  return {};
595
670
  }
596
671
  };
597
- const getPrivacyTokens = (jids) => __awaiter(void 0, void 0, void 0, function* () {
672
+ const getPrivacyTokens = async (jids) => {
598
673
  const t = (0, Utils_1.unixTimestampSeconds)().toString();
599
- const result = yield query({
674
+ const result = await query({
600
675
  tag: 'iq',
601
676
  attrs: {
602
677
  to: WABinary_1.S_WHATSAPP_NET,
@@ -619,10 +694,12 @@ const makeMessagesSocket = (config) => {
619
694
  ]
620
695
  });
621
696
  return result;
622
- });
697
+ };
623
698
  const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
624
699
  const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
625
- return Object.assign(Object.assign({}, sock), { getPrivacyTokens,
700
+ return {
701
+ ...sock,
702
+ getPrivacyTokens,
626
703
  assertSessions,
627
704
  relayMessage,
628
705
  sendReceipt,
@@ -631,15 +708,18 @@ const makeMessagesSocket = (config) => {
631
708
  readMessages,
632
709
  refreshMediaConn,
633
710
  getUSyncDevices,
711
+ sendPeerDataOperationMessage,
634
712
  createParticipantNodes,
713
+ profilePictureUrl,
635
714
  waUploadToServer,
636
- fetchPrivacySettings, updateMediaMessage: (message) => __awaiter(void 0, void 0, void 0, function* () {
715
+ fetchPrivacySettings,
716
+ updateMediaMessage: async (message) => {
637
717
  const content = (0, Utils_1.assertMediaContent)(message.message);
638
718
  const mediaKey = content.mediaKey;
639
719
  const meId = authState.creds.me.id;
640
720
  const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
641
721
  let error = undefined;
642
- yield Promise.all([
722
+ await Promise.all([
643
723
  sendNode(node),
644
724
  waitForMsgMediaUpdate(update => {
645
725
  const result = update.find(c => c.key.id === message.key.id);
@@ -650,7 +730,7 @@ const makeMessagesSocket = (config) => {
650
730
  else {
651
731
  try {
652
732
  const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
653
- if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
733
+ if (media && media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
654
734
  const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
655
735
  throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
656
736
  }
@@ -673,8 +753,168 @@ const makeMessagesSocket = (config) => {
673
753
  { key: message.key, update: { message: message.message } }
674
754
  ]);
675
755
  return message;
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;
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;
678
918
  const userJid = authState.creds.me.id;
679
919
  if (typeof content === 'object' &&
680
920
  'disappearingMessagesInChat' in content &&
@@ -684,32 +924,60 @@ const makeMessagesSocket = (config) => {
684
924
  const value = typeof disappearingMessagesInChat === 'boolean' ?
685
925
  (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
686
926
  disappearingMessagesInChat;
687
- yield groupToggleEphemeral(jid, value);
927
+ await groupToggleEphemeral(jid, value);
688
928
  }
689
929
  else {
690
930
  let mediaHandle;
691
- const fullMsg = yield (0, Utils_1.generateWAMessage)(jid, content, Object.assign({ logger,
692
- userJid, getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
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, {
693
950
  thumbnailWidth: linkPreviewImageThumbnailWidth,
694
- fetchOpts: Object.assign({ timeout: 3000 }, axiosOptions || {}),
951
+ fetchOpts: {
952
+ timeout: 3000,
953
+ ...axiosOptions || {}
954
+ },
695
955
  logger,
696
956
  uploadImage: generateHighQualityLinkPreview
697
957
  ? waUploadToServer
698
958
  : undefined
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) }));
959
+ }),
960
+ upload: async (readStream, opts) => {
961
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
701
962
  mediaHandle = up.handle;
702
963
  return up;
703
- }), mediaCache: config.mediaCache, options: config.options }, options));
704
- const isDeleteMsg = 'delete' in content && !!content.delete;
705
- const isEditMsg = 'edit' in content && !!content.edit;
964
+ },
965
+ mediaCache: config.mediaCache,
966
+ options: config.options,
967
+ ...options,
968
+ });
706
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;
974
+ const isDeleteMsg = 'delete' in content && !!content.delete;
707
975
  const additionalAttributes = {};
708
976
  const additionalNodes = [];
709
977
  // required for delete
710
978
  if (isDeleteMsg) {
711
979
  // if the chat is a group, and I am not the author, then delete the message as an admin
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)) {
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)) {
713
981
  additionalAttributes.edit = '8';
714
982
  }
715
983
  else {
@@ -719,13 +987,19 @@ const makeMessagesSocket = (config) => {
719
987
  else if (isEditMsg) {
720
988
  additionalAttributes.edit = (0, WABinary_1.isJidNewsLetter)(jid) ? '3' : '1';
721
989
  }
990
+ else if (isPinMsg) {
991
+ additionalAttributes.edit = '2';
992
+ }
722
993
  else if (isAiMsg) {
723
994
  additionalNodes.push({
724
995
  attrs: {
725
996
  biz_bot: '1'
726
997
  },
727
- tag: "bot"
998
+ tag: 'bot'
728
999
  });
1000
+ if (options.additionalNodes) {
1001
+ additionalNodes.push(...options.additionalNodes);
1002
+ }
729
1003
  }
730
1004
  if (mediaHandle) {
731
1005
  additionalAttributes['media_id'] = mediaHandle;
@@ -733,7 +1007,7 @@ const makeMessagesSocket = (config) => {
733
1007
  if ('cachedGroupMetadata' in options) {
734
1008
  console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
735
1009
  }
736
- yield relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
1010
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
737
1011
  if (config.emitOwnEvents) {
738
1012
  process.nextTick(() => {
739
1013
  processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
@@ -741,6 +1015,7 @@ const makeMessagesSocket = (config) => {
741
1015
  }
742
1016
  return fullMsg;
743
1017
  }
744
- }) });
1018
+ }
1019
+ };
745
1020
  };
746
1021
  exports.makeMessagesSocket = makeMessagesSocket;