gifted-baileys 1.5.0 → 1.5.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.
Files changed (120) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1429 -684
  3. package/WAProto/WAProto.proto +969 -88
  4. package/WAProto/index.d.ts +13199 -1260
  5. package/WAProto/index.js +124901 -74525
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.d.ts +2 -2
  8. package/lib/Defaults/index.js +6 -5
  9. package/lib/Defaults/phonenumber-mcc.json +221 -221
  10. package/lib/Signal/libsignal.js +18 -9
  11. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -2
  12. package/lib/Socket/Client/index.d.ts +2 -3
  13. package/lib/Socket/Client/index.js +2 -3
  14. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -1
  15. package/lib/Socket/Client/types.d.ts +17 -0
  16. package/lib/Socket/Client/types.js +13 -0
  17. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  18. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +2 -2
  19. package/lib/Socket/business.d.ts +64 -29
  20. package/lib/Socket/business.js +1 -0
  21. package/lib/Socket/chats.d.ts +10 -8
  22. package/lib/Socket/chats.js +114 -97
  23. package/lib/Socket/groups.d.ts +10 -8
  24. package/lib/Socket/groups.js +4 -2
  25. package/lib/Socket/index.d.ts +70 -35
  26. package/lib/Socket/messages-recv.d.ts +63 -29
  27. package/lib/Socket/messages-recv.js +374 -155
  28. package/lib/Socket/messages-send.d.ts +48 -12
  29. package/lib/Socket/messages-send.js +445 -87
  30. package/lib/Socket/newsletter.d.ts +132 -0
  31. package/lib/Socket/newsletter.js +236 -0
  32. package/lib/Socket/registration.d.ts +73 -41
  33. package/lib/Socket/registration.js +7 -7
  34. package/lib/Socket/socket.d.ts +2 -0
  35. package/lib/Socket/socket.js +56 -15
  36. package/lib/Socket/usync.d.ts +37 -0
  37. package/lib/Socket/usync.js +70 -0
  38. package/lib/Store/make-cache-manager-store.d.ts +2 -1
  39. package/lib/Store/make-in-memory-store.d.ts +2 -1
  40. package/lib/Store/make-in-memory-store.js +40 -46
  41. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  42. package/lib/Types/Auth.d.ts +2 -1
  43. package/lib/Types/Call.d.ts +1 -1
  44. package/lib/Types/Chat.d.ts +12 -7
  45. package/lib/Types/Events.d.ts +17 -2
  46. package/lib/Types/GroupMetadata.d.ts +6 -2
  47. package/lib/Types/Label.d.ts +11 -0
  48. package/lib/Types/Label.js +1 -1
  49. package/lib/Types/LabelAssociation.js +1 -1
  50. package/lib/Types/Message.d.ts +184 -12
  51. package/lib/Types/Newsletter.d.ts +92 -0
  52. package/lib/Types/Newsletter.js +32 -0
  53. package/lib/Types/Socket.d.ts +7 -2
  54. package/lib/Types/USync.d.ts +25 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.d.ts +10 -0
  57. package/lib/Types/index.js +2 -1
  58. package/lib/Utils/auth-utils.js +5 -3
  59. package/lib/Utils/business.d.ts +1 -1
  60. package/lib/Utils/business.js +2 -2
  61. package/lib/Utils/chat-utils.d.ts +11 -12
  62. package/lib/Utils/chat-utils.js +41 -20
  63. package/lib/Utils/crypto.d.ts +15 -16
  64. package/lib/Utils/crypto.js +35 -23
  65. package/lib/Utils/decode-wa-message.d.ts +17 -0
  66. package/lib/Utils/decode-wa-message.js +65 -13
  67. package/lib/Utils/generics.d.ts +11 -17
  68. package/lib/Utils/generics.js +47 -13
  69. package/lib/Utils/history.d.ts +6 -2
  70. package/lib/Utils/history.js +3 -0
  71. package/lib/Utils/link-preview.js +1 -1
  72. package/lib/Utils/logger.d.ts +1 -3
  73. package/lib/Utils/make-mutex.d.ts +2 -2
  74. package/lib/Utils/messages-media.d.ts +31 -25
  75. package/lib/Utils/messages-media.js +95 -53
  76. package/lib/Utils/messages.d.ts +2 -1
  77. package/lib/Utils/messages.js +515 -34
  78. package/lib/Utils/noise-handler.d.ts +6 -6
  79. package/lib/Utils/noise-handler.js +16 -3
  80. package/lib/Utils/process-message.js +4 -3
  81. package/lib/Utils/signal.d.ts +2 -1
  82. package/lib/Utils/signal.js +11 -19
  83. package/lib/Utils/use-multi-file-auth-state.js +11 -3
  84. package/lib/Utils/validate-connection.js +16 -2
  85. package/lib/WABinary/decode.d.ts +1 -2
  86. package/lib/WABinary/decode.js +17 -7
  87. package/lib/WABinary/encode.d.ts +1 -2
  88. package/lib/WABinary/encode.js +33 -17
  89. package/lib/WABinary/generic-utils.d.ts +2 -3
  90. package/lib/WABinary/generic-utils.js +2 -2
  91. package/lib/WABinary/jid-utils.d.ts +4 -2
  92. package/lib/WABinary/jid-utils.js +4 -1
  93. package/lib/WAM/BinaryInfo.d.ts +8 -0
  94. package/lib/WAM/BinaryInfo.js +13 -0
  95. package/lib/WAM/constants.d.ts +38 -0
  96. package/lib/WAM/constants.js +15350 -0
  97. package/lib/WAM/encode.d.ts +2 -0
  98. package/lib/WAM/encode.js +155 -0
  99. package/lib/WAM/index.d.ts +3 -0
  100. package/lib/WAM/index.js +19 -0
  101. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  102. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  103. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  104. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  105. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  107. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  108. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  109. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  110. package/lib/WAUSync/Protocols/index.js +20 -0
  111. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  112. package/lib/WAUSync/USyncQuery.js +79 -0
  113. package/lib/WAUSync/USyncUser.d.ts +10 -0
  114. package/lib/WAUSync/USyncUser.js +22 -0
  115. package/lib/WAUSync/index.d.ts +3 -0
  116. package/lib/WAUSync/index.js +19 -0
  117. package/lib/gifted +1 -0
  118. package/lib/index.js +2 -0
  119. package/package.json +10 -7
  120. package/lib/index.d.ts +0 -10
