amiudmodz 4.0.6 → 4.1.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.
package/README.md ADDED
@@ -0,0 +1,130 @@
1
+ <div align="center">
2
+
3
+ <img src="https://capsule-render.vercel.app/api?type=waving&color=0:4000ff,50:7c3aed,100:00d4ff&height=220&section=header&text=Baileys%20-%20UDMODZ&fontSize=52&fontColor=ffffff&animation=fadeIn&fontAlignY=35&desc=⚡%20Lightweight%20WhatsApp%20Web%20API&descAlignY=55&descSize=18" width="100%"/>
4
+
5
+ <br/>
6
+
7
+ [![Node.js](https://img.shields.io/badge/Node.js-≥20-339933?style=for-the-badge&logo=nodedotjs&logoColor=white)](https://nodejs.org)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
9
+ [![WhatsApp](https://img.shields.io/badge/WhatsApp-API-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://web.whatsapp.com)
10
+
11
+ [![npm version](https://img.shields.io/npm/v/amiudmodz?style=for-the-badge&color=7c3aed&logoColor=white)](https://www.npmjs.com/package/amiudmodz)
12
+ [![License](https://img.shields.io/badge/License-MIT-00d4ff?style=for-the-badge&logoColor=white)](https://github.com/udmodz0)
13
+ [![Status](https://img.shields.io/badge/Status-Active-00ff88?style=for-the-badge&logoColor=white)](https://github.com/udmodz0)
14
+
15
+ <br/>
16
+
17
+ ```text
18
+ ██╗░░░██╗██████╗░███╗░░░███╗░█████╗░██████╗░███████╗
19
+ ██║░░░██║██╔══██╗████╗░████║██╔══██╗██╔══██╗╚════██║
20
+ ██║░░░██║██║░░██║██╔████╔██║██║░░██║██║░░██║░░███╔═╝
21
+ ██║░░░██║██║░░██║██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░
22
+ ╚██████╔╝██████╔╝██║░╚═╝░██║╚█████╔╝██████╔╝███████╗
23
+ ░╚═════╝░╚═════╝░╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝
24
+ ```
25
+
26
+ </div>
27
+
28
+ ---
29
+
30
+ <img src="https://user-images.githubusercontent.com/73097560/115834477-dbab4500-a447-11eb-908a-139a6edaec5c.gif" width="100%">
31
+
32
+ ## <img src="https://media.giphy.com/media/iY8CRBdQXODJSCERIr/giphy.gif" width="30"> &nbsp;About
33
+
34
+ > **Baileys (UDMODZ Edition)** is a lightweight, high-performance WhatsApp Web API library (published as `amiudmodz`). It implements the complete WhatsApp Web socket protocol and enables developers to build custom and powerful WhatsApp bots via Node.js limitlessly. Both authentication types (Pairing Code and QR Code) are natively supported.
35
+
36
+ <div align="center">
37
+
38
+ | 🧩 Feature | 📝 Description |
39
+ |:---:|:---|
40
+ | 📡 **Socket Protocol** | Communicates over fast native WebSockets |
41
+ | 🛡️ **End-to-End Encryption** | Fully implements Signal protocol for security |
42
+ | 📱 **Multi-Device Support** | Support for WA Web Multi-Device seamlessly |
43
+ | ⚡ **Lightweight** | Needs very low resources compared to Puppeteer |
44
+ | 📂 **Media Handling** | Download & upload images, videos, audio, documents |
45
+ | 🔑 **Pairing Code** | Easy device linking through Pairing Codes |
46
+
47
+ </div>
48
+
49
+ <img src="https://user-images.githubusercontent.com/73097560/115834477-dbab4500-a447-11eb-908a-139a6edaec5c.gif" width="100%">
50
+
51
+ ## 🚀 Installation & Usage
52
+
53
+ <details>
54
+ <summary><b>📦 1. Install using NPM</b></summary>
55
+ <br/>
56
+
57
+ ```bash
58
+ npm install amiudmodz
59
+ ```
60
+ </details>
61
+
62
+ <details>
63
+ <summary><b>💻 2. Basic Example</b></summary>
64
+ <br/>
65
+
66
+ ```typescript
67
+ import makeWASocket, { useMultiFileAuthState } from 'amiudmodz'
68
+
69
+ async function connectToWhatsApp () {
70
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
71
+
72
+ // Connect to WA Socket
73
+ const sock = makeWASocket({
74
+ printQRInTerminal: true,
75
+ auth: state
76
+ })
77
+
78
+ // Save creds when updated
79
+ sock.ev.on('creds.update', saveCreds)
80
+
81
+ // Receive messages
82
+ sock.ev.on('messages.upsert', async m => {
83
+ console.log(JSON.stringify(m, undefined, 2))
84
+
85
+ console.log('replying to', m.messages[0].key.remoteJid)
86
+ await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
87
+ })
88
+ }
89
+
90
+ connectToWhatsApp()
91
+ ```
92
+ </details>
93
+
94
+ <img src="https://user-images.githubusercontent.com/73097560/115834477-dbab4500-a447-11eb-908a-139a6edaec5c.gif" width="100%">
95
+
96
+ <div align="center">
97
+
98
+ ## 👨‍💻 Creator
99
+
100
+ <a href="https://github.com/udmodz0">
101
+ <img src="https://readme-typing-svg.demolab.com?font=Fira+Code&weight=700&size=28&duration=2500&pause=800&color=7C3AED&center=true&vCenter=true&repeat=true&width=300&height=50&lines=UDMODZ0" alt="UDMODZ0" />
102
+ </a>
103
+
104
+ <br/>
105
+
106
+ <a href="https://github.com/udmodz0">
107
+ <img src="https://img.shields.io/badge/GitHub-udmodz0-181717?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"/>
108
+ </a>
109
+
110
+ <br/><br/>
111
+
112
+ <img src="https://capsule-render.vercel.app/api?type=shark&color=0:4000ff,50:7c3aed,100:00d4ff&height=40&section=footer" width="100%"/>
113
+
114
+ ### ⭐ Star this repo if you found it useful!
115
+
116
+ <br/>
117
+
118
+ > 🚫 **This package is provided as-is.**
119
+ >
120
+ > Made with 💜 by **UDMODZ0**
121
+
122
+ <br/>
123
+
124
+ <img src="https://github-readme-activity-graph.vercel.app/graph?username=udmodz0&theme=tokyo-night&hide_border=true&area=true&custom_title=UDMODZ0%20Contribution%20Graph" width="95%"/>
125
+
126
+ <br/>
127
+
128
+ <img src="https://capsule-render.vercel.app/api?type=waving&color=0:4000ff,50:7c3aed,100:00d4ff&height=120&section=footer&animation=twinkling" width="100%"/>
129
+
130
+ </div>
@@ -76,11 +76,14 @@ exports.DEFAULT_CONNECTION_CONFIG = {
76
76
  browser: Utils_1.Browsers.macOS("Chrome"),
77
77
  waWebSocketUrl: "wss://web.whatsapp.com/ws/chat",
78
78
  connectTimeoutMs: 2E4,
79
- keepAliveIntervalMs: 1.5E4,
79
+
80
+ keepAliveIntervalMs: 2.5E4,
80
81
  logger: logger_1.default.child({ class: "baileys" }),
81
82
  printQRInTerminal: !1,
82
83
  emitOwnEvents: !0,
83
- defaultQueryTimeoutMs: 6E4,
84
+
85
+
86
+ defaultQueryTimeoutMs: 2E4,
84
87
  customUploadHosts: [],
85
88
  retryRequestDelayMs: 250,
86
89
  maxMsgRetryCount: 5,
@@ -149,8 +152,10 @@ exports.TimeMs = {
149
152
  };
150
153
 
151
154
  exports.DEFAULT_CACHE_TTLS = {
152
- SIGNAL_STORE: 300,
155
+
156
+ SIGNAL_STORE: 600,
153
157
  MSG_RETRY: 3600,
154
158
  CALL_OFFER: 300,
155
- USER_DEVICES: 300
159
+
160
+ USER_DEVICES: 600
156
161
  };
@@ -39,6 +39,9 @@ class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
39
39
  handshakeTimeout: this.config.connectTimeoutMs,
40
40
  timeout: this.config.connectTimeoutMs,
41
41
  agent: this.config.agent,
42
+
43
+
44
+ perMessageDeflate: false,
42
45
  });
43
46
  this.socket.setMaxListeners(0);
44
47
  const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response'];
@@ -52,6 +55,9 @@ class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
52
55
  }
53
56
  const closePromise = new Promise((resolve) => {
54
57
  this.socket.once('close', resolve);
58
+
59
+
60
+ setTimeout(resolve, 5000);
55
61
  });
56
62
  this.socket.close();
57
63
  await closePromise;
@@ -59,7 +65,8 @@ class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
59
65
  }
60
66
  send(str, cb) {
61
67
  var _a;
62
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
68
+
69
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, { compress: false }, cb);
63
70
  return Boolean(this.socket);
64
71
  }
65
72
  }
@@ -10,7 +10,7 @@ class toxic {
10
10
  this.waUploadToServer = waUploadToServer;
11
11
  this.config = config;
12
12
  this.sock = sock;
13
-
13
+
14
14
  this.bail = {
15
15
  generateWAMessageContent: this.utils.generateWAMessageContent || Utils_1.generateWAMessageContent,
16
16
  generateMessageID: Utils_1.generateMessageID,
@@ -71,17 +71,17 @@ class toxic {
71
71
  })
72
72
  };
73
73
  }
74
-
74
+
75
75
  async handleProduct(content, jid, quoted) {
76
76
  const {
77
- title,
78
- description,
77
+ title,
78
+ description,
79
79
  thumbnail,
80
- productId,
81
- retailerId,
82
- url,
83
- body = "",
84
- footer = "",
80
+ productId,
81
+ retailerId,
82
+ url,
83
+ body = "",
84
+ footer = "",
85
85
  buttons = [],
86
86
  priceAmount1000 = null,
87
87
  currencyCode = "IDR"
@@ -91,13 +91,13 @@ class toxic {
91
91
 
92
92
  if (Buffer.isBuffer(thumbnail)) {
93
93
  const { imageMessage } = await this.utils.generateWAMessageContent(
94
- { image: thumbnail },
94
+ { image: thumbnail },
95
95
  { upload: this.waUploadToServer }
96
96
  );
97
97
  productImage = imageMessage;
98
98
  } else if (typeof thumbnail === 'object' && thumbnail.url) {
99
99
  const { imageMessage } = await this.utils.generateWAMessageContent(
100
- { image: { url: thumbnail.url }},
100
+ { image: { url: thumbnail.url } },
101
101
  { upload: this.waUploadToServer }
102
102
  );
103
103
  productImage = imageMessage;
@@ -133,7 +133,7 @@ class toxic {
133
133
  }
134
134
  };
135
135
  }
136
-
136
+
137
137
  async handleInteractive(content, jid, quoted) {
138
138
  const {
139
139
  title,
@@ -188,8 +188,8 @@ class toxic {
188
188
  }
189
189
  mediaType = 'video';
190
190
  } else if (document) {
191
- let documentPayload = {
192
- document: document
191
+ let documentPayload = {
192
+ document: document
193
193
  };
194
194
  if (jpegThumbnail) {
195
195
  if (typeof jpegThumbnail === 'object' && jpegThumbnail.url) {
@@ -198,7 +198,7 @@ class toxic {
198
198
  documentPayload.jpegThumbnail = jpegThumbnail;
199
199
  }
200
200
  }
201
-
201
+
202
202
  media = await this.utils.prepareWAMessageMedia(
203
203
  documentPayload,
204
204
  { upload: this.waUploadToServer }
@@ -228,7 +228,7 @@ class toxic {
228
228
  } else if (nativeFlowMessage) {
229
229
  interactiveMessage.nativeFlowMessage = nativeFlowMessage;
230
230
  }
231
-
231
+
232
232
  if (media) {
233
233
  interactiveMessage.header = {
234
234
  title: header || "",
@@ -237,11 +237,11 @@ class toxic {
237
237
  };
238
238
  } else {
239
239
  interactiveMessage.header = {
240
- title: header || "",
240
+ title: header || "",
241
241
  hasMediaAttachment: false
242
242
  };
243
243
  }
244
-
244
+
245
245
  let finalContextInfo = {};
246
246
  if (contextInfo) {
247
247
  finalContextInfo = {
@@ -251,7 +251,7 @@ class toxic {
251
251
  ...contextInfo
252
252
  };
253
253
  }
254
-
254
+
255
255
  if (externalAdReply) {
256
256
  finalContextInfo.externalAdReply = {
257
257
  title: externalAdReply.title || "",
@@ -265,7 +265,7 @@ class toxic {
265
265
  ...externalAdReply
266
266
  };
267
267
  }
268
-
268
+
269
269
  if (Object.keys(finalContextInfo).length > 0) {
270
270
  interactiveMessage.contextInfo = finalContextInfo;
271
271
  }
@@ -273,7 +273,7 @@ class toxic {
273
273
  interactiveMessage: interactiveMessage
274
274
  };
275
275
  }
276
-
276
+
277
277
  async handleAlbum(content, jid, quoted) {
278
278
  const array = content.albumMessage;
279
279
  const album = await this.utils.generateWAMessageFromContent(jid, {
@@ -289,22 +289,22 @@ class toxic {
289
289
  quoted,
290
290
  upload: this.waUploadToServer
291
291
  });
292
-
292
+
293
293
  await this.relayMessage(jid, album.message, {
294
294
  messageId: album.key.id,
295
295
  });
296
-
296
+
297
297
  for (let content of array) {
298
298
  const img = await this.utils.generateWAMessage(jid, content, {
299
299
  upload: this.waUploadToServer,
300
300
  });
301
-
301
+
302
302
  img.message.messageContextInfo = {
303
303
  messageSecret: crypto.randomBytes(32),
304
304
  messageAssociation: {
305
305
  associationType: 1,
306
306
  parentMessageKey: album.key,
307
- },
307
+ },
308
308
  participant: "0@s.whatsapp.net",
309
309
  remoteJid: "status@broadcast",
310
310
  forwardingScore: 99999,
@@ -332,14 +332,14 @@ class toxic {
332
332
  priority: "high",
333
333
  status: "sent",
334
334
  };
335
-
335
+
336
336
  img.message.disappearingMode = {
337
337
  initiator: 3,
338
338
  trigger: 4,
339
339
  initiatorDeviceJid: jid,
340
340
  initiatedByExternalService: true,
341
341
  initiatedByUserDevice: true,
342
- initiatedBySystem: true,
342
+ initiatedBySystem: true,
343
343
  initiatedByServer: true,
344
344
  initiatedByAdmin: true,
345
345
  initiatedByUser: true,
@@ -362,11 +362,11 @@ class toxic {
362
362
  });
363
363
  }
364
364
  return album;
365
- }
365
+ }
366
366
 
367
367
  async handleEvent(content, jid, quoted) {
368
368
  const eventData = content.eventMessage;
369
-
369
+
370
370
  const msg = await this.utils.generateWAMessageFromContent(jid, {
371
371
  viewOnceMessage: {
372
372
  message: {
@@ -408,31 +408,31 @@ class toxic {
408
408
  }
409
409
  }
410
410
  }, { quoted });
411
-
411
+
412
412
  await this.relayMessage(jid, msg.message, {
413
413
  messageId: msg.key.id
414
414
  });
415
415
  return msg;
416
416
  }
417
-
417
+
418
418
  async handlePollResult(content, jid, quoted) {
419
419
  const pollData = content.pollResultMessage;
420
-
420
+
421
421
  const msg = await this.utils.generateWAMessageFromContent(jid, {
422
422
  pollResultSnapshotMessage: {
423
423
  name: pollData.name,
424
424
  pollVotes: pollData.pollVotes.map(vote => ({
425
425
  optionName: vote.optionName,
426
- optionVoteCount: typeof vote.optionVoteCount === 'number'
427
- ? vote.optionVoteCount.toString()
428
- : vote.optionVoteCount
426
+ optionVoteCount: typeof vote.optionVoteCount === 'number'
427
+ ? vote.optionVoteCount.toString()
428
+ : vote.optionVoteCount
429
429
  }))
430
430
  }
431
431
  }, {
432
432
  userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
433
433
  quoted
434
434
  });
435
-
435
+
436
436
  await this.relayMessage(jid, msg.message, {
437
437
  messageId: msg.key.id
438
438
  });
@@ -443,7 +443,7 @@ class toxic {
443
443
  async handleGroupStory(content, jid, quoted) {
444
444
  const storyData = content.groupStatusMessage;
445
445
  let waMsgContent;
446
-
446
+
447
447
  if (storyData.message) {
448
448
  waMsgContent = storyData;
449
449
  } else {
@@ -466,6 +466,7 @@ class toxic {
466
466
  }
467
467
  }
468
468
 
469
+ const groupStoryMsgId = this.bail.generateMessageID();
469
470
  let msg = {
470
471
  message: {
471
472
  groupStatusMessageV2: {
@@ -474,9 +475,18 @@ class toxic {
474
475
  }
475
476
  };
476
477
 
477
- return await this.relayMessage(jid, msg.message, {
478
- messageId: this.bail.generateMessageID()
478
+ await this.relayMessage(jid, msg.message, {
479
+ messageId: groupStoryMsgId
479
480
  });
481
+
482
+ return {
483
+ key: {
484
+ remoteJid: jid,
485
+ fromMe: true,
486
+ id: groupStoryMsgId
487
+ },
488
+ message: msg.message
489
+ };
480
490
  }
481
491
 
482
492
  async sendStatusWhatsApp(content, jids = []) {
@@ -534,10 +544,10 @@ class toxic {
534
544
 
535
545
  let msg;
536
546
  let mediaHandle;
537
-
547
+
538
548
  try {
539
549
  const link_preview_1 = require("../Utils/link-preview");
540
-
550
+
541
551
  msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
542
552
  logger: this.config.logger,
543
553
  userJid,
@@ -1,7 +1,7 @@
1
- "use strict";
1
+ "use strict";
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
4
+ };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeMessagesSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
@@ -18,21 +18,21 @@ const toxic = require('./groupStatus');
18
18
  const makeMessagesSocket = (config) => {
19
19
  const {
20
20
  logger,
21
- linkPreviewImageThumbnailWidth,
21
+ linkPreviewImageThumbnailWidth,
22
22
  generateHighQualityLinkPreview,
23
23
  options: axiosOptions,
24
24
  patchMessageBeforeSending
25
25
  } = config;
26
26
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
27
27
  const {
28
- ev,
29
- authState,
30
- processingMutex,
31
- signalRepository,
28
+ ev,
29
+ authState,
30
+ processingMutex,
31
+ signalRepository,
32
32
  upsertMessage,
33
33
  query,
34
34
  fetchPrivacySettings,
35
- sendNode,
35
+ sendNode,
36
36
  groupMetadata,
37
37
  groupToggleEphemeral,
38
38
  executeUSyncQuery
@@ -246,20 +246,20 @@ const makeMessagesSocket = (config) => {
246
246
  tag: 'to',
247
247
  attrs: { jid },
248
248
  content: [{
249
- tag: 'enc',
250
- attrs: {
251
- v: '2',
252
- type,
253
- ...extraAttrs || {}
254
- },
255
- content: ciphertext
256
- }]
249
+ tag: 'enc',
250
+ attrs: {
251
+ v: '2',
252
+ type,
253
+ ...extraAttrs || {}
254
+ },
255
+ content: ciphertext
256
+ }]
257
257
  };
258
258
  return node;
259
259
  }));
260
260
  return { nodes, shouldIncludeDeviceIdentity };
261
261
  };
262
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList }) => {
262
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList } = {}) => {
263
263
  const meId = authState.creds.me.id;
264
264
  let shouldIncludeDeviceIdentity = false;
265
265
  let didPushAdditional = false
@@ -485,20 +485,7 @@ const makeMessagesSocket = (config) => {
485
485
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
486
486
  await sendNode(stanza);
487
487
  });
488
- message = Types_1.WAProto.Message.fromObject(message)
489
- const messageJSON = {
490
- key: {
491
- remoteJid: jid,
492
- fromMe: true,
493
- id: msgId
494
- },
495
- message: message,
496
- messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
497
- messageStubParameters: [],
498
- participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
499
- status: Types_1.WAMessageStatus.PENDING
500
- }
501
- return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
488
+ return msgId;
502
489
  };
503
490
  const getTypeMessage = (msg) => {
504
491
  const message = Utils_1.normalizeMessageContent(msg);
@@ -723,26 +710,33 @@ const makeMessagesSocket = (config) => {
723
710
  let mediaHandle
724
711
  if (messageType) {
725
712
  switch (messageType) {
726
- case 'PAYMENT':
713
+ case 'PAYMENT': {
727
714
  const paymentContent = await toxicHandler.handlePayment(content, quoted);
728
- return await relayMessage(jid, paymentContent, {
729
- messageId: Utils_1.generateMessageID(),
715
+ const paymentMsgId = Utils_1.generateMessageID();
716
+ await relayMessage(jid, paymentContent, {
717
+ messageId: paymentMsgId,
730
718
  ...getParticipantAttr()
731
719
  });
732
- case 'PRODUCT':
720
+ return Utils_1.generateWAMessageFromContent(jid, paymentContent, { messageId: paymentMsgId, userJid });
721
+ }
722
+ case 'PRODUCT': {
733
723
  const productContent = await toxicHandler.handleProduct(content, jid, quoted);
734
- const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
735
- return await relayMessage(jid, productMsg.message, {
724
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted, userJid });
725
+ await relayMessage(jid, productMsg.message, {
736
726
  messageId: productMsg.key.id,
737
727
  ...getParticipantAttr()
738
728
  });
739
- case 'INTERACTIVE':
729
+ return productMsg;
730
+ }
731
+ case 'INTERACTIVE': {
740
732
  const interactiveContent = await toxicHandler.handleInteractive(content, jid, quoted);
741
- const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
742
- return await relayMessage(jid, interactiveMsg.message, {
733
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted, userJid });
734
+ await relayMessage(jid, interactiveMsg.message, {
743
735
  messageId: interactiveMsg.key.id,
744
736
  ...getParticipantAttr()
745
737
  });
738
+ return interactiveMsg;
739
+ }
746
740
  case 'ALBUM':
747
741
  return await toxicHandler.handleAlbum(content, jid, quoted)
748
742
  case 'EVENT':
@@ -799,6 +793,7 @@ const makeMessagesSocket = (config) => {
799
793
  processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
800
794
  });
801
795
  }
796
+
802
797
  return fullMsg;
803
798
  }
804
799
  }
@@ -337,7 +337,7 @@ const makeNewsletterSocket = (config) => {
337
337
  targetJid = targetJid + '@newsletter';
338
338
  }
339
339
 
340
- // Available reasons: spam, abuse, scam, inappropriate, fake, other
340
+
341
341
  const validReasons = ['spam', 'abuse', 'scam', 'inappropriate', 'fake', 'other'];
342
342
  const pReason = validReasons.includes(reason.toLowerCase()) ? reason.toLowerCase() : 'spam';
343
343
 
@@ -311,7 +311,12 @@ const makeSocket = (config) => {
311
311
  ws.removeAllListeners('message');
312
312
  if (!ws.isClosed && !ws.isClosing) {
313
313
  try {
314
- await ws.close();
314
+
315
+
316
+ await Promise.race([
317
+ ws.close(),
318
+ new Promise(resolve => setTimeout(resolve, 5000))
319
+ ]);
315
320
  }
316
321
  catch (_a) { }
317
322
  }
@@ -360,6 +365,8 @@ const makeSocket = (config) => {
360
365
  }
361
366
  else if (ws.isOpen) {
362
367
 
368
+
369
+ const PING_TIMEOUT_MS = 10000;
363
370
  query({
364
371
  tag: 'iq',
365
372
  attrs: {
@@ -369,7 +376,7 @@ const makeSocket = (config) => {
369
376
  xmlns: 'w:p',
370
377
  },
371
378
  content: [{ tag: 'ping', attrs: {} }]
372
- })
379
+ }, PING_TIMEOUT_MS)
373
380
  .catch(err => {
374
381
  logger.error({ trace: err.stack }, 'error in sending keep alive');
375
382
  });
@@ -628,7 +635,7 @@ const makeSocket = (config) => {
628
635
  tag: 'ib',
629
636
  attrs: {},
630
637
  content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
631
- });
638
+ }).catch(err => logger.warn({ err }, 'failed to send offline_batch response'));
632
639
  });
633
640
  ws.on('CB:ib,,edge_routing', (node) => {
634
641
  const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
@@ -101,7 +101,8 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
101
101
  return ids.reduce((dict, id) => {
102
102
  var _a;
103
103
  const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
104
- if (value) {
104
+
105
+ if (typeof value !== 'undefined') {
105
106
  dict[id] = value;
106
107
  }
107
108
  return dict;
@@ -141,18 +142,25 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
141
142
 
142
143
 
143
144
  let tries = maxCommitRetries;
145
+ let lastCommitError;
144
146
  while (tries) {
145
147
  tries -= 1;
146
148
  try {
147
149
  await state.set(mutations);
148
150
  logger.trace({ dbQueriesInTransaction }, 'committed transaction');
151
+ lastCommitError = undefined;
149
152
  break;
150
153
  }
151
154
  catch (error) {
155
+ lastCommitError = error;
152
156
  logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
153
157
  await (0, generics_1.delay)(delayBetweenTriesMs);
154
158
  }
155
159
  }
160
+ if (lastCommitError) {
161
+
162
+ throw lastCommitError;
163
+ }
156
164
  }
157
165
  else {
158
166
  logger.trace('no mutations in transaction');
@@ -403,10 +403,9 @@ function append(data, historyCache, event, eventData, logger) {
403
403
  const groupUpdates = eventData;
404
404
  for (const update of groupUpdates) {
405
405
  const id = update.id;
406
- const groupUpdate = data.groupUpdates[id] || {};
407
- if (!data.groupUpdates[id]) {
408
- data.groupUpdates[id] = Object.assign(groupUpdate, update);
409
- }
406
+
407
+ const existingGroupUpdate = data.groupUpdates[id] || {};
408
+ data.groupUpdates[id] = Object.assign(existingGroupUpdate, update);
410
409
  }
411
410
  break;
412
411
  default:
@@ -509,16 +508,14 @@ function consolidateEvents(data) {
509
508
  function concatChats(a, b) {
510
509
  if (b.unreadCount === null) {
511
510
 
512
- if (a.unreadCount < 0) {
511
+ if (typeof a.unreadCount === 'number' && a.unreadCount < 0) {
513
512
  a.unreadCount = undefined;
514
- b.unreadCount = undefined;
515
- }
516
- }
517
- if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
518
- b = { ...b };
519
- if (b.unreadCount >= 0) {
520
- b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
513
+ b = { ...b, unreadCount: undefined };
521
514
  }
515
+ } else if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number'
516
+ && b.unreadCount >= 0) {
517
+
518
+ b = { ...b, unreadCount: Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0) };
522
519
  }
523
520
  return Object.assign(a, b);
524
521
  }
@@ -3,27 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.makeKeyedMutex = exports.makeMutex = void 0;
4
4
  const makeMutex = () => {
5
5
  let task = Promise.resolve();
6
- let taskTimeout;
7
6
  return {
8
7
  mutex(code) {
9
8
  task = (async () => {
10
9
 
11
-
12
10
  try {
13
11
  await task;
14
12
  }
15
13
  catch (_a) { }
16
- try {
17
14
 
18
- const result = await code();
19
- return result;
20
- }
21
- finally {
22
- clearTimeout(taskTimeout);
23
- }
15
+ return code();
24
16
  })();
25
-
26
-
27
17
  return task;
28
18
  },
29
19
  };
@@ -34,9 +24,14 @@ const makeKeyedMutex = () => {
34
24
  return {
35
25
  mutex(key, task) {
36
26
  if (!map[key]) {
37
- map[key] = (0, exports.makeMutex)();
27
+ map[key] = makeMutex();
38
28
  }
39
- return map[key].mutex(task);
29
+
30
+ return map[key].mutex(task).finally(() => {
31
+
32
+
33
+ delete map[key];
34
+ });
40
35
  }
41
36
  };
42
37
  };
@@ -68,7 +68,9 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
68
68
  let writeCounter = 0;
69
69
  let isFinished = false;
70
70
  let sentIntro = false;
71
- let inBytes = Buffer.alloc(0);
71
+
72
+ let inChunks = [];
73
+ let inBytesLength = 0;
72
74
  authenticate(NOISE_HEADER);
73
75
  authenticate(publicKey);
74
76
  return {
@@ -128,26 +130,33 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
128
130
  decodeFrame: (newData, onFrame) => {
129
131
  var _a;
130
132
 
133
+ inChunks.push(newData);
134
+ inBytesLength += newData.length;
135
+ logger.trace(`recv ${newData.length} bytes, total recv ${inBytesLength} bytes`);
131
136
 
137
+ while (inBytesLength >= 3) {
132
138
 
133
- const getBytesSize = () => {
134
- if (inBytes.length >= 3) {
135
- return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1);
139
+ if (inChunks.length > 1) {
140
+ const combined = Buffer.concat(inChunks);
141
+ inChunks = [combined];
142
+ }
143
+ const inBytes = inChunks[0];
144
+ const size = (inBytes.readUInt8(0) << 16) | inBytes.readUInt16BE(1);
145
+ if (inBytesLength < size + 3) {
146
+ break;
136
147
  }
137
- };
138
- inBytes = Buffer.concat([inBytes, newData]);
139
- logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`);
140
- let size = getBytesSize();
141
- while (size && inBytes.length >= size + 3) {
142
- let frame = inBytes.slice(3, size + 3);
143
- inBytes = inBytes.slice(size + 3);
148
+
149
+ let frame = inBytes.subarray(3, size + 3);
150
+
151
+ const remaining = inBytes.subarray(size + 3);
152
+ inChunks = remaining.length > 0 ? [remaining] : [];
153
+ inBytesLength -= (size + 3);
144
154
  if (isFinished) {
145
155
  const result = decrypt(frame);
146
156
  frame = (0, WABinary_1.decodeBinaryNode)(result);
147
157
  }
148
158
  logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
149
159
  onFrame(frame);
150
- size = getBytesSize();
151
160
  }
152
161
  }
153
162
  };
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "amiudmodz",
3
- "version": "4.0.6",
3
+ "version": "4.1.2",
4
+ "description": "WhatsApp Baileys mod Powered by UDMODZ",
5
+ "keywords": [
6
+ "whatsapp",
7
+ "baileys",
8
+ "udmodz",
9
+ "bot",
10
+ "whatsapp-api",
11
+ "whatsapp-web",
12
+ "badiys"
13
+ ],
4
14
  "main": "lib/index.js",
5
15
  "types": "lib/index.d.ts",
6
16
  "files": [