@d0v3riz/baileys 6.7.1 → 6.7.4

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.
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": [2, 2403, 2]
2
+ "version": [2, 2413, 1]
3
3
  }
@@ -2,6 +2,7 @@
2
2
  import { GetCatalogOptions, ProductCreate, ProductUpdate, SocketConfig } from '../Types';
3
3
  import { BinaryNode } from '../WABinary';
4
4
  export declare const makeBusinessSocket: (config: SocketConfig) => {
5
+ logger: import("pino").Logger<import("pino").LoggerOptions>;
5
6
  getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../Types").OrderDetails>;
6
7
  getCatalog: ({ jid, limit, cursor }: GetCatalogOptions) => Promise<{
7
8
  products: import("../Types").Product[];
@@ -248,6 +248,7 @@ const makeBusinessSocket = (config) => {
248
248
  };
249
249
  return {
250
250
  ...sock,
251
+ logger: config.logger,
251
252
  getOrderDetails,
252
253
  getCatalog,
253
254
  getCollections,
@@ -61,6 +61,9 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
61
61
  creds: import("../Types").AuthenticationCreds;
62
62
  keys: import("../Types").SignalKeyStoreWithTransaction;
63
63
  };
64
+ /**
65
+ * Star or Unstar a message
66
+ */
64
67
  signalRepository: import("../Types").SignalRepository;
65
68
  user: import("../Types").Contact | undefined;
66
69
  generateMessageTag: () => string;
@@ -72,6 +75,9 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
72
75
  logout: (msg?: string | undefined) => Promise<void>;
73
76
  end: (error: Error | undefined) => void;
74
77
  onUnexpectedError: (err: Error | Boom<any>, msg: string) => void;
78
+ /**
79
+ * Adds label for the chats
80
+ */
75
81
  uploadPreKeys: (count?: number) => Promise<void>;
76
82
  uploadPreKeysToServerIfRequired: () => Promise<void>;
77
83
  requestPairingCode: (phoneNumber: string) => Promise<string>;
@@ -511,7 +511,7 @@ const makeChatsSocket = (config) => {
511
511
  let presence;
512
512
  const jid = attrs.from;
513
513
  const participant = attrs.participant || attrs.from;
514
- if (shouldIgnoreJid(jid)) {
514
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
515
515
  return;
516
516
  }
517
517
  if (tag === 'presence') {
@@ -597,29 +597,9 @@ const makeChatsSocket = (config) => {
597
597
  }
598
598
  }
599
599
  };
600
- /** sending abt props may fix QR scan fail if server expects */
601
- const fetchAbt = async () => {
602
- const abtNode = await query({
603
- tag: 'iq',
604
- attrs: {
605
- to: WABinary_1.S_WHATSAPP_NET,
606
- xmlns: 'abt',
607
- type: 'get',
608
- },
609
- content: [
610
- { tag: 'props', attrs: { protocol: '1' } }
611
- ]
612
- });
613
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(abtNode, 'props');
614
- let props = {};
615
- if (propsNode) {
616
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
617
- }
618
- logger.debug('fetched abt');
619
- return props;
620
- };
621
600
  /** sending non-abt props may fix QR scan fail if server expects */
622
601
  const fetchProps = async () => {
602
+ var _a, _b;
623
603
  const resultNode = await query({
624
604
  tag: 'iq',
625
605
  attrs: {
@@ -628,12 +608,17 @@ const makeChatsSocket = (config) => {
628
608
  type: 'get',
629
609
  },
630
610
  content: [
631
- { tag: 'props', attrs: {} }
611
+ { tag: 'props', attrs: {
612
+ protocol: '2',
613
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
614
+ } }
632
615
  ]
633
616
  });
634
617
  const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
635
618
  let props = {};
636
619
  if (propsNode) {
620
+ authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
621
+ ev.emit('creds.update', authState.creds);
637
622
  props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
638
623
  }
639
624
  logger.debug('fetched props');
@@ -707,7 +692,6 @@ const makeChatsSocket = (config) => {
707
692
  * */
708
693
  const executeInitQueries = async () => {
709
694
  await Promise.all([
710
- fetchAbt(),
711
695
  fetchProps(),
712
696
  fetchBlocklist(),
713
697
  fetchPrivacySettings(),
@@ -3,6 +3,7 @@ import { UserFacingSocketConfig } from '../Types';
3
3
  declare const makeWASocket: (config: UserFacingSocketConfig) => {
4
4
  register: (code: string) => Promise<import("./registration").ExistsResponse>;
5
5
  requestRegistrationCode: (registrationOptions?: import("./registration").RegistrationOptions | undefined) => Promise<import("./registration").ExistsResponse>;
6
+ logger: import("pino").Logger<import("pino").LoggerOptions>;
6
7
  getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../Types").OrderDetails>;
7
8
  getCatalog: ({ jid, limit, cursor }: import("../Types").GetCatalogOptions) => Promise<{
8
9
  products: import("../Types").Product[];
@@ -163,6 +163,8 @@ const makeMessagesRecvSocket = (config) => {
163
163
  }
164
164
  };
165
165
  const handleGroupNotification = (participant, child, msg) => {
166
+ var _a, _b;
167
+ const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
166
168
  switch (child === null || child === void 0 ? void 0 : child.tag) {
167
169
  case 'create':
168
170
  const metadata = (0, groups_1.extractGroupMetadata)(child);
@@ -237,6 +239,15 @@ const makeMessagesRecvSocket = (config) => {
237
239
  msg.messageStubParameters = [approvalMode.attrs.state];
238
240
  }
239
241
  break;
242
+ case 'created_membership_requests':
243
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
244
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
245
+ break;
246
+ case 'revoked_membership_requests':
247
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
248
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
249
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
250
+ break;
240
251
  }
241
252
  };
242
253
  const processNotification = async (node) => {
@@ -461,7 +472,7 @@ const makeMessagesRecvSocket = (config) => {
461
472
  fromMe,
462
473
  participant: attrs.participant
463
474
  };
464
- if (shouldIgnoreJid(remoteJid)) {
475
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
465
476
  logger.debug({ remoteJid }, 'ignoring receipt from jid');
466
477
  await sendMessageAck(node);
467
478
  return;
@@ -480,7 +491,7 @@ const makeMessagesRecvSocket = (config) => {
480
491
  // or another device of ours has read some messages
481
492
  status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
482
493
  !isNodeFromMe)) {
483
- if ((0, WABinary_1.isJidGroup)(remoteJid)) {
494
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
484
495
  if (attrs.participant) {
485
496
  const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
486
497
  ev.emit('message-receipt.update', ids.map(id => ({
@@ -527,7 +538,7 @@ const makeMessagesRecvSocket = (config) => {
527
538
  };
528
539
  const handleNotification = async (node) => {
529
540
  const remoteJid = node.attrs.from;
530
- if (shouldIgnoreJid(remoteJid)) {
541
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
531
542
  logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
532
543
  await sendMessageAck(node);
533
544
  return;
@@ -556,17 +567,17 @@ const makeMessagesRecvSocket = (config) => {
556
567
  };
557
568
  const handleMessage = async (node) => {
558
569
  var _a, _b;
570
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
571
+ logger.debug({ key: node.attrs.key }, 'ignored message');
572
+ await sendMessageAck(node);
573
+ return;
574
+ }
559
575
  const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
560
576
  if (((_b = (_a = msg.message) === null || _a === void 0 ? void 0 : _a.protocolMessage) === null || _b === void 0 ? void 0 : _b.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER) {
561
577
  if (node.attrs.sender_pn) {
562
578
  ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
563
579
  }
564
580
  }
565
- if (shouldIgnoreJid(msg.key.remoteJid)) {
566
- logger.debug({ key: msg.key }, 'ignored message');
567
- await sendMessageAck(node);
568
- return;
569
- }
570
581
  await Promise.all([
571
582
  processingMutex.mutex(async () => {
572
583
  await decrypt();
@@ -4,6 +4,7 @@ import { KeyPair, SignedKeyPair, SocketConfig } from '../Types';
4
4
  export declare const makeRegistrationSocket: (config: SocketConfig) => {
5
5
  register: (code: string) => Promise<ExistsResponse>;
6
6
  requestRegistrationCode: (registrationOptions?: RegistrationOptions) => Promise<ExistsResponse>;
7
+ logger: import("pino").Logger<import("pino").LoggerOptions>;
7
8
  getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../Types").OrderDetails>;
8
9
  getCatalog: ({ jid, limit, cursor }: import("../Types").GetCatalogOptions) => Promise<{
9
10
  products: import("../Types").Product[];
@@ -18,12 +18,16 @@ const Client_1 = require("./Client");
18
18
  * - query phone connection
19
19
  */
20
20
  const makeSocket = (config) => {
21
+ var _a, _b;
21
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
22
23
  let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
23
24
  config.mobile = config.mobile || url.protocol === 'tcp:';
24
25
  if (config.mobile && url.protocol !== 'tcp:') {
25
26
  url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
26
27
  }
28
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
30
+ }
27
31
  const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
28
32
  ws.connect();
29
33
  const ev = (0, Utils_1.makeEventBuffer)(logger);
@@ -34,7 +38,8 @@ const makeSocket = (config) => {
34
38
  keyPair: ephemeralKeyPair,
35
39
  NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
36
40
  mobile: config.mobile,
37
- logger
41
+ logger,
42
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
38
43
  });
39
44
  const { creds } = authState;
40
45
  // add transaction capability
@@ -526,6 +531,14 @@ const makeSocket = (config) => {
526
531
  ws.on('CB:ib,,downgrade_webclient', () => {
527
532
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
528
533
  });
534
+ ws.on('CB:ib,,edge_routing', (node) => {
535
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
536
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
537
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
538
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
539
+ ev.emit('creds.update', authState.creds);
540
+ }
541
+ });
529
542
  let didStartBuffer = false;
530
543
  process.nextTick(() => {
531
544
  var _a;
@@ -20,7 +20,7 @@ export type BaileysInMemoryStoreConfig = {
20
20
  logger?: Logger;
21
21
  socket?: WASocket;
22
22
  };
23
- declare const _default: ({ logger: _logger, chatKey, labelAssociationKey, socket }: BaileysInMemoryStoreConfig) => {
23
+ declare const _default: (config: BaileysInMemoryStoreConfig) => {
24
24
  chats: KeyedDB<Chat, string>;
25
25
  contacts: {
26
26
  [_: string]: Contact;
@@ -23,48 +23,11 @@ exports.waLabelAssociationKey = {
23
23
  compare: (k1, k2) => k2.localeCompare(k1)
24
24
  };
25
25
  const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID);
26
- const predefinedLabels = Object.freeze({
27
- '1': {
28
- id: '1',
29
- name: 'New customer',
30
- predefinedId: '1',
31
- color: 1,
32
- deleted: false
33
- },
34
- '2': {
35
- id: '2',
36
- name: 'New order',
37
- predefinedId: '2',
38
- color: 2,
39
- deleted: false
40
- },
41
- '3': {
42
- id: '3',
43
- name: 'Pending payment',
44
- predefinedId: '3',
45
- color: 3,
46
- deleted: false
47
- },
48
- '4': {
49
- id: '4',
50
- name: 'Paid',
51
- predefinedId: '4',
52
- color: 4,
53
- deleted: false
54
- },
55
- '5': {
56
- id: '5',
57
- name: 'Order completed',
58
- predefinedId: '5',
59
- color: 5,
60
- deleted: false
61
- }
62
- });
63
- exports.default = ({ logger: _logger, chatKey, labelAssociationKey, socket }) => {
64
- // const logger = _logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
65
- chatKey = chatKey || (0, exports.waChatKey)(true);
66
- labelAssociationKey = labelAssociationKey || exports.waLabelAssociationKey;
67
- const logger = _logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
26
+ exports.default = (config) => {
27
+ const socket = config.socket;
28
+ const chatKey = config.chatKey || (0, exports.waChatKey)(true);
29
+ const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey;
30
+ const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
68
31
  const KeyedDB = require('@adiwajshing/keyed-db').default;
69
32
  const chats = new KeyedDB(chatKey, c => c.id);
70
33
  const messages = {};
@@ -72,7 +35,7 @@ exports.default = ({ logger: _logger, chatKey, labelAssociationKey, socket }) =>
72
35
  const groupMetadata = {};
73
36
  const presences = {};
74
37
  const state = { connection: 'close' };
75
- const labels = new object_repository_1.ObjectRepository(predefinedLabels);
38
+ const labels = new object_repository_1.ObjectRepository();
76
39
  const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
77
40
  const assertMessageList = (jid) => {
78
41
  if (!messages[jid]) {
@@ -130,31 +93,31 @@ exports.default = ({ logger: _logger, chatKey, labelAssociationKey, socket }) =>
130
93
  contactsUpsert(contacts);
131
94
  });
132
95
  ev.on('contacts.update', async (updates) => {
96
+ var _a;
133
97
  for (const update of updates) {
134
98
  let contact;
135
99
  if (contacts[update.id]) {
136
100
  contact = contacts[update.id];
137
101
  }
138
102
  else {
139
- const contactHashes = await Promise.all(Object.keys(contacts).map(async (a) => {
140
- return (await (0, Utils_1.md5)(Buffer.from(a + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3);
103
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
104
+ const { user } = (0, WABinary_1.jidDecode)(contactId);
105
+ return [contactId, (await (0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
141
106
  }));
142
- contact = contacts[contactHashes.find(a => a === update.id) || ''];
107
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
143
108
  }
144
- if (update.imgUrl === 'changed' || update.imgUrl === 'removed') {
145
- if (contact) {
146
- if (update.imgUrl === 'changed') {
147
- contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
148
- }
149
- else {
150
- delete contact.imgUrl;
151
- }
109
+ if (contact) {
110
+ if (update.imgUrl === 'changed') {
111
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
152
112
  }
153
- else {
154
- return logger.debug({ update }, 'got update for non-existant contact');
113
+ else if (update.imgUrl === 'removed') {
114
+ delete contact.imgUrl;
155
115
  }
156
116
  }
157
- Object.assign(contacts[update.id], contact);
117
+ else {
118
+ return logger.debug({ update }, 'got update for non-existant contact');
119
+ }
120
+ Object.assign(contacts[contact.id], contact);
158
121
  }
159
122
  });
160
123
  ev.on('chats.upsert', newChats => {
@@ -64,6 +64,8 @@ export type AuthenticationCreds = SignalCreds & {
64
64
  backupToken: Buffer;
65
65
  registration: RegistrationOptions;
66
66
  pairingCode: string | undefined;
67
+ lastPropHash: string | undefined;
68
+ routingInfo: Buffer | undefined;
67
69
  };
68
70
  export type SignalDataTypeMap = {
69
71
  'pre-key': KeyPair;
@@ -4,7 +4,7 @@ import { AuthenticationCreds } from './Auth';
4
4
  import { WACallEvent } from './Call';
5
5
  import { Chat, ChatUpdate, PresenceData } from './Chat';
6
6
  import { Contact } from './Contact';
7
- import { GroupMetadata, ParticipantAction } from './GroupMetadata';
7
+ import { GroupMetadata, ParticipantAction, RequestJoinAction, RequestJoinMethod } from './GroupMetadata';
8
8
  import { Label } from './Label';
9
9
  import { LabelAssociation } from './LabelAssociation';
10
10
  import { MessageUpsertType, MessageUserReceiptUpdate, WAMessage, WAMessageKey, WAMessageUpdate } from './Message';
@@ -78,6 +78,13 @@ export type BaileysEventMap = {
78
78
  participants: string[];
79
79
  action: ParticipantAction;
80
80
  };
81
+ 'group.join-request': {
82
+ id: string;
83
+ author: string;
84
+ participant: string;
85
+ action: RequestJoinAction;
86
+ method: RequestJoinMethod;
87
+ };
81
88
  'blocklist.set': {
82
89
  blocklist: string[];
83
90
  };
@@ -5,6 +5,8 @@ export type GroupParticipant = (Contact & {
5
5
  admin?: 'admin' | 'superadmin' | null;
6
6
  });
7
7
  export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote';
8
+ export type RequestJoinAction = 'created' | 'revoked' | 'rejected';
9
+ export type RequestJoinMethod = 'invite_link' | 'linked_group_join' | 'non_admin_add' | undefined;
8
10
  export interface GroupMetadata {
9
11
  id: string;
10
12
  owner: string | undefined;
@@ -210,6 +210,8 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
210
210
  backgroundColor?: string;
211
211
  /** font type for status */
212
212
  font?: number;
213
+ /** if it is broadcast */
214
+ broadcast?: boolean;
213
215
  };
214
216
  export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions & {
215
217
  userJid: string;
@@ -199,6 +199,8 @@ const initAuthCreds = () => {
199
199
  backupToken: (0, crypto_1.randomBytes)(20),
200
200
  registration: {},
201
201
  pairingCode: undefined,
202
+ lastPropHash: undefined,
203
+ routingInfo: undefined,
202
204
  };
203
205
  };
204
206
  exports.initAuthCreds = initAuthCreds;
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
3
  import { Logger } from 'pino';
4
+ import { type Transform } from 'stream';
4
5
  import { proto } from '../../WAProto';
5
6
  import { AnyMediaMessageContent, AnyMessageContent, MediaGenerationOptions, MessageContentGenerationOptions, MessageGenerationOptions, MessageGenerationOptionsFromContent, MessageUserReceipt, WAMessage, WAMessageContent, WAProto } from '../Types';
6
7
  import { MediaDownloadOptions } from './messages-media';
@@ -70,7 +71,7 @@ type DownloadMediaMessageContext = {
70
71
  /**
71
72
  * Downloads the given message. Throws an error if it's not a media message
72
73
  */
73
- export declare const downloadMediaMessage: (message: WAMessage, type: 'buffer' | 'stream', options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Buffer | import("stream").Transform>;
74
+ export declare const downloadMediaMessage: <Type extends "stream" | "buffer">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer : Transform>;
74
75
  /** Checks whether the given message is a media message; if it is returns the inner content */
75
76
  export declare const assertMediaContent: (content: proto.IMessage | null | undefined) => proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
76
77
  export {};
@@ -706,12 +706,9 @@ const REUPLOAD_REQUIRED_STATUS = [410, 404];
706
706
  * Downloads the given message. Throws an error if it's not a media message
707
707
  */
708
708
  const downloadMediaMessage = async (message, type, options, ctx) => {
709
- var _a;
710
- try {
711
- const result = await downloadMsg();
712
- return result;
713
- }
714
- catch (error) {
709
+ const result = await downloadMsg()
710
+ .catch(async (error) => {
711
+ var _a;
715
712
  if (ctx) {
716
713
  if (axios_1.default.isAxiosError(error)) {
717
714
  // check if the message requires a reupload
@@ -725,7 +722,8 @@ const downloadMediaMessage = async (message, type, options, ctx) => {
725
722
  }
726
723
  }
727
724
  throw error;
728
- }
725
+ });
726
+ return result;
729
727
  async function downloadMsg() {
730
728
  const mContent = (0, exports.extractMessageContent)(message.message);
731
729
  if (!mContent) {
@@ -3,11 +3,12 @@ import { Logger } from 'pino';
3
3
  import { proto } from '../../WAProto';
4
4
  import { KeyPair } from '../Types';
5
5
  import { BinaryNode } from '../WABinary';
6
- export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, }: {
6
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }: {
7
7
  keyPair: KeyPair;
8
8
  NOISE_HEADER: Uint8Array;
9
9
  mobile: boolean;
10
10
  logger: Logger;
11
+ routingInfo?: Buffer | undefined;
11
12
  }) => {
12
13
  encrypt: (plaintext: Uint8Array) => Buffer;
13
14
  decrypt: (ciphertext: Uint8Array) => Buffer;
@@ -11,7 +11,7 @@ const generateIV = (counter) => {
11
11
  new DataView(iv).setUint32(8, counter);
12
12
  return new Uint8Array(iv);
13
13
  };
14
- const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, }) => {
14
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
15
15
  logger = logger.child({ class: 'ns' });
16
16
  const authenticate = (data) => {
17
17
  if (!isFinished) {
@@ -101,10 +101,23 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
101
101
  if (isFinished) {
102
102
  data = encrypt(data);
103
103
  }
104
- const introSize = sentIntro ? 0 : NOISE_HEADER.length;
104
+ let header;
105
+ if (routingInfo) {
106
+ header = Buffer.alloc(7);
107
+ header.write('ED', 0, 'utf8');
108
+ header.writeUint8(0, 2);
109
+ header.writeUint8(1, 3);
110
+ header.writeUint8(routingInfo.byteLength >> 16, 4);
111
+ header.writeUint16BE(routingInfo.byteLength & 65535, 5);
112
+ header = Buffer.concat([header, routingInfo, NOISE_HEADER]);
113
+ }
114
+ else {
115
+ header = Buffer.from(NOISE_HEADER);
116
+ }
117
+ const introSize = sentIntro ? 0 : header.length;
105
118
  const frame = Buffer.alloc(introSize + 3 + data.byteLength);
106
119
  if (!sentIntro) {
107
- frame.set(NOISE_HEADER);
120
+ frame.set(header);
108
121
  sentIntro = true;
109
122
  }
110
123
  frame.writeUInt8(data.byteLength >> 16, introSize);
@@ -103,7 +103,7 @@ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pol
103
103
  }
104
104
  exports.decryptPollVote = decryptPollVote;
105
105
  const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage }) => {
106
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
107
107
  const meId = creds.me.id;
108
108
  const { accountSettings } = creds;
109
109
  const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
@@ -220,6 +220,9 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
220
220
  var _a;
221
221
  ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
222
222
  };
223
+ const emitGroupRequestJoin = (participant, action, method) => {
224
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
225
+ };
223
226
  const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
224
227
  switch (message.messageStubType) {
225
228
  case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
@@ -273,6 +276,12 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
273
276
  const approvalMode = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
274
277
  emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
275
278
  break;
279
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
280
+ const participant = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
281
+ const action = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[1];
282
+ const method = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[2];
283
+ emitGroupRequestJoin(participant, action, method);
284
+ break;
276
285
  }
277
286
  }
278
287
  else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
@@ -283,7 +292,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
283
292
  const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
284
293
  const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
285
294
  const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
286
- const pollEncKey = (_k = pollMsg.messageContextInfo) === null || _k === void 0 ? void 0 : _k.messageSecret;
295
+ const pollEncKey = (_o = pollMsg.messageContextInfo) === null || _o === void 0 ? void 0 : _o.messageSecret;
287
296
  try {
288
297
  const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
289
298
  pollEncKey,
@@ -1,11 +1,21 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.useMultiFileAuthState = void 0;
7
+ const async_lock_1 = __importDefault(require("async-lock"));
4
8
  const promises_1 = require("fs/promises");
5
9
  const path_1 = require("path");
6
10
  const WAProto_1 = require("../../WAProto");
7
11
  const auth_utils_1 = require("./auth-utils");
8
12
  const generics_1 = require("./generics");
13
+ // We need to lock files due to the fact that we are using async functions to read and write files
14
+ // https://github.com/WhiskeySockets/Baileys/issues/794
15
+ // https://github.com/nodejs/node/issues/26338
16
+ // Default pending is 1000, set it to infinity
17
+ // https://github.com/rogierschouten/async-lock/issues/63
18
+ const fileLock = new async_lock_1.default({ maxPending: Infinity });
9
19
  /**
10
20
  * stores the full authentication state in a single folder.
11
21
  * Far more efficient than singlefileauthstate
@@ -15,11 +25,13 @@ const generics_1 = require("./generics");
15
25
  * */
16
26
  const useMultiFileAuthState = async (folder) => {
17
27
  const writeData = (data, file) => {
18
- return (0, promises_1.writeFile)((0, path_1.join)(folder, fixFileName(file)), JSON.stringify(data, generics_1.BufferJSON.replacer));
28
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
29
+ return fileLock.acquire(filePath, () => (0, promises_1.writeFile)((0, path_1.join)(filePath), JSON.stringify(data, generics_1.BufferJSON.replacer)));
19
30
  };
20
31
  const readData = async (file) => {
21
32
  try {
22
- const data = await (0, promises_1.readFile)((0, path_1.join)(folder, fixFileName(file)), { encoding: 'utf-8' });
33
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
34
+ const data = await fileLock.acquire(filePath, () => (0, promises_1.readFile)(filePath, { encoding: 'utf-8' }));
23
35
  return JSON.parse(data, generics_1.BufferJSON.reviver);
24
36
  }
25
37
  catch (error) {
@@ -28,7 +40,8 @@ const useMultiFileAuthState = async (folder) => {
28
40
  };
29
41
  const removeData = async (file) => {
30
42
  try {
31
- await (0, promises_1.unlink)((0, path_1.join)(folder, fixFileName(file)));
43
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
44
+ await fileLock.acquire(filePath, () => (0, promises_1.unlink)(filePath));
32
45
  }
33
46
  catch (_a) {
34
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@d0v3riz/baileys",
3
- "version": "6.7.1",
3
+ "version": "6.7.4",
4
4
  "description": "WhatsApp API",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -46,6 +46,7 @@
46
46
  "@adiwajshing/keyed-db": "^0.2.4",
47
47
  "@d0v3riz/ws": "^8.13.0",
48
48
  "@hapi/boom": "^9.1.3",
49
+ "async-lock": "^1.4.1",
49
50
  "audio-decode": "^2.1.3",
50
51
  "axios": "^1.3.3",
51
52
  "cache-manager": "4.0.1",
@@ -70,6 +71,7 @@
70
71
  "eslint": "^8.0.0",
71
72
  "jest": "^27.0.6",
72
73
  "jimp": "^0.16.1",
74
+ "json": "^11.0.0",
73
75
  "link-preview-js": "^3.0.0",
74
76
  "open": "^8.4.2",
75
77
  "qrcode-terminal": "^0.12.0",
@@ -78,8 +80,7 @@
78
80
  "ts-jest": "^27.0.3",
79
81
  "ts-node": "^10.8.1",
80
82
  "typedoc": "^0.24.7",
81
- "typescript": "^4.6.4",
82
- "json": "^11.0.0"
83
+ "typescript": "^4.6.4"
83
84
  },
84
85
  "peerDependencies": {
85
86
  "jimp": "^0.16.1",