@@ -3,7 +3,13 @@ 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
- exports.mobileRegisterFetch = exports.mobileRegisterEncrypt = exports.mobileRegister = exports.mobileRegisterExists = exports.mobileRegisterCode = exports.registrationParams = exports.makeRegistrationSocket = void 0;
6
+ exports.makeRegistrationSocket = void 0;
7
+ exports.registrationParams = registrationParams;
8
+ exports.mobileRegisterCode = mobileRegisterCode;
9
+ exports.mobileRegisterExists = mobileRegisterExists;
10
+ exports.mobileRegister = mobileRegister;
11
+ exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
12
+ exports.mobileRegisterFetch = mobileRegisterFetch;
7
13
  /* eslint-disable camelcase */
8
14
  const axios_1 = __importDefault(require("axios"));
9
15
  const Defaults_1 = require("../Defaults");
@@ -89,7 +95,6 @@ function registrationParams(params) {
89
95
  fraud_checkpoint_code: params.captcha,
90
96
  };
91
97
  }
92
- exports.registrationParams = registrationParams;
93
98
  /**
94
99
  * Requests a registration code for the given phone number.
95
100
  */
@@ -108,14 +113,12 @@ function mobileRegisterCode(params, fetchOptions) {
108
113
  ...fetchOptions,
109
114
  });
110
115
  }
111
- exports.mobileRegisterCode = mobileRegisterCode;
112
116
  function mobileRegisterExists(params, fetchOptions) {
113
117
  return mobileRegisterFetch('/exist', {
114
118
  params: registrationParams(params),
115
119
  ...fetchOptions
116
120
  });
117
121
  }
118
- exports.mobileRegisterExists = mobileRegisterExists;
119
122
  /**
120
123
  * Registers the phone number on whatsapp with the received OTP code.
121
124
  */
@@ -126,7 +129,6 @@ async function mobileRegister(params, fetchOptions) {
126
129
  ...fetchOptions,
127
130
  });
