@pney/whatsapp-web 1.34.6 → 1.34.7-2

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 (59) hide show
  1. package/.env.example +0 -1
  2. package/.gitattributes +4 -0
  3. package/.husky/commit-msg +4 -0
  4. package/.husky/pre-commit +1 -0
  5. package/.lintstagedrc.json +6 -0
  6. package/.prettierignore +8 -0
  7. package/.prettierrc.json +10 -0
  8. package/README.md +83 -80
  9. package/commitlint.config.js +29 -0
  10. package/eslint.config.mjs +67 -0
  11. package/example.js +151 -71
  12. package/index.d.ts +982 -734
  13. package/index.js +4 -4
  14. package/package.json +3 -3
  15. package/shell.js +4 -4
  16. package/src/Client.js +1860 -920
  17. package/src/authStrategies/BaseAuthStrategy.js +4 -2
  18. package/src/authStrategies/LocalAuth.js +25 -12
  19. package/src/authStrategies/NoAuth.js +3 -4
  20. package/src/authStrategies/RemoteAuth.js +92 -43
  21. package/src/factories/ChatFactory.js +1 -1
  22. package/src/factories/ContactFactory.js +2 -2
  23. package/src/structures/Base.js +5 -3
  24. package/src/structures/Broadcast.js +1 -2
  25. package/src/structures/BusinessContact.js +1 -2
  26. package/src/structures/Buttons.js +14 -10
  27. package/src/structures/Call.js +10 -6
  28. package/src/structures/Channel.js +171 -91
  29. package/src/structures/Chat.js +57 -41
  30. package/src/structures/ClientInfo.js +1 -1
  31. package/src/structures/Contact.js +37 -16
  32. package/src/structures/GroupChat.js +425 -228
  33. package/src/structures/GroupNotification.js +21 -12
  34. package/src/structures/Label.js +6 -6
  35. package/src/structures/List.js +22 -14
  36. package/src/structures/Location.js +5 -4
  37. package/src/structures/Message.js +412 -168
  38. package/src/structures/MessageMedia.js +31 -18
  39. package/src/structures/Order.js +4 -4
  40. package/src/structures/Payment.js +6 -3
  41. package/src/structures/Poll.js +2 -2
  42. package/src/structures/PollVote.js +9 -6
  43. package/src/structures/PrivateChat.js +2 -4
  44. package/src/structures/PrivateContact.js +2 -4
  45. package/src/structures/Product.js +1 -1
  46. package/src/structures/ProductMetadata.js +1 -2
  47. package/src/structures/Reaction.js +2 -4
  48. package/src/structures/ScheduledEvent.js +22 -10
  49. package/src/util/Constants.js +8 -6
  50. package/src/util/Injected/AuthStore/AuthStore.js +7 -3
  51. package/src/util/Injected/Utils.js +753 -345
  52. package/src/util/InterfaceController.js +72 -25
  53. package/src/util/Puppeteer.js +1 -1
  54. package/src/util/Util.js +28 -15
  55. package/src/webCache/LocalWebCache.js +7 -5
  56. package/src/webCache/RemoteWebCache.js +10 -4
  57. package/src/webCache/WebCache.js +8 -5
  58. package/src/webCache/WebCacheFactory.js +9 -9
  59. package/CODE_OF_CONDUCT.md +0 -133