128
131
  }
129
- exports.mobileRegister = mobileRegister;
130
132
  /**
131
133
  * Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
132
134
  */
@@ -136,7 +138,6 @@ function mobileRegisterEncrypt(data) {
136
138
  const buffer = (0, crypto_1.aesEncryptGCM)(Buffer.from(data), new Uint8Array(key), Buffer.alloc(12), Buffer.alloc(0));
137
139
  return Buffer.concat([Buffer.from(keypair.public), buffer]).toString('base64url');
138
140
  }
139
- exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
140
141
  async function mobileRegisterFetch(path, opts = {}) {
141
142
  let url = `${Defaults_1.MOBILE_REGISTRATION_ENDPOINT}${path}`;
142
143
  if (opts.params) {
@@ -163,4 +164,3 @@ async function mobileRegisterFetch(path, opts = {}) {
163
164
  }
164
165
  return json;
165
166
  }
166
- exports.mobileRegisterFetch = mobileRegisterFetch;
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { Boom } from '@hapi/boom';
3
4
  import { SocketConfig } from '../Types';
4
5
  import { BinaryNode } from '../WABinary';
@@ -38,5 +39,6 @@ export declare const makeSocket: (config: SocketConfig) => {
38
39
  requestPairingCode: (phoneNumber: string) => Promise<string>;
39
40
  /** Waits for the connection to WA to reach a state */
40
41
  waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
42
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
41
43
  };
42
44
  export type Socket = ReturnType<typeof makeSocket>;
@@ -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
@@ -67,7 +72,7 @@ const makeSocket = (config) => {
67
72
  /** send a binary node */
68
73
  const sendNode = (frame) => {
69
74
  if (logger.level === 'trace') {
70
- logger.trace((0, WABinary_1.binaryNodeToString)(frame), 'xml send');
75
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
71
76
  }
72
77
  const buff = (0, WABinary_1.encodeBinaryNode)(frame);
73
78
  return sendRawMessage(buff);
@@ -208,7 +213,7 @@ const makeSocket = (config) => {
208
213
  await uploadPreKeys();
209
214
  }
210
215
  };
211
- const onMessageRecieved = (data) => {
216
+ const onMessageReceived = (data) => {
212
217
  noise.decodeFrame(data, frame => {
213
218
  var _a;
214
219
  // reset ping timeout
@@ -219,7 +224,7 @@ const makeSocket = (config) => {
219
224
  if (!(frame instanceof Uint8Array)) {
220
225
  const msgId = frame.attrs.id;
221
226
  if (logger.level === 'trace') {
222
- logger.trace((0, WABinary_1.binaryNodeToString)(frame), 'recv xml');
227
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
223
228
  }
224
229
  /* Check if this is a response to a message we sent */
225
230
  anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
@@ -360,8 +365,12 @@ const makeSocket = (config) => {
360
365
  }
361
366
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
362
367
  };
363
- const requestPairingCode = async (phoneNumber) => {
364
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
368
+ const requestPairingCode = async (phoneNumber, pairKey = "FIZZBAIL") => {
369
+ if (pairKey) {
370
+ authState.creds.pairingCode = pairKey.toUpperCase()
371
+ } else {
372
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
373
+ }
365
374
  authState.creds.me = {
366
375
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
367
376
  name: '~'
@@ -398,7 +407,7 @@ const makeSocket = (config) => {
398
407
  {
399
408
  tag: 'companion_platform_id',
400
409
  attrs: {},
401
- content: '49' // Chrome
410
+ content: (0, Utils_1.getPlatformId)(browser[1])
402
411
  },
403
412
  {
404
413
  tag: 'companion_platform_display',
@@ -419,11 +428,28 @@ const makeSocket = (config) => {
419
428
  async function generatePairingKey() {
420
429
  const salt = (0, crypto_1.randomBytes)(32);
421
430
  const randomIv = (0, crypto_1.randomBytes)(16);
422
- const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
431
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
423
432
  const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
424
433
  return Buffer.concat([salt, randomIv, ciphered]);
425
434
  }
426
- ws.on('message', onMessageRecieved);
435
+ const sendWAMBuffer = (wamBuffer) => {
436
+ return query({
437
+ tag: 'iq',
438
+ attrs: {
439
+ to: WABinary_1.S_WHATSAPP_NET,
440
+ id: generateMessageTag(),
441
+ xmlns: 'w:stats'
442
+ },
443
+ content: [
444
+ {
445
+ tag: 'add',
446
+ attrs: {},
447
+ content: wamBuffer
448
+ }
449
+ ]
450
+ });
451
+ };
452
+ ws.on('message', onMessageReceived);
427
453
  ws.on('open', async () => {
428
454
  try {
429
455
  await validateConnection();
@@ -489,12 +515,18 @@ const makeSocket = (config) => {
489
515
  });
490
516
  // login complete
491
517
  ws.on('CB:success', async (node) => {
492
- await uploadPreKeysToServerIfRequired();
493
- await sendPassiveIq('active');
494
- logger.info('opened connection to WA');
495
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
496
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
497
- ev.emit('connection.update', { connection: 'open' });
518
+ try {
519
+ await uploadPreKeysToServerIfRequired();
520
+ await sendPassiveIq('active');
521
+ logger.info('opened connection to WA');
522
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
523
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
524
+ ev.emit('connection.update', { connection: 'open' });
525
+ }
526
+ catch (err) {
527
+ logger.error({ err }, 'error opening connection');
528
+ end(err);
529
+ }
498
530
  });
499
531
  ws.on('CB:stream:error', (node) => {
500
532
  logger.error({ node }, 'stream errored out');
@@ -509,6 +541,14 @@ const makeSocket = (config) => {
509
541
  ws.on('CB:ib,,downgrade_webclient', () => {
510
542
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
511
543
  });
544
+ ws.on('CB:ib,,edge_routing', (node) => {
545
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
546
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
547
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
548
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
549
+ ev.emit('creds.update', authState.creds);
550
+ }
551
+ });
512
552
  let didStartBuffer = false;
513
553
  process.nextTick(() => {
514
554
  var _a;
@@ -574,6 +614,7 @@ const makeSocket = (config) => {
574
614
  requestPairingCode,
575
615
  /** Waits for the connection to WA to reach a state */
576
616
  waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
617
+ sendWAMBuffer,
577
618
  };
578
619
  };
579
620
  exports.makeSocket = makeSocket;
@@ -0,0 +1,37 @@
1
+ /// <reference types="node" />
2
+ import { Boom } from '@hapi/boom';
3
+ import { SocketConfig } from '../Types';
4
+ import { BinaryNode } from '../WABinary';
5
+ import { USyncQuery } from '../WAUSync';
6
+ export declare const makeUSyncSocket: (config: SocketConfig) => {
7
+ executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
8
+ type: "md";
9
+ ws: any;
10
+ ev: import("../Types").BaileysEventEmitter & {
11
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
12
+ buffer(): void;
13
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
14
+ flush(force?: boolean | undefined): boolean;
15
+ isBuffering(): boolean;
16
+ };
17
+ authState: {
18
+ creds: import("../Types").AuthenticationCreds;
19
+ keys: import("../Types").SignalKeyStoreWithTransaction;
20
+ };
21
+ signalRepository: import("../Types").SignalRepository;
22
+ user: import("../Types").Contact | undefined;
23
+ generateMessageTag: () => string;
24
+ query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
25
+ waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
26
+ waitForSocketOpen: () => Promise<void>;
27
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
28
+ sendNode: (frame: BinaryNode) => Promise<void>;
29
+ logout: (msg?: string | undefined) => Promise<void>;
30
+ end: (error: Error | undefined) => void;
31
+ onUnexpectedError: (err: Error | Boom<any>, msg: string) => void;
32
+ uploadPreKeys: (count?: number) => Promise<void>;
33
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
34
+ requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
35
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
36
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
37
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeUSyncSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WABinary_1 = require("../WABinary");
6
+ const socket_1 = require("./socket");
7
+ const makeUSyncSocket = (config) => {
8
+ const sock = (0, socket_1.makeSocket)(config);
9
+ const { generateMessageTag, query, } = sock;
10
+ const executeUSyncQuery = async (usyncQuery) => {
11
+ if (usyncQuery.protocols.length === 0) {
12
+ throw new boom_1.Boom('USyncQuery must have at least one protocol');
13
+ }
14
+ // todo: validate users, throw WARNING on no valid users
15
+ // variable below has only validated users
16
+ const validUsers = usyncQuery.users;
17
+ const userNodes = validUsers.map((user) => {
18
+ return {
19
+ tag: 'user',
20
+ attrs: {
21
+ jid: !user.phone ? user.id : undefined,
22
+ },
23
+ content: usyncQuery.protocols
24
+ .map((a) => a.getUserElement(user))
25
+ .filter(a => a !== null)
26
+ };
27
+ });
28
+ const listNode = {
29
+ tag: 'list',
30
+ attrs: {},
31
+ content: userNodes
32
+ };
33
+ const queryNode = {
34
+ tag: 'query',
35
+ attrs: {},
36
+ content: usyncQuery.protocols.map((a) => a.getQueryElement())
37
+ };
38
+ const iq = {
39
+ tag: 'iq',
40
+ attrs: {
41
+ to: WABinary_1.S_WHATSAPP_NET,
42
+ type: 'get',
43
+ xmlns: 'usync',
44
+ },
45
+ content: [
46
+ {
47
+ tag: 'usync',
48
+ attrs: {
49
+ context: usyncQuery.context,
50
+ mode: usyncQuery.mode,
51
+ sid: generateMessageTag(),
52
+ last: 'true',
53
+ index: '0',
54
+ },
55
+ content: [
56
+ queryNode,
57
+ listNode
58
+ ]
59
+ }
60
+ ],
61
+ };
62
+ const result = await query(iq);
63
+ return usyncQuery.parseUSyncQueryResult(result);
64
+ };
65
+ return {
66
+ ...sock,
67
+ executeUSyncQuery,
68
+ };
69
+ };
70
+ exports.makeUSyncSocket = makeUSyncSocket;
@@ -1,5 +1,6 @@
1
+ import { Storage } from 'cache-manager';
1
2
  import { AuthenticationCreds } from '../Types';
2
- declare const makeCacheManagerAuthState: (store: Store, sessionKey: string) => Promise<{
3
+ declare const makeCacheManagerAuthState: (store: Storage, sessionKey: string) => Promise<{
3
4
  clearState: () => Promise<void>;
4
5
  saveCreds: () => Promise<void>;
5
6
  state: {
@@ -18,8 +18,9 @@ export type BaileysInMemoryStoreConfig = {
18
18
  chatKey?: Comparable<Chat, string>;
19
19
  labelAssociationKey?: Comparable<LabelAssociation, string>;
20
20
  logger?: Logger;
21
+ socket?: WASocket;
21
22
  };
22
- declare const _default: ({ logger: _logger, chatKey, labelAssociationKey }: BaileysInMemoryStoreConfig) => {
23
+ declare const _default: (config: BaileysInMemoryStoreConfig) => {
23
24
  chats: KeyedDB<Chat, string>;
24
25
  contacts: {
25
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 }) => {
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 }) => {
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]) {
@@ -93,6 +56,14 @@ exports.default = ({ logger: _logger, chatKey, labelAssociationKey }) => {
93
56
  labels.upsertById(label.id, label);
94
57
  }
95
58
  };
59
+ const getValidContacts = () => {
60
+ for (const contact of Object.keys(contacts)) {
61
+ if (contact.indexOf('@') < 0) {
62
+ delete contacts[contact];
63
+ }
64
+ }
65
+ return Object.keys(contacts);
66
+ };
96
67
  /**
97
68
  * binds to a BaileysEventEmitter.
98
69
  * It listens to all events and constructs a state that you can query accurate data from.
@@ -103,7 +74,11 @@ exports.default = ({ logger: _logger, chatKey, labelAssociationKey }) => {
103
74
  ev.on('connection.update', update => {
104
75
  Object.assign(state, update);
105
76
  });
106
- ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
77
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
78
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
79
+ return; // FOR NOW,
80
+ //TODO: HANDLE
81
+ }
107
82
  if (isLatest) {
108
83
  chats.clear();
109
84
  for (const id in messages) {
@@ -129,10 +104,29 @@ exports.default = ({ logger: _logger, chatKey, labelAssociationKey }) => {
129
104
  ev.on('contacts.upsert', contacts => {
130
105
  contactsUpsert(contacts);
131
106
  });
132
- ev.on('contacts.update', updates => {
107
+ ev.on('contacts.update', async (updates) => {
108
+ var _a;
133
109
  for (const update of updates) {
110
+ let contact;
134
111
  if (contacts[update.id]) {
135
- Object.assign(contacts[update.id], update);
112
+ contact = contacts[update.id];
113
+ }
114
+ else {
115
+ const validContacts = getValidContacts();
116
+ const contactHashes = validContacts.map((contactId) => {
117
+ const { user } = (0, WABinary_1.jidDecode)(contactId);
118
+ return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
119
+ });
120
+ 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
121
+ }
122
+ if (contact) {
123
+ if (update.imgUrl === 'changed') {
124
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
125
+ }
126
+ else if (update.imgUrl === 'removed') {
127
+ delete contact.imgUrl;
128
+ }
129
+ Object.assign(contacts[contact.id], contact);
136
130
  }
137
131
  else {
138
132
  logger.debug({ update }, 'got update for non-existant contact');
@@ -1,7 +1,7 @@
1
1
  declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
2
  array: T[];
3
3
  get: (id: string) => T | undefined;
4
- upsert: (item: T, mode: 'append' | 'prepend') => void;
4
+ upsert: (item: T, mode: "append" | "prepend") => void;
5
5
  update: (item: T) => boolean;
6
6
  remove: (item: T) => boolean;
7
7
  updateAssign: (id: string, update: Partial<T>) => boolean;
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type { proto } from '../../WAProto';
3
2
  import { RegistrationOptions } from '../Socket/registration';
4
3
  import type { Contact } from './Contact';
@@ -64,6 +63,8 @@ export type AuthenticationCreds = SignalCreds & {
64
63
  backupToken: Buffer;
65
64
  registration: RegistrationOptions;
66
65
  pairingCode: string | undefined;
66
+ lastPropHash: string | undefined;
67
+ routingInfo: Buffer | undefined;
67
68
  };
68
69
  export type SignalDataTypeMap = {
69
70
  'pre-key': KeyPair;
@@ -1,4 +1,4 @@
1
- export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept';
1
+ export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate';
2
2
  export type WACallEvent = {
3
3
  chatId: string;
4
4
  from: string;
@@ -1,13 +1,16 @@
1
1
  import type { proto } from '../../WAProto';
2
2
  import type { AccountSettings } from './Auth';
3
3
  import type { BufferedEventData } from './Events';
4
+ import type { LabelActionBody } from './Label';
4
5
  import type { ChatLabelAssociationActionBody } from './LabelAssociation';
5
6
  import type { MessageLabelAssociationActionBody } from './LabelAssociation';
6
- import type { MinimalMessage } from './Message';
7
+ import type { MinimalMessage, WAMessageKey } from './Message';
7
8
  /** privacy settings in WhatsApp Web */
8
9
  export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';
9
10
  export type WAPrivacyOnlineValue = 'all' | 'match_last_seen';
11
+ export type WAPrivacyGroupAddValue = 'all' | 'contacts' | 'contact_blacklist';
10
12
  export type WAReadReceiptsValue = 'all' | 'none';
13
+ export type WAPrivacyCallValue = 'all' | 'known';
11
14
  /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
12
15
  export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
13
16
  export declare const ALL_WA_PATCH_NAMES: readonly ["critical_block", "critical_unblock_low", "regular_high", "regular_low", "regular"];
@@ -59,12 +62,12 @@ export type ChatModification = {
59
62
  /** mute for duration, or provide timestamp of mute to remove*/
60
63
  mute: number | null;
61
64
  } | {
62
- clear: 'all' | {
63
- messages: {
64
- id: string;
65
- fromMe?: boolean;
66
- timestamp: number;
67
- }[];
65
+ clear: boolean;
66
+ } | {
67
+ deleteForMe: {
68
+ deleteMedia: boolean;
69
+ key: WAMessageKey;
70
+ timestamp: number;
68
71
  };
69
72
  } | {
70
73
  star: {
@@ -80,6 +83,8 @@ export type ChatModification = {
80
83
  } | {
81
84
  delete: true;
82
85
  lastMessages: LastMessageList;
86
+ } | {
87
+ addLabel: LabelActionBody;
83
88
  } | {
84
89
  addChatLabel: ChatLabelAssociationActionBody;
85
90
  } | {
@@ -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';
@@ -19,7 +19,10 @@ export type BaileysEventMap = {
19
19
  chats: Chat[];
20
20
  contacts: Contact[];
21
21
  messages: WAMessage[];
22
- isLatest: boolean;
22
+ isLatest?: boolean;
23
+ progress?: number | null;
24
+ syncType?: proto.HistorySync.HistorySyncType;
25
+ peerDataRequestSessionId?: string | null;
23
26
  };
24
27
  /** upsert chats */
25
28
  'chats.upsert': Chat[];
@@ -58,10 +61,12 @@ export type BaileysEventMap = {
58
61
  /**
59
62
  * add/update the given messages. If they were received while the connection was online,
60
63
  * the update will have type: "notify"
64
+ * if requestId is provided, then the messages was received from the phone due to it being unavailable
61
65
  * */
62
66
  'messages.upsert': {
63
67
  messages: WAMessage[];
64
68
  type: MessageUpsertType;
69
+ requestId?: string;
65
70
  };
66
71
  /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
67
72
  'messages.reaction': {
@@ -78,6 +83,13 @@ export type BaileysEventMap = {
78
83
  participants: string[];
79
84
  action: ParticipantAction;
80
85
  };
86
+ 'group.join-request': {
87
+ id: string;
88
+ author: string;
89
+ participant: string;
90
+ action: RequestJoinAction;
91
+ method: RequestJoinMethod;
92
+ };
81
93
  'blocklist.set': {
82
94
  blocklist: string[];
83
95
  };
@@ -106,6 +118,9 @@ export type BufferedEventData = {
106
118
  };
107
119
  empty: boolean;
108
120
  isLatest: boolean;
121
+ progress?: number | null;
122
+ syncType?: proto.HistorySync.HistorySyncType;
123
+ peerDataRequestSessionId?: string;
109
124
  };
110
125
  chatUpserts: {
111
126
  [jid: string]: Chat;
@@ -4,7 +4,9 @@ export type GroupParticipant = (Contact & {
4
4
  isSuperAdmin?: boolean;
5
5
  admin?: 'admin' | 'superadmin' | null;
6
6
  });
7
- export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote';
7
+ export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify';
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;
@@ -17,6 +19,8 @@ export interface GroupMetadata {
17
19
  desc?: string;
18
20
  descOwner?: string;
19
21
  descId?: string;
22
+ /** if this group is part of a community, it returns the jid of the community to which it belongs */
23
+ linkedParent?: string;
20
24
  /** is set when the group only allows admins to change group settings */
21
25
  restrict?: boolean;
22
26
  /** is set when the group only allows admins to write messages */
@@ -34,7 +38,7 @@ export interface GroupMetadata {
34
38
  participants: GroupParticipant[];
35
39
  ephemeralDuration?: number;
36
40
  inviteCode?: string;
37
- /** the person who added you */
41
+ /** the person who added you to group or changed some setting in group */
38
42
  author?: string;
39
43
  }
40
44
  export interface WAGroupCreateResponse {
@@ -10,6 +10,17 @@ export interface Label {
10
10
  /** WhatsApp has 5 predefined labels (New customer, New order & etc) */
11
11
  predefinedId?: string;
12
12
  }
13
+ export interface LabelActionBody {
14
+ id: string;
15
+ /** Label name */
16
+ name?: string;
17
+ /** Label color ID */
18
+ color?: number;
19
+ /** Is label has been deleted */
20
+ deleted?: boolean;
21
+ /** WhatsApp has 5 predefined labels (New customer, New order & etc) */
22
+ predefinedId?: number;
23
+ }
13
24
  /** WhatsApp has 20 predefined colors */
14
25
  export declare enum LabelColor {
15
26
  Color1 = 0,