@@ -12,15 +12,20 @@ exports.LoadUtils = () => {
12
12
  */
13
13
  window.WWebJS.compareWwebVersions = (lOperand, operator, rOperand) => {
14
14
  if (!['>', '>=', '<', '<=', '='].includes(operator)) {
15
- throw new class _ extends Error {
16
- constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
17
- }('Invalid comparison operator is provided');
18
-
15
+ throw new (class _ extends Error {
16
+ constructor(m) {
17
+ super(m);
18
+ this.name = 'CompareWwebVersionsError';
19
+ }
20
+ })('Invalid comparison operator is provided');
19
21
  }
20
22
  if (typeof lOperand !== 'string' || typeof rOperand !== 'string') {
21
- throw new class _ extends Error {
22
- constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
23
- }('A non-string WWeb version type is provided');
23
+ throw new (class _ extends Error {
24
+ constructor(m) {
25
+ super(m);
26
+ this.name = 'CompareWwebVersionsError';
27
+ }
28
+ })('A non-string WWeb version type is provided');
24
29
  }
25
30
 
26
31
  lOperand = lOperand.replace(/-beta$/, '');
@@ -28,21 +33,24 @@ exports.LoadUtils = () => {
28
33
 
29
34
  while (lOperand.length !== rOperand.length) {
30
35
  lOperand.length > rOperand.length
31
- ? rOperand = rOperand.concat('0')
32
- : lOperand = lOperand.concat('0');
36
+ ? (rOperand = rOperand.concat('0'))
37
+ : (lOperand = lOperand.concat('0'));
33
38
  }
34
39
 
35
40
  lOperand = Number(lOperand.replace(/\./g, ''));
36
41
  rOperand = Number(rOperand.replace(/\./g, ''));
37
42
 
38
- return (
39
- operator === '>' ? lOperand > rOperand :
40
- operator === '>=' ? lOperand >= rOperand :
41
- operator === '<' ? lOperand < rOperand :
42
- operator === '<=' ? lOperand <= rOperand :
43
- operator === '=' ? lOperand === rOperand :
44
- false
45
- );
43
+ return operator === '>'
44
+ ? lOperand > rOperand
45
+ : operator === '>='
46
+ ? lOperand >= rOperand
47
+ : operator === '<'
48
+ ? lOperand < rOperand
49
+ : operator === '<='
50
+ ? lOperand <= rOperand
51
+ : operator === '='
52
+ ? lOperand === rOperand
53
+ : false;
46
54
  };
47
55
 
48
56
  /**
@@ -59,7 +67,7 @@ exports.LoadUtils = () => {
59
67
  window.WWebJS.injectToFunction = (target, callback) => {
60
68
  try {
61
69
  let module = window.require(target.module);
62
- if (!module) return;
70
+ if (!module) return;
63
71
 
64
72
  const path = target.function.split('.');
65
73
  const funcName = path.pop();
@@ -79,31 +87,55 @@ exports.LoadUtils = () => {
79
87
  return originalFunction.apply(module, args);
80
88
  }
81
89
  }).bind(module);
82
-
83
90
  } catch {
84
91
  return;
85
92
  }
86
93
  };
87
94
 
88
- window.WWebJS.injectToFunction({ module: 'WAWebBackendJobsCommon', function: 'mediaTypeFromProtobuf' }, (module, func, ...args) => { const [proto] = args; return proto.locationMessage ? null : func(...args); });
89
-
90
- window.WWebJS.injectToFunction({ module: 'WAWebE2EProtoUtils', function: 'typeAttributeFromProtobuf' }, (module, func, ...args) => { const [proto] = args; return proto.locationMessage || proto.groupInviteMessage ? 'text' : func(...args); });
95
+ window.WWebJS.injectToFunction(
96
+ { module: 'WAWebBackendJobsCommon', function: 'mediaTypeFromProtobuf' },
97
+ (module, func, ...args) => {
98
+ const [proto] = args;
99
+ return proto.locationMessage ? null : func(...args);
100
+ },
101
+ );
102
+
103
+ window.WWebJS.injectToFunction(
104
+ { module: 'WAWebE2EProtoUtils', function: 'typeAttributeFromProtobuf' },
105
+ (module, func, ...args) => {
106
+ const [proto] = args;
107
+ return proto.locationMessage || proto.groupInviteMessage
108
+ ? 'text'
109
+ : func(...args);
110
+ },
111
+ );
91
112
 
92
-
93
113
  window.WWebJS.forwardMessage = async (chatId, msgId) => {
94
- const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
114
+ const msg =
115
+ window.require('WAWebCollections').Msg.get(msgId) ||
116
+ (
117
+ await window
118
+ .require('WAWebCollections')
119
+ .Msg.getMessagesById([msgId])
120
+ )?.messages?.[0];
95
121
  const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
96
- return await (window.require('WAWebChatForwardMessage')).forwardMessages({'chat': chat, 'msgs' : [msg], 'multicast': true, 'includeCaption': true, 'appendedText' : undefined});
122
+ return await window.require('WAWebChatForwardMessage').forwardMessages({
123
+ chat: chat,
124
+ msgs: [msg],
125
+ multicast: true,
126
+ includeCaption: true,
127
+ appendedText: undefined,
128
+ });
97
129
  };
98
130
 
99
131
  window.WWebJS.sendSeen = async (chatId) => {
100
132
  const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
101
133
  if (chat) {
102
134
  window.require('WAWebStreamModel').Stream.markAvailable();
103
- await (window.require('WAWebUpdateUnreadChatAction')).sendSeen({
135
+ await window.require('WAWebUpdateUnreadChatAction').sendSeen({
104
136
  chat: chat,
105
- threadId: undefined
106
- });
137
+ threadId: undefined,
138
+ });
107
139
  window.require('WAWebStreamModel').Stream.markUnavailable();
108
140
  return true;
109
141
  }
@@ -111,27 +143,31 @@ exports.LoadUtils = () => {
111
143
  };
112
144
 
113
145
  window.WWebJS.sendMessage = async (chat, content, options = {}) => {
114
- const { getIsNewsletter, getIsBroadcast } = window.require('WAWebChatGetters');
146
+ const { getIsNewsletter, getIsBroadcast } =
147
+ window.require('WAWebChatGetters');
115
148
  const isChannel = getIsNewsletter(chat);
116
149
  const isStatus = getIsBroadcast(chat);
117
150
 
118
151
  const { findLink } = window.require('WALinkify');
119
-
152
+
120
153
  let mediaOptions = {};
121
154
  if (options.media) {
122
- mediaOptions = options.sendMediaAsSticker && !isChannel && !isStatus
123
- ? await window.WWebJS.processStickerData(options.media)
124
- : await window.WWebJS.processMediaData(options.media, {
125
- forceSticker: options.sendMediaAsSticker,
126
- forceGif: options.sendVideoAsGif,
127
- forceVoice: options.sendAudioAsVoice,
128
- forceDocument: options.sendMediaAsDocument,
129
- forceMediaHd: options.sendMediaAsHd,
130
- sendToChannel: isChannel,
131
- sendToStatus: isStatus
132
- });
155
+ mediaOptions =
156
+ options.sendMediaAsSticker && !isChannel && !isStatus
157
+ ? await window.WWebJS.processStickerData(options.media)
158
+ : await window.WWebJS.processMediaData(options.media, {
159
+ forceSticker: options.sendMediaAsSticker,
160
+ forceGif: options.sendVideoAsGif,
161
+ forceVoice: options.sendAudioAsVoice,
162
+ forceDocument: options.sendMediaAsDocument,
163
+ forceMediaHd: options.sendMediaAsHd,
164
+ sendToChannel: isChannel,
165
+ sendToStatus: isStatus,
166
+ });
133
167
  mediaOptions.caption = options.caption;
134
- content = options.sendMediaAsSticker ? undefined : mediaOptions.preview;
168
+ content = options.sendMediaAsSticker
169
+ ? undefined
170
+ : mediaOptions.preview;
135
171
  mediaOptions.isViewOnce = options.isViewOnce;
136
172
  delete options.media;
137
173
  delete options.sendMediaAsSticker;
@@ -139,10 +175,16 @@ exports.LoadUtils = () => {
139
175
 
140
176
  let quotedMsgOptions = {};
141
177
  if (options.quotedMessageId) {
142
- let quotedMessage = (window.require('WAWebCollections')).Msg.get(options.quotedMessageId);
143
- !quotedMessage && (quotedMessage = (await (window.require('WAWebCollections')).Msg.getMessagesById([options.quotedMessageId]))?.messages?.[0]);
178
+ let quotedMessage = window
179
+ .require('WAWebCollections')
180
+ .Msg.get(options.quotedMessageId);
181
+ !quotedMessage &&
182
+ (quotedMessage = (
183
+ await window
184
+ .require('WAWebCollections')
185
+ .Msg.getMessagesById([options.quotedMessageId])
186
+ )?.messages?.[0]);
144
187
  if (quotedMessage) {
145
-
146
188
  const ReplyUtils = window.require('WAWebMsgReply');
147
189
  const canReply = ReplyUtils
148
190
  ? ReplyUtils.canReplyMsg(quotedMessage.unsafe())
@@ -156,20 +198,22 @@ exports.LoadUtils = () => {
156
198
  throw new Error('Could not get the quoted message.');
157
199
  }
158
200
  }
159
-
201
+
160
202
  delete options.ignoreQuoteErrors;
161
203
  delete options.quotedMessageId;
162
204
  }
163
205
 
164
206
  if (options.mentionedJidList) {
165
- options.mentionedJidList = options.mentionedJidList.map((id) => window.require('WAWebWidFactory').createWid(id));
207
+ options.mentionedJidList = options.mentionedJidList.map((id) =>
208
+ window.require('WAWebWidFactory').createWid(id),
209
+ );
166
210
  options.mentionedJidList = options.mentionedJidList.filter(Boolean);
167
211
  }
168
212
 
169
213
  if (options.groupMentions) {
170
214
  options.groupMentions = options.groupMentions.map((e) => ({
171
215
  groupSubject: e.subject,
172
- groupJid: window.require('WAWebWidFactory').createWid(e.id)
216
+ groupJid: window.require('WAWebWidFactory').createWid(e.id),
173
217
  }));
174
218
  }
175
219
 
@@ -183,7 +227,7 @@ exports.LoadUtils = () => {
183
227
  loc: description,
184
228
  lat: latitude,
185
229
  lng: longitude,
186
- clientUrl: url
230
+ clientUrl: url,
187
231
  };
188
232
  delete options.location;
189
233
  }
@@ -191,7 +235,8 @@ exports.LoadUtils = () => {
191
235
  let pollOptions = {};
192
236
  if (options.poll) {
193
237
  const { pollName, pollOptions: _pollOptions } = options.poll;
194
- const { allowMultipleAnswers, messageSecret } = options.poll.options;
238
+ const { allowMultipleAnswers, messageSecret } =
239
+ options.poll.options;
195
240
  pollOptions = {
196
241
  kind: 'pollCreation',
197
242
  type: 'poll_creation',
@@ -201,7 +246,7 @@ exports.LoadUtils = () => {
201
246
  messageSecret:
202
247
  Array.isArray(messageSecret) && messageSecret.length === 32
203
248
  ? new Uint8Array(messageSecret)
204
- : window.crypto.getRandomValues(new Uint8Array(32))
249
+ : window.crypto.getRandomValues(new Uint8Array(32)),
205
250
  };
206
251
  delete options.poll;
207
252
  }
@@ -219,12 +264,17 @@ exports.LoadUtils = () => {
219
264
  eventLocation: eventSendOptions.location && {
220
265
  degreesLatitude: 0,
221
266
  degreesLongitude: 0,
222
- name: eventSendOptions.location
267
+ name: eventSendOptions.location,
223
268
  },
224
- eventJoinLink: eventSendOptions.callType === 'none' ? null : await (window.require('WAWebGenerateEventCallLink')).createEventCallLink(
225
- startTimeTs,
226
- eventSendOptions.callType
227
- ),
269
+ eventJoinLink:
270
+ eventSendOptions.callType === 'none'
271
+ ? null
272
+ : await window
273
+ .require('WAWebGenerateEventCallLink')
274
+ .createEventCallLink(
275
+ startTimeTs,
276
+ eventSendOptions.callType,
277
+ ),
228
278
  isEventCanceled: eventSendOptions.isEventCanceled,
229
279
  messageSecret:
230
280
  Array.isArray(messageSecret) && messageSecret.length === 32
@@ -236,34 +286,54 @@ exports.LoadUtils = () => {
236
286
 
237
287
  let vcardOptions = {};
238
288
  if (options.contactCard) {
239
- let contact = (window.require('WAWebCollections')).Contact.get(options.contactCard);
289
+ let contact = await window
290
+ .require('WAWebCollections')
291
+ .Contact.find(options.contactCard);
240
292
  vcardOptions = {
241
- body: window.require('WAWebFrontendVcardUtils').vcardFromContactModel(contact).vcard,
293
+ body: window
294
+ .require('WAWebFrontendVcardUtils')
295
+ .vcardFromContactModel(contact).vcard,
242
296
  type: 'vcard',
243
- vcardFormattedName: contact.formattedName
297
+ vcardFormattedName: contact.formattedName,
244
298
  };
245
299
  delete options.contactCard;
246
300
  } else if (options.contactCardList) {
247
- let contacts = options.contactCardList.map(c => (window.require('WAWebCollections')).Contact.get(c));
248
- let vcards = contacts.map(c => window.require('WAWebFrontendVcardUtils').vcardFromContactModel(c));
301
+ let contacts = await Promise.all(
302
+ options.contactCardList.map((c) =>
303
+ window.require('WAWebCollections').Contact.find(c),
304
+ ),
305
+ );
306
+ let vcards = contacts.map((c) =>
307
+ window
308
+ .require('WAWebFrontendVcardUtils')
309
+ .vcardFromContactModel(c),
310
+ );
249
311
  vcardOptions = {
250
312
  type: 'multi_vcard',
251
313
  vcardList: vcards,
252
- body: null
314
+ body: null,
253
315
  };
254
316
  delete options.contactCardList;
255
- } else if (options.parseVCards && typeof (content) === 'string' && content.startsWith('BEGIN:VCARD')) {
317
+ } else if (
318
+ options.parseVCards &&
319
+ typeof content === 'string' &&
320
+ content.startsWith('BEGIN:VCARD')
321
+ ) {
256
322
  delete options.parseVCards;
257
323
  delete options.linkPreview;
258
324
  try {
259
- const parsed = window.require('WAWebVcardParsingUtils').parseVcard(content);
325
+ const parsed = window
326
+ .require('WAWebVcardParsingUtils')
327
+ .parseVcard(content);
260
328
  if (parsed) {
261
329
  vcardOptions = {
262
330
  type: 'vcard',
263
- vcardFormattedName: window.require('WAWebVcardGetNameFromParsed').vcardGetNameFromParsed(parsed)
331
+ vcardFormattedName: window
332
+ .require('WAWebVcardGetNameFromParsed')
333
+ .vcardGetNameFromParsed(parsed),
264
334
  };
265
335
  }
266
- } catch (_) {
336
+ } catch (ignoredError) {
267
337
  // not a vcard
268
338
  }
269
339
  }
@@ -272,12 +342,14 @@ exports.LoadUtils = () => {
272
342
  delete options.linkPreview;
273
343
  const link = findLink(content);
274
344
  if (link) {
275
- let preview = await (window.require('WAWebLinkPreviewChatAction')).getLinkPreview(link);
345
+ let preview = await window
346
+ .require('WAWebLinkPreviewChatAction')
347
+ .getLinkPreview(link);
276
348
  if (preview && preview.data) {
277
349
  preview = preview.data;
278
350
  preview.preview = true;
279
351
  preview.subtype = 'url';
280
- options = {...options, ...preview};
352
+ options = { ...options, ...preview };
281
353
  }
282
354
  }
283
355
  }
@@ -289,34 +361,41 @@ exports.LoadUtils = () => {
289
361
  content = options.buttons.body;
290
362
  caption = content;
291
363
  } else {
292
- caption = options.caption ? options.caption : ' '; //Caption can't be empty
364
+ caption = options.caption ? options.caption : ' '; // Caption can't be empty
293
365
  }
294
366
  buttonOptions = {
295
367
  productHeaderImageRejected: false,
296
368
  isFromTemplate: false,
297
369
  isDynamicReplyButtonsMsg: true,
298
- title: options.buttons.title ? options.buttons.title : undefined,
299
- footer: options.buttons.footer ? options.buttons.footer : undefined,
370
+ title: options.buttons.title
371
+ ? options.buttons.title
372
+ : undefined,
373
+ footer: options.buttons.footer
374
+ ? options.buttons.footer
375
+ : undefined,
300
376
  dynamicReplyButtons: options.buttons.buttons,
301
377
  replyButtons: options.buttons.buttons,
302
- caption: caption
378
+ caption: caption,
303
379
  };
304
380
  delete options.buttons;
305
381
  }
306
382
 
307
383
  let listOptions = {};
308
384
  if (options.list) {
309
- if ((window.require('WAWebConnModel').Conn).platform === 'smba' || (window.require('WAWebConnModel').Conn).platform === 'smbi') {
310
- throw '[LT01] Whatsapp business can\'t send this yet';
385
+ if (
386
+ window.require('WAWebConnModel').Conn.platform === 'smba' ||
387
+ window.require('WAWebConnModel').Conn.platform === 'smbi'
388
+ ) {
389
+ throw "[LT01] Whatsapp business can't send this yet";
311
390
  }
312
391
  listOptions = {
313
392
  type: 'list',
314
393
  footer: options.list.footer,
315
394
  list: {
316
395
  ...options.list,
317
- listType: 1
396
+ listType: 1,
318
397
  },
319
- body: options.list.description
398
+ body: options.list.description,
320
399
  };
321
400
  delete options.list;
322
401
  delete listOptions.list.footer;
@@ -324,26 +403,43 @@ exports.LoadUtils = () => {
324
403
 
325
404
  const botOptions = {};
326
405
  if (options.invokedBotWid) {
327
- botOptions.messageSecret = window.crypto.getRandomValues(new Uint8Array(32));
328
- botOptions.botMessageSecret = await (window.require('WAWebBotMessageSecret')).genBotMsgSecretFromMsgSecret(botOptions.messageSecret);
329
- botOptions.invokedBotWid = window.require('WAWebWidFactory').createWid(options.invokedBotWid);
330
- botOptions.botPersonaId = window.require('WAWebBotProfileCollection').BotProfileCollection.get(options.invokedBotWid).personaId;
406
+ botOptions.messageSecret = window.crypto.getRandomValues(
407
+ new Uint8Array(32),
408
+ );
409
+ botOptions.botMessageSecret = await window
410
+ .require('WAWebBotMessageSecret')
411
+ .genBotMsgSecretFromMsgSecret(botOptions.messageSecret);
412
+ botOptions.invokedBotWid = window
413
+ .require('WAWebWidFactory')
414
+ .createWid(options.invokedBotWid);
415
+ botOptions.botPersonaId = window
416
+ .require('WAWebBotProfileCollection')
417
+ .BotProfileCollection.get(options.invokedBotWid).personaId;
331
418
  delete options.invokedBotWid;
332
419
  }
333
- const { getMaybeMeLidUser, getMaybeMePnUser } = window.require('WAWebUserPrefsMeUser');
420
+ const { getMaybeMeLidUser, getMaybeMePnUser } = window.require(
421
+ 'WAWebUserPrefsMeUser',
422
+ );
334
423
  const lidUser = getMaybeMeLidUser();
335
424
  const meUser = getMaybeMePnUser();
336
- const newId = await (window.require('WAWebMsgKey')).newId();
425
+ const newId = await window.require('WAWebMsgKey').newId();
337
426
  let from = chat.id.isLid() ? lidUser : meUser;
338
427
  let participant;
339
428
 
340
429
  if (typeof chat.id?.isGroup === 'function' && chat.id.isGroup()) {
341
- from = chat.groupMetadata && chat.groupMetadata.isLidAddressingMode ? lidUser : meUser;
342
- participant = window.require('WAWebWidFactory').asUserWidOrThrow(from);
430
+ from =
431
+ chat.groupMetadata && chat.groupMetadata.isLidAddressingMode
432
+ ? lidUser
433
+ : meUser;
434
+ participant = window
435
+ .require('WAWebWidFactory')
436
+ .asUserWidOrThrow(from);
343
437
  }
344
438
 
345
439
  if (typeof chat.id?.isStatus === 'function' && chat.id.isStatus()) {
346
- participant = window.require('WAWebWidFactory').asUserWidOrThrow(from);
440
+ participant = window
441
+ .require('WAWebWidFactory')
442
+ .asUserWidOrThrow(from);
347
443
  }
348
444
 
349
445
  const newMsgKey = new (window.require('WAWebMsgKey'))({
@@ -357,7 +453,9 @@ exports.LoadUtils = () => {
357
453
  const extraOptions = options.extraOptions || {};
358
454
  delete options.extraOptions;
359
455
 
360
- const ephemeralFields = window.require('WAWebGetEphemeralFieldsMsgActionsUtils').getEphemeralFields(chat);
456
+ const ephemeralFields = window
457
+ .require('WAWebGetEphemeralFieldsMsgActionsUtils')
458
+ .getEphemeralFields(chat);
361
459
 
362
460
  const message = {
363
461
  ...options,
@@ -382,96 +480,126 @@ exports.LoadUtils = () => {
382
480
  ...buttonOptions,
383
481
  ...listOptions,
384
482
  ...botOptions,
385
- ...extraOptions
483
+ ...extraOptions,
386
484
  };
387
-
485
+
388
486
  // Bot's won't reply if canonicalUrl is set (linking)
389
487
  if (botOptions) {
390
488
  delete message.canonicalUrl;
391
489
  }
392
490
 
393
491
  if (isChannel) {
394
- const msg = new (window.require('WAWebCollections')).Msg.modelClass(message);
395
- const msgDataFromMsgModel = (window.require('WAWebMsgDataFromModel')).msgDataFromMsgModel(msg);
492
+ const msg = new (window.require('WAWebCollections').Msg.modelClass)(
493
+ message,
494
+ );
495
+ const msgDataFromMsgModel = window
496
+ .require('WAWebMsgDataFromModel')
497
+ .msgDataFromMsgModel(msg);
396
498
  const isMedia = Object.keys(mediaOptions).length > 0;
397
- await (window.require('WAWebNewsletterUpdateMsgsRecordsJob')).addNewsletterMsgsRecords([msgDataFromMsgModel]);
499
+ await window
500
+ .require('WAWebNewsletterUpdateMsgsRecordsJob')
501
+ .addNewsletterMsgsRecords([msgDataFromMsgModel]);
398
502
  chat.msgs.add(msg);
399
503
  chat.t = msg.t;
400
504
 
401
- const sendChannelMsgResponse = await (window.require('WAWebNewsletterSendMessageJob')).sendNewsletterMessageJob({
402
- msg: msg,
403
- type: message.type === 'chat' ? 'text' : isMedia ? 'media' : 'pollCreation',
404
- newsletterJid: chat.id.toJid(),
405
- ...(isMedia
406
- ? {
407
- mediaMetadata: msg.avParams(),
408
- mediaHandle: isMedia ? mediaOptions.mediaHandle : null,
409
- }
410
- : {}
411
- )
412
- });
505
+ const sendChannelMsgResponse = await window
506
+ .require('WAWebNewsletterSendMessageJob')
507
+ .sendNewsletterMessageJob({
508
+ msg: msg,
509
+ type:
510
+ message.type === 'chat'
511
+ ? 'text'
512
+ : isMedia
513
+ ? 'media'
514
+ : 'pollCreation',
515
+ newsletterJid: chat.id.toJid(),
516
+ ...(isMedia
517
+ ? {
518
+ mediaMetadata: msg.avParams(),
519
+ mediaHandle: isMedia
520
+ ? mediaOptions.mediaHandle
521
+ : null,
522
+ }
523
+ : {}),
524
+ });
413
525
 
414
526
  if (sendChannelMsgResponse.success) {
415
527
  msg.t = sendChannelMsgResponse.ack.t;
416
528
  msg.serverId = sendChannelMsgResponse.serverId;
417
529
  }
418
530
  msg.updateAck(1, true);
419
- await (window.require('WAWebNewsletterUpdateMsgsRecordsJob')).updateNewsletterMsgRecord(msg);
531
+ await window
532
+ .require('WAWebNewsletterUpdateMsgsRecordsJob')
533
+ .updateNewsletterMsgRecord(msg);
420
534
  return msg;
421
535
  }
422
536
 
423
537
  if (isStatus) {
424
538
  const { backgroundColor, fontStyle } = extraOptions;
425
539
  const isMedia = Object.keys(mediaOptions).length > 0;
426
- const mediaUpdate = data => (window.require('WAWebMediaUpdateMsg'))(data, mediaOptions);
427
- const msg = new (window.require('WAWebCollections')).Msg.modelClass({
428
- ...message,
429
- author: participant ? participant : null,
430
- messageSecret: window.crypto.getRandomValues(new Uint8Array(32)),
431
- cannotBeRanked: (window.require('WAWebStatusGatingUtils')).canCheckStatusRankingPosterGating()
432
- });
540
+ const mediaUpdate = (data) =>
541
+ window.require('WAWebMediaUpdateMsg')(data, mediaOptions);
542
+ const msg = new (window.require('WAWebCollections').Msg.modelClass)(
543
+ {
544
+ ...message,
545
+ author: participant ? participant : null,
546
+ messageSecret: window.crypto.getRandomValues(
547
+ new Uint8Array(32),
548
+ ),
549
+ cannotBeRanked: window
550
+ .require('WAWebStatusGatingUtils')
551
+ .canCheckStatusRankingPosterGating(),
552
+ },
553
+ );
433
554
 
434
555
  // for text only
435
556
  const statusOptions = {
436
- color: backgroundColor && window.WWebJS.assertColor(backgroundColor) || 0xff7acca5,
437
- font: fontStyle >= 0 && fontStyle <= 7 && fontStyle || 0,
438
- text: msg.body
557
+ color:
558
+ (backgroundColor &&
559
+ window.WWebJS.assertColor(backgroundColor)) ||
560
+ 0xff7acca5,
561
+ font: (fontStyle >= 0 && fontStyle <= 7 && fontStyle) || 0,
562
+ text: msg.body,
439
563
  };
440
564
 
441
- await (window.require('WAWebSendStatusMsgAction'))[
442
- isMedia ?
443
- 'sendStatusMediaMsgAction' : 'sendStatusTextMsgAction'
444
- ](
445
- ...(
446
- isMedia ?
447
- [msg, mediaUpdate] : [statusOptions]
448
- )
449
- );
565
+ await window
566
+ .require('WAWebSendStatusMsgAction')
567
+ [
568
+ isMedia
569
+ ? 'sendStatusMediaMsgAction'
570
+ : 'sendStatusTextMsgAction'
571
+ ](...(isMedia ? [msg, mediaUpdate] : [statusOptions]));
450
572
 
451
573
  return msg;
452
574
  }
453
575
 
454
- const [msgPromise, sendMsgResultPromise] = (window.require('WAWebSendMsgChatAction')).addAndSendMsgToChat(chat, message);
576
+ const [msgPromise, sendMsgResultPromise] = window
577
+ .require('WAWebSendMsgChatAction')
578
+ .addAndSendMsgToChat(chat, message);
455
579
  await msgPromise;
456
580
 
457
581
  if (options.waitUntilMsgSent) await sendMsgResultPromise;
458
582
 
459
- return (window.require('WAWebCollections')).Msg.get(newMsgKey._serialized);
583
+ return window
584
+ .require('WAWebCollections')
585
+ .Msg.get(newMsgKey._serialized);
460
586
  };
461
-
587
+
462
588
  window.WWebJS.editMessage = async (msg, content, options = {}) => {
463
589
  const extraOptions = options.extraOptions || {};
464
590
  delete options.extraOptions;
465
-
591
+
466
592
  if (options.mentionedJidList) {
467
- options.mentionedJidList = options.mentionedJidList.map((id) => window.require('WAWebWidFactory').createWid(id));
593
+ options.mentionedJidList = options.mentionedJidList.map((id) =>
594
+ window.require('WAWebWidFactory').createWid(id),
595
+ );
468
596
  options.mentionedJidList = options.mentionedJidList.filter(Boolean);
469
597
  }
470
598
 
471
599
  if (options.groupMentions) {
472
600
  options.groupMentions = options.groupMentions.map((e) => ({
473
601
  groupSubject: e.subject,
474
- groupJid: window.require('WAWebWidFactory').createWid(e.id)
602
+ groupJid: window.require('WAWebWidFactory').createWid(e.id),
475
603
  }));
476
604
  }
477
605
 
@@ -480,54 +608,64 @@ exports.LoadUtils = () => {
480
608
  delete options.linkPreview;
481
609
  const link = findLink(content);
482
610
  if (link) {
483
- const preview = await (window.require('WAWebLinkPreviewChatAction')).getLinkPreview(link);
611
+ const preview = await window
612
+ .require('WAWebLinkPreviewChatAction')
613
+ .getLinkPreview(link);
484
614
  preview.preview = true;
485
615
  preview.subtype = 'url';
486
616
  options = { ...options, ...preview };
487
617
  }
488
618
  }
489
619
 
490
-
491
620
  const internalOptions = {
492
621
  ...options,
493
- ...extraOptions
622
+ ...extraOptions,
494
623
  };
495
624
 
496
- await (window.require('WAWebSendMessageEditAction')).sendMessageEdit(msg, content, internalOptions);
497
- return (window.require('WAWebCollections')).Msg.get(msg.id._serialized);
625
+ await window
626
+ .require('WAWebSendMessageEditAction')
627
+ .sendMessageEdit(msg, content, internalOptions);
628
+ return window.require('WAWebCollections').Msg.get(msg.id._serialized);
498
629
  };
499
630
 
500
631
  window.WWebJS.toStickerData = async (mediaInfo) => {
501
632
  if (mediaInfo.mimetype == 'image/webp') return mediaInfo;
502
633
 
503
634
  const file = window.WWebJS.mediaInfoToFile(mediaInfo);
504
- const webpSticker = await (window.require('WAWebImageUtils')).toWebpSticker(file);
635
+ const webpSticker = await window
636
+ .require('WAWebImageUtils')
637
+ .toWebpSticker(file);
505
638
  const webpBuffer = await webpSticker.arrayBuffer();
506
639
  const data = window.WWebJS.arrayBufferToBase64(webpBuffer);
507
640
 
508
641
  return {
509
642
  mimetype: 'image/webp',
510
- data
643
+ data,
511
644
  };
512
645
  };
513
646
 
514
647
  window.WWebJS.processStickerData = async (mediaInfo) => {
515
- if (mediaInfo.mimetype !== 'image/webp') throw new Error('Invalid media type');
648
+ if (mediaInfo.mimetype !== 'image/webp')
649
+ throw new Error('Invalid media type');
516
650
 
517
651
  const file = window.WWebJS.mediaInfoToFile(mediaInfo);
518
652
  let filehash = await window.WWebJS.getFileHash(file);
519
653
  let mediaKey = await window.WWebJS.generateHash(32);
520
654
 
521
655
  const controller = new AbortController();
522
- const uploadedInfo = await (window.require('WAWebUploadManager')).encryptAndUpload({
523
- blob: file,
524
- type: 'sticker',
525
- signal: controller.signal,
526
- mediaKey,
527
- uploadQpl: window.require('WAWebStartMediaUploadQpl').startMediaUploadQpl({
528
- entryPoint: 'MediaUpload'
529
- }),
530
- });
656
+ const uploadedInfo = await window
657
+ .require('WAWebUploadManager')
658
+ .encryptAndUpload({
659
+ blob: file,
660
+ type: 'sticker',
661
+ signal: controller.signal,
662
+ mediaKey,
663
+ uploadQpl: window
664
+ .require('WAWebStartMediaUploadQpl')
665
+ .startMediaUploadQpl({
666
+ entryPoint: 'MediaUpload',
667
+ }),
668
+ });
531
669
 
532
670
  const stickerInfo = {
533
671
  ...uploadedInfo,
@@ -536,30 +674,48 @@ exports.LoadUtils = () => {
536
674
  uploadhash: uploadedInfo.encFilehash,
537
675
  size: file.size,
538
676
  type: 'sticker',
539
- filehash
677
+ filehash,
540
678
  };
541
679
 
542
680
  return stickerInfo;
543
681
  };
544
682
 
545
- window.WWebJS.processMediaData = async (mediaInfo, { forceSticker, forceGif, forceVoice, forceDocument, forceMediaHd, sendToChannel, sendToStatus }) => {
683
+ window.WWebJS.processMediaData = async (
684
+ mediaInfo,
685
+ {
686
+ forceSticker,
687
+ forceGif,
688
+ forceVoice,
689
+ forceDocument,
690
+ forceMediaHd,
691
+ sendToChannel,
692
+ sendToStatus,
693
+ },
694
+ ) => {
546
695
  const file = window.WWebJS.mediaInfoToFile(mediaInfo);
547
696
  const OpaqueData = window.require('WAWebMediaOpaqueData');
548
- const opaqueData = await OpaqueData.createFromData(file, mediaInfo.mimetype);
697
+ const opaqueData = await OpaqueData.createFromData(
698
+ file,
699
+ mediaInfo.mimetype,
700
+ );
549
701
  const mediaParams = {
550
702
  asSticker: forceSticker,
551
703
  asGif: forceGif,
552
704
  isPtt: forceVoice,
553
- asDocument: forceDocument
705
+ asDocument: forceDocument,
554
706
  };
555
-
707
+
556
708
  if (forceMediaHd && file.type.indexOf('image/') === 0) {
557
709
  mediaParams.maxDimension = 2560;
558
710
  }
559
-
560
- const mediaPrep = window.require('WAWebPrepRawMedia').prepRawMedia(opaqueData, mediaParams);
711
+
712
+ const mediaPrep = window
713
+ .require('WAWebPrepRawMedia')
714
+ .prepRawMedia(opaqueData, mediaParams);
561
715
  const mediaData = await mediaPrep.waitForPrep();
562
- const mediaObject = window.require('WAWebMediaStorage').getOrCreateMediaObject(mediaData.filehash);
716
+ const mediaObject = window
717
+ .require('WAWebMediaStorage')
718
+ .getOrCreateMediaObject(mediaData.filehash);
563
719
  const mediaType = window.require('WAWebMmsMediaTypes').msgToMediaType({
564
720
  type: mediaData.type,
565
721
  isGif: mediaData.isGif,
@@ -570,39 +726,53 @@ exports.LoadUtils = () => {
570
726
  throw new Error('media-fault: sendToChat filehash undefined');
571
727
  }
572
728
 
573
- if ((forceVoice && mediaData.type === 'ptt') || (sendToStatus && mediaData.type === 'audio')) {
729
+ if (
730
+ (forceVoice && mediaData.type === 'ptt') ||
731
+ (sendToStatus && mediaData.type === 'audio')
732
+ ) {
574
733
  const waveform = mediaObject.contentInfo.waveform;
575
734
  mediaData.waveform =
576
- waveform || await window.WWebJS.generateWaveform(file);
735
+ waveform || (await window.WWebJS.generateWaveform(file));
577
736
  }
578
737
 
579
738
  if (!(mediaData.mediaBlob instanceof OpaqueData)) {
580
739
  mediaData.mediaBlob = await OpaqueData.createFromData(
581
740
  mediaData.mediaBlob,
582
- mediaData.mediaBlob.type
741
+ mediaData.mediaBlob.type,
583
742
  );
584
743
  }
585
744
 
586
745
  mediaData.renderableUrl = mediaData.mediaBlob.url();
587
746
  mediaObject.consolidate(mediaData.toJSON());
588
-
747
+
589
748
  mediaData.mediaBlob.autorelease();
590
- const shouldUseMediaCache = (window.require('WAWebMediaDataUtils')).shouldUseMediaCache(
591
- window.require('WAWebMmsMediaTypes').castToV4(mediaObject.type)
592
- );
749
+ const shouldUseMediaCache = window
750
+ .require('WAWebMediaDataUtils')
751
+ .shouldUseMediaCache(
752
+ window.require('WAWebMmsMediaTypes').castToV4(mediaObject.type),
753
+ );
593
754
  if (shouldUseMediaCache && mediaData.mediaBlob instanceof OpaqueData) {
594
755
  const formData = mediaData.mediaBlob.formData();
595
- (window.require('WAWebMediaInMemoryBlobCache')).InMemoryMediaBlobCache.put(mediaObject.filehash, formData);
756
+ window
757
+ .require('WAWebMediaInMemoryBlobCache')
758
+ .InMemoryMediaBlobCache.put(mediaObject.filehash, formData);
596
759
  }
597
760
 
598
761
  const dataToUpload = {
599
762
  mimetype: mediaData.mimetype,
600
763
  mediaObject,
601
764
  mediaType,
602
- ...(sendToChannel ? { calculateToken: window.require('WAMediaCalculateFilehash').getRandomFilehash } : {})
765
+ ...(sendToChannel
766
+ ? {
767
+ calculateToken: window.require('WAMediaCalculateFilehash')
768
+ .getRandomFilehash,
769
+ }
770
+ : {}),
603
771
  };
604
772
 
605
- const { uploadMedia, uploadUnencryptedMedia } = window.require('WAWebMediaMmsV4Upload');
773
+ const { uploadMedia, uploadUnencryptedMedia } = window.require(
774
+ 'WAWebMediaMmsV4Upload',
775
+ );
606
776
  const uploadedMedia = !sendToChannel
607
777
  ? await uploadMedia(dataToUpload)
608
778
  : await uploadUnencryptedMedia(dataToUpload);
@@ -634,26 +804,34 @@ exports.LoadUtils = () => {
634
804
  const msg = message.serialize();
635
805
 
636
806
  const { findLinks } = window.require('WALinkify');
637
-
807
+
638
808
  msg.isEphemeral = message.isEphemeral;
639
809
  msg.isStatusV3 = message.isStatusV3;
640
- msg.links = findLinks(message.mediaObject ? message.caption : message.body).map((link) => ({
810
+ msg.links = findLinks(
811
+ message.mediaObject ? message.caption : message.body,
812
+ ).map((link) => ({
641
813
  link: link.href,
642
- isSuspicious: Boolean(link.suspiciousCharacters && link.suspiciousCharacters.size)
814
+ isSuspicious: Boolean(
815
+ link.suspiciousCharacters && link.suspiciousCharacters.size,
816
+ ),
643
817
  }));
644
818
 
645
819
  if (msg.buttons) {
646
820
  msg.buttons = msg.buttons.serialize();
647
821
  }
648
822
  if (msg.dynamicReplyButtons) {
649
- msg.dynamicReplyButtons = JSON.parse(JSON.stringify(msg.dynamicReplyButtons));
823
+ msg.dynamicReplyButtons = JSON.parse(
824
+ JSON.stringify(msg.dynamicReplyButtons),
825
+ );
650
826
  }
651
827
  if (msg.replyButtons) {
652
828
  msg.replyButtons = JSON.parse(JSON.stringify(msg.replyButtons));
653
829
  }
654
830
 
655
831
  if (typeof msg.id.remote === 'object') {
656
- msg.id = Object.assign({}, msg.id, { remote: msg.id.remote._serialized });
832
+ msg.id = Object.assign({}, msg.id, {
833
+ remote: msg.id.remote._serialized,
834
+ });
657
835
  }
658
836
 
659
837
  delete msg.pendingAckUpdate;
@@ -668,16 +846,28 @@ exports.LoadUtils = () => {
668
846
 
669
847
  if (isChannel) {
670
848
  try {
671
- chat = (window.require('WAWebCollections')).WAWebNewsletterCollection.get(chatId);
849
+ chat = window
850
+ .require('WAWebCollections')
851
+ .WAWebNewsletterCollection.get(chatId);
672
852
  if (!chat) {
673
- await (window.require('WAWebLoadNewsletterPreviewChatAction')).loadNewsletterPreviewChat(chatId);
674
- chat = await (window.require('WAWebCollections')).WAWebNewsletterCollection.find(chatWid);
853
+ await window
854
+ .require('WAWebLoadNewsletterPreviewChatAction')
855
+ .loadNewsletterPreviewChat(chatId);
856
+ chat = await window
857
+ .require('WAWebCollections')
858
+ .WAWebNewsletterCollection.find(chatWid);
675
859
  }
676
- } catch (err) {
860
+ } catch (ignoredError) {
677
861
  chat = null;
678
862
  }
679
863
  } else {
680
- chat = (window.require('WAWebCollections')).Chat.get(chatWid) || (await (window.require('WAWebFindChatAction')).findOrCreateLatestChat(chatWid))?.chat;
864
+ chat =
865
+ window.require('WAWebCollections').Chat.get(chatWid) ||
866
+ (
867
+ await window
868
+ .require('WAWebFindChatAction')
869
+ .findOrCreateLatestChat(chatWid)
870
+ )?.chat;
681
871
  }
682
872
 
683
873
  return getAsModel && chat
@@ -686,44 +876,62 @@ exports.LoadUtils = () => {
686
876
  };
687
877
 
688
878
  window.WWebJS.getChannelMetadata = async (inviteCode) => {
689
- const role = (window.require('WAWebNewsletterModelUtils')).getRoleByIdentifier(inviteCode);
690
- const response =
691
- await (window.require('WAWebNewsletterMetadataQueryJob')).queryNewsletterMetadataByInviteCode(
692
- inviteCode,
693
- role
694
- );
695
-
696
- const picUrl = response.newsletterPictureMetadataMixin?.picture[0]?.queryPictureDirectPathOrEmptyResponseMixinGroup.value.directPath;
879
+ const role = window
880
+ .require('WAWebNewsletterModelUtils')
881
+ .getRoleByIdentifier(inviteCode);
882
+ const response = await window
883
+ .require('WAWebNewsletterMetadataQueryJob')
884
+ .queryNewsletterMetadataByInviteCode(inviteCode, role);
885
+
886
+ const picUrl =
887
+ response.newsletterPictureMetadataMixin?.picture[0]
888
+ ?.queryPictureDirectPathOrEmptyResponseMixinGroup.value
889
+ .directPath;
697
890
 
698
891
  return {
699
892
  id: response.idJid,
700
- createdAtTs: response.newsletterCreationTimeMetadataMixin.creationTimeValue,
893
+ createdAtTs:
894
+ response.newsletterCreationTimeMetadataMixin.creationTimeValue,
701
895
  titleMetadata: {
702
896
  title: response.newsletterNameMetadataMixin.nameElementValue,
703
- updatedAtTs: response.newsletterNameMetadataMixin.nameUpdateTime
897
+ updatedAtTs:
898
+ response.newsletterNameMetadataMixin.nameUpdateTime,
704
899
  },
705
900
  descriptionMetadata: {
706
- description: response.newsletterDescriptionMetadataMixin.descriptionQueryDescriptionResponseMixin.elementValue,
707
- updatedAtTs: response.newsletterDescriptionMetadataMixin.descriptionQueryDescriptionResponseMixin.updateTime
901
+ description:
902
+ response.newsletterDescriptionMetadataMixin
903
+ .descriptionQueryDescriptionResponseMixin.elementValue,
904
+ updatedAtTs:
905
+ response.newsletterDescriptionMetadataMixin
906
+ .descriptionQueryDescriptionResponseMixin.updateTime,
708
907
  },
709
908
  inviteLink: `https://whatsapp.com/channel/${response.newsletterInviteLinkMetadataMixin.inviteCode}`,
710
909
  membershipType: role,
711
910
  stateType: response.newsletterStateMetadataMixin.stateType,
712
911
  pictureUrl: picUrl ? `https://pps.whatsapp.net${picUrl}` : null,
713
- subscribersCount: response.newsletterSubscribersMetadataMixin.subscribersCount,
714
- isVerified: response.newsletterVerificationMetadataMixin.verificationState === 'verified'
912
+ subscribersCount:
913
+ response.newsletterSubscribersMetadataMixin.subscribersCount,
914
+ isVerified:
915
+ response.newsletterVerificationMetadataMixin
916
+ .verificationState === 'verified',
715
917
  };
716
918
  };
717
919
 
718
920
  window.WWebJS.getChats = async () => {
719
- const chats = (window.require('WAWebCollections')).Chat.getModelsArray();
720
- const chatPromises = chats.map(chat => window.WWebJS.getChatModel(chat));
921
+ const chats = window.require('WAWebCollections').Chat.getModelsArray();
922
+ const chatPromises = chats.map((chat) =>
923
+ window.WWebJS.getChatModel(chat),
924
+ );
721
925
  return await Promise.all(chatPromises);
722
926
  };
723
927
 
724
928
  window.WWebJS.getChannels = async () => {
725
- const channels = (window.require('WAWebCollections')).WAWebNewsletterCollection.getModelsArray();
726
- const channelPromises = channels?.map((channel) => window.WWebJS.getChatModel(channel, { isChannel: true }));
929
+ const channels = window
930
+ .require('WAWebCollections')
931
+ .WAWebNewsletterCollection.getModelsArray();
932
+ const channelPromises = channels?.map((channel) =>
933
+ window.WWebJS.getChatModel(channel, { isChannel: true }),
934
+ );
727
935
  return await Promise.all(channelPromises);
728
936
  };
729
937
 
@@ -734,36 +942,60 @@ exports.LoadUtils = () => {
734
942
  model.isGroup = false;
735
943
  model.isMuted = chat.mute?.expiration !== 0;
736
944
  if (isChannel) {
737
- model.isChannel = (window.require('WAWebChatGetters')).getIsNewsletter(chat);
945
+ model.isChannel = window
946
+ .require('WAWebChatGetters')
947
+ .getIsNewsletter(chat);
738
948
  } else {
739
949
  model.formattedTitle = chat.formattedTitle;
740
950
  }
741
951
 
742
952
  if (chat.groupMetadata) {
743
953
  model.isGroup = true;
744
- const chatWid = window.require('WAWebWidFactory').createWid(chat.id._serialized);
745
- const groupMetadata = (window.require('WAWebCollections')).GroupMetadata || (window.require('WAWebCollections')).WAWebGroupMetadataCollection;
954
+ const chatWid = window
955
+ .require('WAWebWidFactory')
956
+ .createWid(chat.id._serialized);
957
+ const groupMetadata =
958
+ window.require('WAWebCollections').GroupMetadata ||
959
+ window.require('WAWebCollections').WAWebGroupMetadataCollection;
746
960
  await groupMetadata.update(chatWid);
747
- chat.groupMetadata.participants._models
748
- .filter(x => x.id?._serialized?.endsWith('@lid'))
749
- .forEach(x => x.contact?.phoneNumber && (x.id = x.contact.phoneNumber));
750
- model.groupMetadata = chat.groupMetadata.serialize();
961
+ const { toPn } = window.require('WAWebLidMigrationUtils');
962
+ const serializedMetadata = chat.groupMetadata.serialize();
963
+ for (const p of serializedMetadata.participants || []) {
964
+ p.id = toPn(p.id) ?? p.id;
965
+ }
966
+ model.groupMetadata = serializedMetadata;
751
967
  model.isReadOnly = chat.groupMetadata.announce;
752
968
  }
753
969
 
754
970
  if (chat.newsletterMetadata) {
755
- const newsletterMetadata = (window.require('WAWebCollections')).NewsletterMetadataCollection || (window.require('WAWebCollections')).WAWebNewsletterMetadataCollection;
971
+ const newsletterMetadata =
972
+ window.require('WAWebCollections')
973
+ .NewsletterMetadataCollection ||
974
+ window.require('WAWebCollections')
975
+ .WAWebNewsletterMetadataCollection;
756
976
  await newsletterMetadata.update(chat.id);
757
977
  model.channelMetadata = chat.newsletterMetadata.serialize();
758
- model.channelMetadata.createdAtTs = chat.newsletterMetadata.creationTime;
978
+ model.channelMetadata.createdAtTs =
979
+ chat.newsletterMetadata.creationTime;
759
980
  }
760
981
 
761
982
  model.lastMessage = null;
762
983
  if (model.msgs && model.msgs.length) {
763
984
  const lastMessage = chat.lastReceivedKey
764
- ? (window.require('WAWebCollections')).Msg.get(chat.lastReceivedKey._serialized) || (await (window.require('WAWebCollections')).Msg.getMessagesById([chat.lastReceivedKey._serialized]))?.messages?.[0]
985
+ ? window
986
+ .require('WAWebCollections')
987
+ .Msg.get(chat.lastReceivedKey._serialized) ||
988
+ (
989
+ await window
990
+ .require('WAWebCollections')
991
+ .Msg.getMessagesById([
992
+ chat.lastReceivedKey._serialized,
993
+ ])
994
+ )?.messages?.[0]
765
995
  : null;
766
- lastMessage && (model.lastMessage = window.WWebJS.getMessageModel(lastMessage));
996
+ lastMessage &&
997
+ (model.lastMessage =
998
+ window.WWebJS.getMessageModel(lastMessage));
767
999
  }
768
1000
 
769
1001
  delete model.msgs;
@@ -773,16 +1005,35 @@ exports.LoadUtils = () => {
773
1005
  return model;
774
1006
  };
775
1007
 
776
- window.WWebJS.getContactModel = contact => {
1008
+ window.WWebJS.getContactModel = (contact) => {
777
1009
  let res = contact.serialize();
778
- res.isBusiness = contact.isBusiness === undefined ? false : contact.isBusiness;
1010
+
1011
+ const wid = window
1012
+ .require('WAWebWidFactory')
1013
+ .createWidFromWidLike(contact.id);
1014
+ if (wid.isLid() && contact.phoneNumber) {
1015
+ res.id = contact.phoneNumber;
1016
+ }
1017
+
1018
+ res.isBusiness =
1019
+ contact.isBusiness === undefined ? false : contact.isBusiness;
779
1020
 
780
1021
  if (contact.businessProfile) {
781
1022
  res.businessProfile = contact.businessProfile.serialize();
782
1023
  }
783
-
1024
+
784
1025
  res.isBlocked = contact.isContactBlocked;
785
-
1026
+ if (!res.isBlocked) {
1027
+ const alt = window
1028
+ .require('WAWebApiContact')
1029
+ .getAlternateUserWid(wid);
1030
+ if (alt) {
1031
+ res.isBlocked = !!window
1032
+ .require('WAWebCollections')
1033
+ .Blocklist.get(alt);
1034
+ }
1035
+ }
1036
+
786
1037
  const ContactMethods = window.require('WAWebContactGetters');
787
1038
  res.isMe = ContactMethods.getIsMe(contact);
788
1039
  res.isUser = ContactMethods.getIsUser(contact);
@@ -795,28 +1046,47 @@ exports.LoadUtils = () => {
795
1046
  res.name = ContactMethods.getName(contact);
796
1047
  res.shortName = ContactMethods.getShortName(contact);
797
1048
  res.pushname = ContactMethods.getPushname(contact);
798
-
799
- const { getIsMyContact } = window.require('WAWebFrontendContactGetters');
1049
+
1050
+ const { getIsMyContact } = window.require(
1051
+ 'WAWebFrontendContactGetters',
1052
+ );
800
1053
  res.isMyContact = getIsMyContact(contact);
801
1054
  res.isEnterprise = ContactMethods.getIsEnterprise(contact);
802
1055
 
803
1056
  return res;
804
1057
  };
805
1058
 
806
- window.WWebJS.getContact = async contactId => {
807
- const wid = window.require('WAWebWidFactory').createWid(contactId);
808
- let contact = await (window.require('WAWebCollections')).Contact.find(wid);
809
- if (contact.id._serialized.endsWith('@lid')) {
810
- contact.id = contact.phoneNumber;
1059
+ window.WWebJS.getContact = async (contactId) => {
1060
+ const contactWid = window
1061
+ .require('WAWebWidFactory')
1062
+ .createWid(contactId);
1063
+ const contact = await window
1064
+ .require('WAWebCollections')
1065
+ .Contact.find(contactWid);
1066
+ if (contact.isBusiness || contact.isEnterprise) {
1067
+ const bizProfile = await window
1068
+ .require('WAWebCollections')
1069
+ .BusinessProfile.find(contactWid);
1070
+ bizProfile.profileOptions && (contact.businessProfile = bizProfile);
811
1071
  }
812
- const bizProfile = await (window.require('WAWebCollections')).BusinessProfile.fetchBizProfile(wid);
813
- bizProfile.profileOptions && (contact.businessProfile = bizProfile);
814
1072
  return window.WWebJS.getContactModel(contact);
815
1073
  };
816
1074
 
817
1075
  window.WWebJS.getContacts = () => {
818
- const contacts = (window.require('WAWebCollections')).Contact.getModelsArray();
819
- return contacts.map(contact => window.WWebJS.getContactModel(contact));
1076
+ const contacts = window
1077
+ .require('WAWebCollections')
1078
+ .Contact.getModelsArray();
1079
+ return Promise.all(
1080
+ contacts.map(async (contact) => {
1081
+ if (contact.isBusiness || contact.isEnterprise) {
1082
+ await window
1083
+ .require('WAWebCollections')
1084
+ .BusinessProfile.find(contact.id)
1085
+ .catch(() => {});
1086
+ }
1087
+ return window.WWebJS.getContactModel(contact);
1088
+ }),
1089
+ );
820
1090
  };
821
1091
 
822
1092
  window.WWebJS.mediaInfoToFile = ({ data, mimetype, filename }) => {
@@ -831,7 +1101,7 @@ exports.LoadUtils = () => {
831
1101
  const blob = new Blob([buffer], { type: mimetype });
832
1102
  return new File([blob], filename, {
833
1103
  type: mimetype,
834
- lastModified: Date.now()
1104
+ lastModified: Date.now(),
835
1105
  });
836
1106
  };
837
1107
 
@@ -867,10 +1137,13 @@ exports.LoadUtils = () => {
867
1137
 
868
1138
  window.WWebJS.generateHash = async (length) => {
869
1139
  var result = '';
870
- var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1140
+ var characters =
1141
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
871
1142
  var charactersLength = characters.length;
872
1143
  for (var i = 0; i < length; i++) {
873
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
1144
+ result += characters.charAt(
1145
+ Math.floor(Math.random() * charactersLength),
1146
+ );
874
1147
  }
875
1148
  return result;
876
1149
  };
@@ -898,11 +1171,11 @@ exports.LoadUtils = () => {
898
1171
  const normalizedData = filteredData.map((n) => n * multiplier);
899
1172
 
900
1173
  const waveform = new Uint8Array(
901
- normalizedData.map((n) => Math.floor(100 * n))
1174
+ normalizedData.map((n) => Math.floor(100 * n)),
902
1175
  );
903
1176
 
904
1177
  return waveform;
905
- } catch (e) {
1178
+ } catch (ignoredError) {
906
1179
  return undefined;
907
1180
  }
908
1181
  };
@@ -910,7 +1183,7 @@ exports.LoadUtils = () => {
910
1183
  window.WWebJS.sendClearChat = async (chatId) => {
911
1184
  let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
912
1185
  if (chat !== undefined) {
913
- await (window.require('WAWebChatClearBridge')).sendClear(chat, false);
1186
+ await window.require('WAWebChatClearBridge').sendClear(chat, false);
914
1187
  return true;
915
1188
  }
916
1189
  return false;
@@ -919,7 +1192,7 @@ exports.LoadUtils = () => {
919
1192
  window.WWebJS.sendDeleteChat = async (chatId) => {
920
1193
  let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
921
1194
  if (chat !== undefined) {
922
- await (window.require('WAWebDeleteChatAction')).sendDelete(chat);
1195
+ await window.require('WAWebDeleteChatAction').sendDelete(chat);
923
1196
  return true;
924
1197
  }
925
1198
  return false;
@@ -930,23 +1203,23 @@ exports.LoadUtils = () => {
930
1203
 
931
1204
  const ChatState = window.require('WAWebChatStateBridge');
932
1205
  switch (state) {
933
- case 'typing':
934
- await ChatState.sendChatStateComposing(chatId);
935
- break;
936
- case 'recording':
937
- await ChatState.sendChatStateRecording(chatId);
938
- break;
939
- case 'stop':
940
- await ChatState.sendChatStatePaused(chatId);
941
- break;
942
- default:
943
- throw 'Invalid chatstate';
1206
+ case 'typing':
1207
+ await ChatState.sendChatStateComposing(chatId);
1208
+ break;
1209
+ case 'recording':
1210
+ await ChatState.sendChatStateRecording(chatId);
1211
+ break;
1212
+ case 'stop':
1213
+ await ChatState.sendChatStatePaused(chatId);
1214
+ break;
1215
+ default:
1216
+ throw 'Invalid chatstate';
944
1217
  }
945
1218
 
946
1219
  return true;
947
1220
  };
948
1221
 
949
- window.WWebJS.getLabelModel = label => {
1222
+ window.WWebJS.getLabelModel = (label) => {
950
1223
  let res = label.serialize();
951
1224
  res.hexColor = label.hexColor;
952
1225
 
@@ -954,28 +1227,34 @@ exports.LoadUtils = () => {
954
1227
  };
955
1228
 
956
1229
  window.WWebJS.getLabels = () => {
957
- const labels = (window.require('WAWebCollections')).Label.getModelsArray();
958
- return labels.map(label => window.WWebJS.getLabelModel(label));
1230
+ const labels = window
1231
+ .require('WAWebCollections')
1232
+ .Label.getModelsArray();
1233
+ return labels.map((label) => window.WWebJS.getLabelModel(label));
959
1234
  };
960
1235
 
961
1236
  window.WWebJS.getLabel = (labelId) => {
962
- const label = (window.require('WAWebCollections')).Label.get(labelId);
1237
+ const label = window.require('WAWebCollections').Label.get(labelId);
963
1238
  return window.WWebJS.getLabelModel(label);
964
1239
  };
965
1240
 
966
1241
  window.WWebJS.getChatLabels = async (chatId) => {
967
1242
  const chat = await window.WWebJS.getChat(chatId);
968
- return (chat.labels || []).map(id => window.WWebJS.getLabel(id));
1243
+ return (chat.labels || []).map((id) => window.WWebJS.getLabel(id));
969
1244
  };
970
1245
 
971
1246
  window.WWebJS.getOrderDetail = async (orderId, token, chatId) => {
972
1247
  const chatWid = window.require('WAWebWidFactory').createWid(chatId);
973
- return (window.require('WAWebBizOrderBridge')).queryOrder(chatWid, orderId, 80, 80, token);
1248
+ return window
1249
+ .require('WAWebBizOrderBridge')
1250
+ .queryOrder(chatWid, orderId, 80, 80, token);
974
1251
  };
975
1252
 
976
1253
  window.WWebJS.getProductMetadata = async (productId) => {
977
- let sellerId = (window.require('WAWebConnModel').Conn).wid;
978
- let product = await (window.require('WAWebBizProductCatalogBridge')).queryProduct(sellerId, productId);
1254
+ let sellerId = window.require('WAWebConnModel').Conn.wid;
1255
+ let product = await window
1256
+ .require('WAWebBizProductCatalogBridge')
1257
+ .queryProduct(sellerId, productId);
979
1258
  if (product && product.data) {
980
1259
  return product.data;
981
1260
  }
@@ -984,22 +1263,28 @@ exports.LoadUtils = () => {
984
1263
  };
985
1264
 
986
1265
  window.WWebJS.rejectCall = async (peerJid, id) => {
987
- let userId = (window.require('WAWebUserPrefsMeUser')).getMaybeMePnUser()._serialized;
988
-
989
- const stanza = window.require('WAWap').wap('call', {
990
- id: window.require('WAWap').generateId(),
991
- from: userId,
992
- to: peerJid,
993
- }, [
994
- window.require('WAWap').wap('reject', {
995
- 'call-id': id,
996
- 'call-creator': peerJid,
997
- count: '0',
998
- })
999
- ]);
1000
- await (window.require('WADeprecatedSendIq')).deprecatedCastStanza(stanza);
1266
+ let userId = window
1267
+ .require('WAWebUserPrefsMeUser')
1268
+ .getMaybeMePnUser()._serialized;
1269
+
1270
+ const stanza = window.require('WAWap').wap(
1271
+ 'call',
1272
+ {
1273
+ id: window.require('WAWap').generateId(),
1274
+ from: userId,
1275
+ to: peerJid,
1276
+ },
1277
+ [
1278
+ window.require('WAWap').wap('reject', {
1279
+ 'call-id': id,
1280
+ 'call-creator': peerJid,
1281
+ count: '0',
1282
+ }),
1283
+ ],
1284
+ );
1285
+ await window.require('WADeprecatedSendIq').deprecatedCastStanza(stanza);
1001
1286
  };
1002
-
1287
+
1003
1288
  window.WWebJS.cropAndResizeImage = async (media, options = {}) => {
1004
1289
  if (!media.mimetype.includes('image'))
1005
1290
  throw new Error('Media is not an image');
@@ -1007,9 +1292,17 @@ exports.LoadUtils = () => {
1007
1292
  if (options.mimetype && !options.mimetype.includes('image'))
1008
1293
  delete options.mimetype;
1009
1294
 
1010
- options = Object.assign({ size: 640, mimetype: media.mimetype, quality: .75, asDataUrl: false }, options);
1295
+ options = Object.assign(
1296
+ {
1297
+ size: 640,
1298
+ mimetype: media.mimetype,
1299
+ quality: 0.75,
1300
+ asDataUrl: false,
1301
+ },
1302
+ options,
1303
+ );
1011
1304
 
1012
- const img = await new Promise ((resolve, reject) => {
1305
+ const img = await new Promise((resolve, reject) => {
1013
1306
  const img = new Image();
1014
1307
  img.onload = () => resolve(img);
1015
1308
  img.onerror = reject;
@@ -1029,25 +1322,40 @@ exports.LoadUtils = () => {
1029
1322
 
1030
1323
  const dataUrl = canvas.toDataURL(options.mimetype, options.quality);
1031
1324
 
1032
- if (options.asDataUrl)
1033
- return dataUrl;
1325
+ if (options.asDataUrl) return dataUrl;
1034
1326
 
1035
1327
  return Object.assign(media, {
1036
1328
  mimetype: options.mimetype,
1037
- data: dataUrl.replace(`data:${options.mimetype};base64,`, '')
1329
+ data: dataUrl.replace(`data:${options.mimetype};base64,`, ''),
1038
1330
  });
1039
1331
  };
1040
1332
 
1041
1333
  window.WWebJS.setPicture = async (chatId, media) => {
1042
- const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
1043
- const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });
1334
+ const thumbnail = await window.WWebJS.cropAndResizeImage(media, {
1335
+ asDataUrl: true,
1336
+ mimetype: 'image/jpeg',
1337
+ size: 96,
1338
+ });
1339
+ const profilePic = await window.WWebJS.cropAndResizeImage(media, {
1340
+ asDataUrl: true,
1341
+ mimetype: 'image/jpeg',
1342
+ size: 640,
1343
+ });
1044
1344
 
1045
1345
  const chatWid = window.require('WAWebWidFactory').createWid(chatId);
1046
1346
  try {
1047
- const collection = (window.require('WAWebCollections')).ProfilePicThumb.get(chatId) || await (window.require('WAWebCollections')).ProfilePicThumb.find(chatId);
1347
+ const collection =
1348
+ window
1349
+ .require('WAWebCollections')
1350
+ .ProfilePicThumb.get(chatId) ||
1351
+ (await window
1352
+ .require('WAWebCollections')
1353
+ .ProfilePicThumb.find(chatId));
1048
1354
  if (!collection?.canSet()) return false;
1049
1355
 
1050
- const res = await (window.require('WAWebContactProfilePicThumbBridge')).sendSetPicture(chatWid, thumbnail, profilePic);
1356
+ const res = await window
1357
+ .require('WAWebContactProfilePicThumbBridge')
1358
+ .sendSetPicture(chatWid, thumbnail, profilePic);
1051
1359
  return res ? res.status === 200 : false;
1052
1360
  } catch (err) {
1053
1361
  if (err.name === 'ServerStatusCodeError') return false;
@@ -1058,19 +1366,25 @@ exports.LoadUtils = () => {
1058
1366
  window.WWebJS.deletePicture = async (chatid) => {
1059
1367
  const chatWid = window.require('WAWebWidFactory').createWid(chatid);
1060
1368
  try {
1061
- const collection = (window.require('WAWebCollections')).ProfilePicThumb.get(chatid);
1369
+ const collection = window
1370
+ .require('WAWebCollections')
1371
+ .ProfilePicThumb.get(chatid);
1062
1372
  if (!collection.canDelete()) return;
1063
1373
 
1064
- const res = await (window.require('WAWebContactProfilePicThumbBridge')).requestDeletePicture(chatWid);
1374
+ const res = await window
1375
+ .require('WAWebContactProfilePicThumbBridge')
1376
+ .requestDeletePicture(chatWid);
1065
1377
  return res ? res.status === 200 : false;
1066
1378
  } catch (err) {
1067
- if(err.name === 'ServerStatusCodeError') return false;
1379
+ if (err.name === 'ServerStatusCodeError') return false;
1068
1380
  throw err;
1069
1381
  }
1070
1382
  };
1071
-
1383
+
1072
1384
  window.WWebJS.getProfilePicThumbToBase64 = async (chatWid) => {
1073
- const profilePicCollection = await (window.require('WAWebCollections')).ProfilePicThumb.find(chatWid);
1385
+ const profilePicCollection = await window
1386
+ .require('WAWebCollections')
1387
+ .ProfilePicThumb.find(chatWid);
1074
1388
 
1075
1389
  const _readImageAsBase64 = (imageBlob) => {
1076
1390
  return new Promise((resolve) => {
@@ -1098,33 +1412,44 @@ exports.LoadUtils = () => {
1098
1412
  return base64Image;
1099
1413
  }
1100
1414
  }
1101
- } catch (error) { /* empty */ }
1415
+ } catch (ignoredError) {
1416
+ /* empty */
1417
+ }
1102
1418
  }
1103
1419
  return undefined;
1104
1420
  };
1105
1421
 
1106
- window.WWebJS.getAddParticipantsRpcResult = async (groupWid, participantWid) => {
1422
+ window.WWebJS.getAddParticipantsRpcResult = async (
1423
+ groupWid,
1424
+ participantWid,
1425
+ ) => {
1107
1426
  const iqTo = window.require('WAWebWidToJid').widToGroupJid(groupWid);
1108
1427
 
1109
- const participantArgs = [{
1110
- participantJid: window.require('WAWebWidToJid').widToUserJid(participantWid)
1111
- }];
1428
+ const participantArgs = [
1429
+ {
1430
+ participantJid: window
1431
+ .require('WAWebWidToJid')
1432
+ .widToUserJid(participantWid),
1433
+ },
1434
+ ];
1112
1435
 
1113
1436
  let rpcResult, resultArgs;
1114
1437
  const data = {
1115
1438
  name: undefined,
1116
1439
  code: undefined,
1117
1440
  inviteV4Code: undefined,
1118
- inviteV4CodeExp: undefined
1441
+ inviteV4CodeExp: undefined,
1119
1442
  };
1120
1443
 
1121
1444
  try {
1122
- rpcResult = await (window.require('WASmaxGroupsAddParticipantsRPC')).sendAddParticipantsRPC({ participantArgs, iqTo });
1123
- resultArgs = rpcResult.value.addParticipant[0]
1124
- .addParticipantsParticipantAddedOrNonRegisteredWaUserParticipantErrorLidResponseMixinGroup
1125
- .value
1126
- .addParticipantsParticipantMixins;
1127
- } catch (err) {
1445
+ rpcResult = await window
1446
+ .require('WASmaxGroupsAddParticipantsRPC')
1447
+ .sendAddParticipantsRPC({ participantArgs, iqTo });
1448
+ resultArgs =
1449
+ rpcResult.value.addParticipant[0]
1450
+ .addParticipantsParticipantAddedOrNonRegisteredWaUserParticipantErrorLidResponseMixinGroup
1451
+ .value.addParticipantsParticipantMixins;
1452
+ } catch (ignoredError) {
1128
1453
  data.code = 400;
1129
1454
  return data;
1130
1455
  }
@@ -1134,15 +1459,13 @@ exports.LoadUtils = () => {
1134
1459
  data.name = resultArgs?.name;
1135
1460
  data.code = +code;
1136
1461
  data.inviteV4Code = resultArgs?.value.addRequestCode;
1137
- data.inviteV4CodeExp = resultArgs?.value.addRequestExpiration?.toString();
1138
- }
1139
-
1140
- else if (rpcResult.name === 'AddParticipantsResponseClientError') {
1141
- const { code: code } = rpcResult.value.errorAddParticipantsClientErrors.value;
1462
+ data.inviteV4CodeExp =
1463
+ resultArgs?.value.addRequestExpiration?.toString();
1464
+ } else if (rpcResult.name === 'AddParticipantsResponseClientError') {
1465
+ const { code: code } =
1466
+ rpcResult.value.errorAddParticipantsClientErrors.value;
1142
1467
  data.code = +code;
1143
- }
1144
-
1145
- else if (rpcResult.name === 'AddParticipantsResponseServerError') {
1468
+ } else if (rpcResult.name === 'AddParticipantsResponseServerError') {
1146
1469
  const { code: code } = rpcResult.value.errorServerErrors.value;
1147
1470
  data.code = +code;
1148
1471
  }
@@ -1150,44 +1473,69 @@ exports.LoadUtils = () => {
1150
1473
  return data;
1151
1474
  };
1152
1475
 
1153
- window.WWebJS.membershipRequestAction = async (groupId, action, requesterIds, sleep) => {
1476
+ window.WWebJS.membershipRequestAction = async (
1477
+ groupId,
1478
+ action,
1479
+ requesterIds,
1480
+ sleep,
1481
+ ) => {
1154
1482
  const groupWid = window.require('WAWebWidFactory').createWid(groupId);
1155
- const group = await (window.require('WAWebCollections')).Chat.find(groupWid);
1483
+ const group = await window
1484
+ .require('WAWebCollections')
1485
+ .Chat.find(groupWid);
1156
1486
  const toApprove = action === 'Approve';
1157
1487
  let membershipRequests;
1158
1488
  let response;
1159
1489
  let result = [];
1160
1490
 
1161
- await (window.require('WAWebGroupQueryJob')).queryAndUpdateGroupMetadataById({ id: groupId });
1491
+ await window
1492
+ .require('WAWebGroupQueryJob')
1493
+ .queryAndUpdateGroupMetadataById({ id: groupId });
1162
1494
 
1163
1495
  if (!requesterIds?.length) {
1164
- membershipRequests = group.groupMetadata.membershipApprovalRequests._models.map(({ id }) => id);
1496
+ membershipRequests =
1497
+ group.groupMetadata.membershipApprovalRequests._models.map(
1498
+ ({ id }) => id,
1499
+ );
1165
1500
  } else {
1166
1501
  !Array.isArray(requesterIds) && (requesterIds = [requesterIds]);
1167
- membershipRequests = requesterIds.map(r => window.require('WAWebWidFactory').createWid(r));
1502
+ membershipRequests = requesterIds.map((r) =>
1503
+ window.require('WAWebWidFactory').createWid(r),
1504
+ );
1168
1505
  }
1169
1506
 
1170
1507
  if (!membershipRequests.length) return [];
1171
1508
 
1172
- const participantArgs = membershipRequests.map(m => ({
1509
+ const participantArgs = membershipRequests.map((m) => ({
1173
1510
  participantArgs: [
1174
1511
  {
1175
- participantJid: window.require('WAWebWidToJid').widToUserJid(m)
1176
- }
1177
- ]
1512
+ participantJid: window
1513
+ .require('WAWebWidToJid')
1514
+ .widToUserJid(m),
1515
+ },
1516
+ ],
1178
1517
  }));
1179
1518
 
1180
- const groupJid = window.require('WAWebWidToJid').widToGroupJid(groupWid);
1181
-
1519
+ const groupJid = window
1520
+ .require('WAWebWidToJid')
1521
+ .widToGroupJid(groupWid);
1522
+
1182
1523
  const _getSleepTime = (sleep) => {
1183
- if (!Array.isArray(sleep) || (sleep.length === 2 && sleep[0] === sleep[1])) {
1524
+ if (
1525
+ !Array.isArray(sleep) ||
1526
+ (sleep.length === 2 && sleep[0] === sleep[1])
1527
+ ) {
1184
1528
  return sleep;
1185
1529
  }
1186
1530
  if (sleep.length === 1) {
1187
1531
  return sleep[0];
1188
1532
  }
1189
- sleep[1] - sleep[0] < 100 && (sleep[0] = sleep[1]) && (sleep[1] += 100);
1190
- return Math.floor(Math.random() * (sleep[1] - sleep[0] + 1)) + sleep[0];
1533
+ sleep[1] - sleep[0] < 100 &&
1534
+ (sleep[0] = sleep[1]) &&
1535
+ (sleep[1] += 100);
1536
+ return (
1537
+ Math.floor(Math.random() * (sleep[1] - sleep[0] + 1)) + sleep[0]
1538
+ );
1191
1539
  };
1192
1540
 
1193
1541
  const membReqResCodes = {
@@ -1199,63 +1547,101 @@ exports.LoadUtils = () => {
1199
1547
  408: 'ParticipantTemporarilyBlockedError',
1200
1548
  409: 'ParticipantConflictError',
1201
1549
  412: 'ParticipantParentLinkedGroupsResourceConstraintError',
1202
- 500: 'ParticipantResourceConstraintError'
1550
+ 500: 'ParticipantResourceConstraintError',
1203
1551
  };
1204
1552
 
1205
1553
  try {
1206
1554
  for (const participant of participantArgs) {
1207
- response = await (window.require('WASmaxGroupsMembershipRequestsActionRPC')).sendMembershipRequestsActionRPC({
1208
- iqTo: groupJid,
1209
- [toApprove ? 'approveArgs' : 'rejectArgs']: participant
1210
- });
1555
+ response = await window
1556
+ .require('WASmaxGroupsMembershipRequestsActionRPC')
1557
+ .sendMembershipRequestsActionRPC({
1558
+ iqTo: groupJid,
1559
+ [toApprove ? 'approveArgs' : 'rejectArgs']: participant,
1560
+ });
1211
1561
 
1212
- if (response.name === 'MembershipRequestsActionResponseSuccess') {
1562
+ if (
1563
+ response.name === 'MembershipRequestsActionResponseSuccess'
1564
+ ) {
1213
1565
  const value = toApprove
1214
1566
  ? response.value.membershipRequestsActionApprove
1215
1567
  : response.value.membershipRequestsActionReject;
1216
1568
  if (value?.participant) {
1217
- const [_] = value.participant.map(p => {
1569
+ const [_] = value.participant.map((p) => {
1218
1570
  const error = toApprove
1219
- ? value.participant[0].membershipRequestsActionAcceptParticipantMixins?.value.error
1220
- : value.participant[0].membershipRequestsActionRejectParticipantMixins?.value.error;
1571
+ ? value.participant[0]
1572
+ .membershipRequestsActionAcceptParticipantMixins
1573
+ ?.value.error
1574
+ : value.participant[0]
1575
+ .membershipRequestsActionRejectParticipantMixins
1576
+ ?.value.error;
1221
1577
  return {
1222
- requesterId: window.require('WAWebWidFactory').createWid(p.jid)._serialized,
1578
+ requesterId: window
1579
+ .require('WAWebWidFactory')
1580
+ .createWid(p.jid)._serialized,
1223
1581
  ...(error
1224
- ? { error: +error, message: membReqResCodes[error] || membReqResCodes.default }
1225
- : { message: `${toApprove ? 'Approved' : 'Rejected'} successfully` })
1582
+ ? {
1583
+ error: +error,
1584
+ message:
1585
+ membReqResCodes[error] ||
1586
+ membReqResCodes.default,
1587
+ }
1588
+ : {
1589
+ message: `${toApprove ? 'Approved' : 'Rejected'} successfully`,
1590
+ }),
1226
1591
  };
1227
1592
  });
1228
1593
  _ && result.push(_);
1229
1594
  }
1230
1595
  } else {
1231
1596
  result.push({
1232
- requesterId: window.require('WAWebJidToWid').userJidToUserWid(participant.participantArgs[0].participantJid)._serialized,
1233
- message: 'ServerStatusCodeError'
1597
+ requesterId: window
1598
+ .require('WAWebJidToWid')
1599
+ .userJidToUserWid(
1600
+ participant.participantArgs[0].participantJid,
1601
+ )._serialized,
1602
+ message: 'ServerStatusCodeError',
1234
1603
  });
1235
1604
  }
1236
1605
 
1237
1606
  sleep &&
1238
1607
  participantArgs.length > 1 &&
1239
- participantArgs.indexOf(participant) !== participantArgs.length - 1 &&
1240
- (await new Promise((resolve) => setTimeout(resolve, _getSleepTime(sleep))));
1608
+ participantArgs.indexOf(participant) !==
1609
+ participantArgs.length - 1 &&
1610
+ (await new Promise((resolve) =>
1611
+ setTimeout(resolve, _getSleepTime(sleep)),
1612
+ ));
1241
1613
  }
1242
1614
  return result;
1243
- } catch (err) {
1615
+ } catch (ignoredError) {
1244
1616
  return [];
1245
1617
  }
1246
1618
  };
1247
1619
 
1248
- window.WWebJS.subscribeToUnsubscribeFromChannel = async (channelId, action, options = {}) => {
1249
- const channel = await window.WWebJS.getChat(channelId, { getAsModel: false });
1620
+ window.WWebJS.subscribeToUnsubscribeFromChannel = async (
1621
+ channelId,
1622
+ action,
1623
+ options = {},
1624
+ ) => {
1625
+ const channel = await window.WWebJS.getChat(channelId, {
1626
+ getAsModel: false,
1627
+ });
1250
1628
 
1251
- if (!channel || channel.newsletterMetadata.membershipType === 'owner') return false;
1252
- options = { eventSurface: 3, deleteLocalModels: options.deleteLocalModels ?? true };
1629
+ if (!channel || channel.newsletterMetadata.membershipType === 'owner')
1630
+ return false;
1631
+ options = {
1632
+ eventSurface: 3,
1633
+ deleteLocalModels: options.deleteLocalModels ?? true,
1634
+ };
1253
1635
 
1254
1636
  try {
1255
1637
  if (action === 'Subscribe') {
1256
- await (window.require('WAWebNewsletterSubscribeAction')).subscribeToNewsletterAction(channel, options);
1638
+ await window
1639
+ .require('WAWebNewsletterSubscribeAction')
1640
+ .subscribeToNewsletterAction(channel, options);
1257
1641
  } else if (action === 'Unsubscribe') {
1258
- await (window.require('WAWebNewsletterUnsubscribeAction')).unsubscribeFromNewsletterAction(channel, options);
1642
+ await window
1643
+ .require('WAWebNewsletterUnsubscribeAction')
1644
+ .unsubscribeFromNewsletterAction(channel, options);
1259
1645
  } else return false;
1260
1646
  return true;
1261
1647
  } catch (err) {
@@ -1265,47 +1651,69 @@ exports.LoadUtils = () => {
1265
1651
  };
1266
1652
 
1267
1653
  window.WWebJS.pinUnpinMsgAction = async (msgId, action, duration) => {
1268
- const message = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
1654
+ const message =
1655
+ window.require('WAWebCollections').Msg.get(msgId) ||
1656
+ (
1657
+ await window
1658
+ .require('WAWebCollections')
1659
+ .Msg.getMessagesById([msgId])
1660
+ )?.messages?.[0];
1269
1661
  if (!message) return false;
1270
1662
 
1271
1663
  if (typeof duration !== 'number') return false;
1272
-
1273
- const originalFunction = window.require('WAWebPinMsgConstants').getPinExpiryDuration;
1274
- window.require('WAWebPinMsgConstants').getPinExpiryDuration = () => duration;
1275
-
1276
- const response = await (window.require('WAWebSendPinMessageAction')).sendPinInChatMsg(message, action, duration);
1277
1664
 
1278
- window.require('WAWebPinMsgConstants').getPinExpiryDuration = originalFunction;
1665
+ const originalFunction = window.require(
1666
+ 'WAWebPinMsgConstants',
1667
+ ).getPinExpiryDuration;
1668
+ window.require('WAWebPinMsgConstants').getPinExpiryDuration = () =>
1669
+ duration;
1670
+
1671
+ const response = await window
1672
+ .require('WAWebSendPinMessageAction')
1673
+ .sendPinInChatMsg(message, action, duration);
1674
+
1675
+ window.require('WAWebPinMsgConstants').getPinExpiryDuration =
1676
+ originalFunction;
1279
1677
 
1280
1678
  return response.messageSendResult === 'OK';
1281
1679
  };
1282
-
1283
- window.WWebJS.getStatusModel = status => {
1680
+
1681
+ window.WWebJS.getStatusModel = (status) => {
1284
1682
  const res = status.serialize();
1285
1683
  delete res._msgs;
1286
1684
  return res;
1287
1685
  };
1288
1686
 
1289
1687
  window.WWebJS.getAllStatuses = () => {
1290
- const statuses = (window.require('WAWebCollections')).Status.getModelsArray();
1291
- return statuses.map(status => window.WWebJS.getStatusModel(status));
1688
+ const statuses = window
1689
+ .require('WAWebCollections')
1690
+ .Status.getModelsArray();
1691
+ return statuses.map((status) => window.WWebJS.getStatusModel(status));
1292
1692
  };
1293
1693
 
1294
1694
  window.WWebJS.enforceLidAndPnRetrieval = async (userId) => {
1295
1695
  const wid = window.require('WAWebWidFactory').createWid(userId);
1296
1696
  const isLid = wid.server === 'lid';
1297
1697
 
1298
- let lid = isLid ? wid : window.require('WAWebApiContact').getCurrentLid(wid);
1299
- let phone = isLid ? window.require('WAWebApiContact').getPhoneNumber(wid) : wid;
1698
+ let lid = isLid
1699
+ ? wid
1700
+ : window.require('WAWebApiContact').getCurrentLid(wid);
1701
+ let phone = isLid
1702
+ ? window.require('WAWebApiContact').getPhoneNumber(wid)
1703
+ : wid;
1300
1704
 
1301
1705
  if (!isLid && !lid) {
1302
- const queryResult = await (window.require('WAWebQueryExistsJob').queryWidExists)(wid);
1706
+ const queryResult = await window
1707
+ .require('WAWebQueryExistsJob')
1708
+ .queryWidExists(wid);
1303
1709
  if (!queryResult?.wid) return {};
1304
1710
  lid = window.require('WAWebApiContact').getCurrentLid(wid);
1305
1711
  }
1306
1712
 
1307
1713
  if (isLid && !phone) {
1308
- const queryResult = await (window.require('WAWebQueryExistsJob').queryWidExists)(wid);
1714
+ const queryResult = await window
1715
+ .require('WAWebQueryExistsJob')
1716
+ .queryWidExists(wid);
1309
1717
  if (!queryResult?.wid) return {};
1310
1718
  phone = window.require('WAWebApiContact').getPhoneNumber(wid);
1311
1719
  }