@queenanya/baileys 6.9.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +56 -13
  2. package/lib/Defaults/baileys-version.json +1 -1
  3. package/lib/Defaults/index.js +5 -2
  4. package/lib/Socket/business.d.ts +46 -8
  5. package/lib/Socket/business.js +1 -0
  6. package/lib/Socket/chats.d.ts +10 -2
  7. package/lib/Socket/chats.js +42 -3
  8. package/lib/Socket/groups.d.ts +17 -3
  9. package/lib/Socket/groups.js +12 -1
  10. package/lib/Socket/index.d.ts +46 -8
  11. package/lib/Socket/messages-recv.d.ts +45 -9
  12. package/lib/Socket/messages-recv.js +184 -22
  13. package/lib/Socket/messages-send.d.ts +40 -6
  14. package/lib/Socket/messages-send.js +153 -37
  15. package/lib/Socket/newsletter.d.ts +140 -0
  16. package/lib/Socket/newsletter.js +249 -0
  17. package/lib/Socket/registration.d.ts +46 -11
  18. package/lib/Socket/socket.js +18 -4
  19. package/lib/Store/make-in-memory-store.d.ts +2 -2
  20. package/lib/Store/make-in-memory-store.js +11 -44
  21. package/lib/Types/Auth.d.ts +1 -0
  22. package/lib/Types/Chat.d.ts +5 -0
  23. package/lib/Types/Events.d.ts +40 -2
  24. package/lib/Types/GroupMetadata.d.ts +3 -1
  25. package/lib/Types/Label.d.ts +11 -0
  26. package/lib/Types/Message.d.ts +39 -27
  27. package/lib/Types/Newsletter.d.ts +79 -0
  28. package/lib/Types/Newsletter.js +18 -0
  29. package/lib/Types/Socket.d.ts +7 -0
  30. package/lib/Types/index.d.ts +9 -0
  31. package/lib/Types/index.js +1 -0
  32. package/lib/Utils/auth-utils.js +1 -0
  33. package/lib/Utils/chat-utils.js +16 -0
  34. package/lib/Utils/crypto.d.ts +1 -1
  35. package/lib/Utils/crypto.js +4 -2
  36. package/lib/Utils/decode-wa-message.d.ts +1 -0
  37. package/lib/Utils/decode-wa-message.js +50 -22
  38. package/lib/Utils/generics.d.ts +30 -10
  39. package/lib/Utils/generics.js +82 -10
  40. package/lib/Utils/history.d.ts +4 -0
  41. package/lib/Utils/history.js +3 -0
  42. package/lib/Utils/logger.d.ts +1 -3
  43. package/lib/Utils/messages-media.d.ts +10 -1
  44. package/lib/Utils/messages-media.js +61 -18
  45. package/lib/Utils/messages.d.ts +2 -1
  46. package/lib/Utils/messages.js +77 -76
  47. package/lib/Utils/noise-handler.d.ts +3 -2
  48. package/lib/Utils/noise-handler.js +18 -5
  49. package/lib/Utils/process-message.d.ts +3 -2
  50. package/lib/Utils/process-message.js +53 -21
  51. package/lib/Utils/signal.js +21 -16
  52. package/lib/Utils/use-multi-file-auth-state.js +16 -3
  53. package/lib/WABinary/decode.d.ts +2 -2
  54. package/lib/WABinary/decode.js +6 -4
  55. package/lib/WABinary/encode.d.ts +1 -2
  56. package/lib/WABinary/encode.js +1 -1
  57. package/lib/WABinary/jid-utils.d.ts +3 -1
  58. package/lib/WABinary/jid-utils.js +4 -1
  59. package/package.json +32 -27
@@ -2,22 +2,48 @@
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { proto } from '../../WAProto';
4
4
  import { AnyMessageContent, MediaConnInfo, MessageReceiptType, MessageRelayOptions, MiscMessageGenerationOptions, SocketConfig, WAMessageKey } from '../Types';
5
- import { BinaryNode } from '../WABinary';
5
+ import { BinaryNode, JidWithDevice } from '../WABinary';
6
6
  export declare const makeMessagesSocket: (config: SocketConfig) => {
7
7
  getPrivacyTokens: (jids: string[]) => Promise<BinaryNode>;
8
8
  assertSessions: (jids: string[], force: boolean) => Promise<boolean>;
9
- relayMessage: (jid: string, message: proto.IMessage, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, cachedGroupMetadata, statusJidList }: MessageRelayOptions) => Promise<string>;
9
+ relayMessage: (jid: string, message: proto.IMessage, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }: MessageRelayOptions) => Promise<string>;
10
10
  sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: MessageReceiptType) => Promise<void>;
11
11
  sendReceipts: (keys: WAMessageKey[], type: MessageReceiptType) => Promise<void>;
12
- getButtonArgs: (message: proto.IMessage) => BinaryNode['attrs'];
13
12
  readMessages: (keys: WAMessageKey[]) => Promise<void>;
14
13
  refreshMediaConn: (forceGet?: boolean) => Promise<MediaConnInfo>;
15
14
  waUploadToServer: import("../Types").WAMediaUploadFunction;
16
15
  fetchPrivacySettings: (force?: boolean) => Promise<{
17
16
  [_: string]: string;
18
17
  }>;
18
+ sendPeerDataOperationMessage: (pdoMessage: proto.Message.IPeerDataOperationRequestMessage) => Promise<string>;
19
+ createParticipantNodes: (jids: string[], message: proto.IMessage, extraAttrs?: BinaryNode['attrs']) => Promise<{
20
+ nodes: BinaryNode[];
21
+ shouldIncludeDeviceIdentity: boolean;
22
+ }>;
23
+ getUSyncDevices: (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => Promise<JidWithDevice[]>;
19
24
  updateMediaMessage: (message: proto.IWebMessageInfo) => Promise<proto.IWebMessageInfo>;
20
25
  sendMessage: (jid: string, content: AnyMessageContent, options?: MiscMessageGenerationOptions) => Promise<proto.WebMessageInfo | undefined>;
26
+ subscribeNewsletterUpdates: (jid: string) => Promise<{
27
+ duration: string;
28
+ }>;
29
+ newsletterReactionMode: (jid: string, mode: import("../Types").NewsletterReactionMode) => Promise<void>;
30
+ newsletterUpdateDescription: (jid: string, description?: string | undefined) => Promise<void>;
31
+ newsletterUpdateName: (jid: string, name: string) => Promise<void>;
32
+ newsletterUpdatePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
33
+ newsletterRemovePicture: (jid: string) => Promise<void>;
34
+ newsletterUnfollow: (jid: string) => Promise<void>;
35
+ newsletterFollow: (jid: string) => Promise<void>;
36
+ newsletterUnmute: (jid: string) => Promise<void>;
37
+ newsletterMute: (jid: string) => Promise<void>;
38
+ newsletterCreate: (name: string, description: string) => Promise<import("../Types").NewsletterMetadata>;
39
+ newsletterMetadata: (type: "invite" | "jid", key: string, role?: import("../Types").NewsletterViewRole | undefined) => Promise<import("../Types").NewsletterMetadata>;
40
+ newsletterAdminCount: (jid: string) => Promise<number>;
41
+ newsletterChangeOwner: (jid: string, user: string) => Promise<void>;
42
+ newsletterDemote: (jid: string, user: string) => Promise<void>;
43
+ newsletterDelete: (jid: string) => Promise<void>;
44
+ newsletterReactMessage: (jid: string, server_id: string, code?: string | undefined) => Promise<void>;
45
+ newsletterFetchMessages: (type: "invite" | "jid", key: string, count: number, after?: number | undefined) => Promise<import("../Types").NewsletterFetchedUpdate[]>;
46
+ newsletterFetchUpdates: (jid: string, count: number, after?: number | undefined, since?: number | undefined) => Promise<import("../Types").NewsletterFetchedUpdate[]>;
21
47
  groupMetadata: (jid: string) => Promise<import("../Types").GroupMetadata>;
22
48
  groupCreate: (subject: string, participants: string[]) => Promise<import("../Types").GroupMetadata>;
23
49
  groupLeave: (id: string) => Promise<void>;
@@ -27,7 +53,7 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
27
53
  }[]>;
28
54
  groupRequestParticipantsUpdate: (jid: string, participants: string[], action: "reject" | "approve") => Promise<{
29
55
  status: string;
30
- jid: string; /** Bulk read messages. Keys can be from different chats & participants */
56
+ jid: string;
31
57
  }[]>;
32
58
  groupParticipantsUpdate: (jid: string, participants: string[], action: import("../Types").ParticipantAction) => Promise<{
33
59
  status: string;
@@ -38,7 +64,8 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
38
64
  groupInviteCode: (jid: string) => Promise<string | undefined>;
39
65
  groupRevokeInvite: (jid: string) => Promise<string | undefined>;
40
66
  groupAcceptInvite: (code: string) => Promise<string | undefined>;
41
- groupAcceptInviteV4: (key: string | proto.IMessageKey, inviteMessage: proto.Message.IGroupInviteMessage) => Promise<string>;
67
+ groupRevokeInviteV4: (groupJid: string, invitedJid: string) => Promise<boolean>;
68
+ groupAcceptInviteV4: (key: string | WAMessageKey, inviteMessage: proto.Message.IGroupInviteMessage) => Promise<string>;
42
69
  groupGetInviteInfo: (code: string) => Promise<import("../Types").GroupMetadata>;
43
70
  groupToggleEphemeral: (jid: string, ephemeralExpiration: number) => Promise<void>;
44
71
  groupSettingUpdate: (jid: string, setting: "announcement" | "locked" | "not_announcement" | "unlocked") => Promise<void>;
@@ -60,6 +87,11 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
60
87
  jid: string;
61
88
  }[]>;
62
89
  fetchBlocklist: () => Promise<string[]>;
90
+ fetchDisappearingDuration: (...jids: string[]) => Promise<{
91
+ user: string;
92
+ duration: number;
93
+ setAt: Date;
94
+ }[]>;
63
95
  fetchStatus: (jid: string) => Promise<{
64
96
  status: string | undefined;
65
97
  setAt: Date;
@@ -69,17 +101,19 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
69
101
  updateProfileStatus: (status: string) => Promise<void>;
70
102
  updateProfileName: (name: string) => Promise<void>;
71
103
  updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;
104
+ updateCallPrivacy: (value: import("../Types").WAPrivacyCallValue) => Promise<void>;
72
105
  updateLastSeenPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
73
106
  updateOnlinePrivacy: (value: import("../Types").WAPrivacyOnlineValue) => Promise<void>;
74
107
  updateProfilePicturePrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
75
108
  updateStatusPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
76
109
  updateReadReceiptsPrivacy: (value: import("../Types").WAReadReceiptsValue) => Promise<void>;
77
- updateGroupsAddPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
110
+ updateGroupsAddPrivacy: (value: import("../Types").WAPrivacyGroupAddValue) => Promise<void>;
78
111
  updateDefaultDisappearingMode: (duration: number) => Promise<void>;
79
112
  getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;
80
113
  resyncAppState: (collections: readonly ("critical_block" | "critical_unblock_low" | "regular_high" | "regular_low" | "regular")[], isInitialSync: boolean) => Promise<void>;
81
114
  chatModify: (mod: import("../Types").ChatModification, jid: string) => Promise<void>;
82
115
  cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
116
+ addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
83
117
  addChatLabel: (jid: string, labelId: string) => Promise<void>;
84
118
  removeChatLabel: (jid: string, labelId: string) => Promise<void>;
85
119
  addMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
@@ -11,12 +11,12 @@ const Defaults_1 = require("../Defaults");
11
11
  const Utils_1 = require("../Utils");
12
12
  const link_preview_1 = require("../Utils/link-preview");
13
13
  const WABinary_1 = require("../WABinary");
14
- const groups_1 = require("./groups");
14
+ const newsletter_1 = require("./newsletter");
15
15
  var ListType = WAProto_1.proto.Message.ListMessage.ListType;
16
16
  const makeMessagesSocket = (config) => {
17
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
18
- const sock = (0, groups_1.makeGroupsSocket)(config);
19
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral } = sock;
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
18
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
19
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
20
20
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
21
21
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
22
22
  useClones: false
@@ -77,7 +77,7 @@ const makeMessagesSocket = (config) => {
77
77
  }
78
78
  }
79
79
  if (type) {
80
- node.attrs.type = type;
80
+ node.attrs.type = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : type;
81
81
  }
82
82
  const remainingMessageIds = messageIds.slice(1);
83
83
  if (remainingMessageIds.length) {
@@ -130,6 +130,9 @@ const makeMessagesSocket = (config) => {
130
130
  users.push({ tag: 'user', attrs: { jid } });
131
131
  }
132
132
  }
133
+ if (!users.length) {
134
+ return deviceResults;
135
+ }
133
136
  const iq = {
134
137
  tag: 'iq',
135
138
  attrs: {
@@ -219,6 +222,28 @@ const makeMessagesSocket = (config) => {
219
222
  }
220
223
  return didFetchNewSession;
221
224
  };
225
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
226
+ var _a;
227
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
228
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
229
+ throw new boom_1.Boom('Not authenticated');
230
+ }
231
+ const protocolMessage = {
232
+ protocolMessage: {
233
+ peerDataOperationRequestMessage: pdoMessage,
234
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
235
+ }
236
+ };
237
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
238
+ const msgId = await relayMessage(meJid, protocolMessage, {
239
+ additionalAttributes: {
240
+ category: 'peer',
241
+ // eslint-disable-next-line camelcase
242
+ push_priority: 'high_force',
243
+ },
244
+ });
245
+ return msgId;
246
+ };
222
247
  const createParticipantNodes = async (jids, message, extraAttrs) => {
223
248
  const patched = await patchMessageBeforeSending(message, jids);
224
249
  const bytes = (0, Utils_1.encodeWAMessage)(patched);
@@ -246,18 +271,21 @@ const makeMessagesSocket = (config) => {
246
271
  }));
247
272
  return { nodes, shouldIncludeDeviceIdentity };
248
273
  };
249
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, useUserDevicesCache, cachedGroupMetadata, statusJidList }) => {
274
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
275
+ var _a;
250
276
  const meId = authState.creds.me.id;
251
277
  let shouldIncludeDeviceIdentity = false;
252
278
  const { user, server } = (0, WABinary_1.jidDecode)(jid);
253
279
  const statusJid = 'status@broadcast';
254
280
  const isGroup = server === 'g.us';
281
+ const isNewsletter = server == 'newsletter';
255
282
  const isStatus = jid === statusJid;
256
283
  const isLid = server === 'lid';
257
- msgId = msgId || (0, Utils_1.generateMessageID)();
284
+ msgId = msgId || (0, Utils_1.generateMessageIDV3)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
258
285
  useUserDevicesCache = useUserDevicesCache !== false;
286
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
259
287
  const participants = [];
260
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid;
288
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
261
289
  const binaryNodeContent = [];
262
290
  const devices = [];
263
291
  const meMsg = {
@@ -266,6 +294,7 @@ const makeMessagesSocket = (config) => {
266
294
  message
267
295
  }
268
296
  };
297
+ const extraAttrs = {};
269
298
  if (participant) {
270
299
  // when the retry request is not for a group
271
300
  // only send to the specific device that asked for a retry
@@ -277,16 +306,22 @@ const makeMessagesSocket = (config) => {
277
306
  devices.push({ user, device });
278
307
  }
279
308
  await authState.keys.transaction(async () => {
280
- var _a, _b;
309
+ var _a, _b, _c, _d, _e;
281
310
  const mediaType = getMediaType(message);
311
+ if (mediaType) {
312
+ extraAttrs['mediatype'] = mediaType;
313
+ }
314
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
315
+ extraAttrs['decrypt-fail'] = 'hide';
316
+ }
282
317
  if (isGroup || isStatus) {
283
318
  const [groupData, senderKeyMap] = await Promise.all([
284
319
  (async () => {
285
- let groupData = cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
286
- if (groupData) {
320
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
321
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
287
322
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
288
323
  }
289
- if (!groupData && !isStatus) {
324
+ else if (!isStatus) {
290
325
  groupData = await groupMetadata(jid);
291
326
  }
292
327
  return groupData;
@@ -335,7 +370,7 @@ const makeMessagesSocket = (config) => {
335
370
  }
336
371
  };
337
372
  await assertSessions(senderKeyJids, false);
338
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { mediatype: mediaType } : undefined);
373
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
339
374
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
340
375
  participants.push(...result.nodes);
341
376
  }
@@ -346,23 +381,34 @@ const makeMessagesSocket = (config) => {
346
381
  });
347
382
  await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
348
383
  }
384
+ else if (isNewsletter) {
385
+ const patched = await patchMessageBeforeSending(message, []);
386
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
387
+ binaryNodeContent.push({
388
+ tag: 'plaintext',
389
+ attrs: {},
390
+ content: bytes
391
+ });
392
+ }
349
393
  else {
350
394
  const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
351
395
  if (!participant) {
352
396
  devices.push({ user });
353
397
  // do not send message to self if the device is 0 (mobile)
354
- if (meDevice !== undefined && meDevice !== 0) {
355
- devices.push({ user: meUser });
398
+ if (!((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer' && user === meUser)) {
399
+ if (meDevice !== undefined && meDevice !== 0) {
400
+ devices.push({ user: meUser });
401
+ }
402
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
403
+ devices.push(...additionalDevices);
356
404
  }
357
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
358
- devices.push(...additionalDevices);
359
405
  }
360
406
  const allJids = [];
361
407
  const meJids = [];
362
408
  const otherJids = [];
363
409
  for (const { user, device } of devices) {
364
410
  const isMe = user === meUser;
365
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_b = (_a = authState.creds) === null || _a === void 0 ? void 0 : _a.me) === null || _b === void 0 ? void 0 : _b.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
411
+ const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_c = (_b = authState.creds) === null || _b === void 0 ? void 0 : _b.me) === null || _c === void 0 ? void 0 : _c.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
366
412
  if (isMe) {
367
413
  meJids.push(jid);
368
414
  }
@@ -373,19 +419,27 @@ const makeMessagesSocket = (config) => {
373
419
  }
374
420
  await assertSessions(allJids, false);
375
421
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
376
- createParticipantNodes(meJids, meMsg, mediaType ? { mediatype: mediaType } : undefined),
377
- createParticipantNodes(otherJids, message, mediaType ? { mediatype: mediaType } : undefined)
422
+ createParticipantNodes(meJids, meMsg, extraAttrs),
423
+ createParticipantNodes(otherJids, message, extraAttrs)
378
424
  ]);
379
425
  participants.push(...meNodes);
380
426
  participants.push(...otherNodes);
381
427
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
382
428
  }
383
429
  if (participants.length) {
384
- binaryNodeContent.push({
385
- tag: 'participants',
386
- attrs: {},
387
- content: participants
388
- });
430
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
431
+ const peerNode = (_e = (_d = participants[0]) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e[0];
432
+ if (peerNode) {
433
+ binaryNodeContent.push(peerNode); // push only enc
434
+ }
435
+ }
436
+ else {
437
+ binaryNodeContent.push({
438
+ tag: 'participants',
439
+ attrs: {},
440
+ content: participants
441
+ });
442
+ }
389
443
  }
390
444
  const stanza = {
391
445
  tag: 'message',
@@ -423,25 +477,60 @@ const makeMessagesSocket = (config) => {
423
477
  });
424
478
  logger.debug({ jid }, 'adding device identity');
425
479
  }
426
- const buttonType = getButtonType(message);
427
- if (buttonType) {
428
- stanza.content.push({
480
+ if (additionalNodes && additionalNodes.length > 0) {
481
+ stanza.content.push(...additionalNodes);
482
+ }
483
+ /**
484
+ const buttonType = getButtonType(message)
485
+ if(buttonType) {
486
+ (stanza.content as BinaryNode[]).push({
429
487
  tag: 'biz',
430
- attrs: {},
488
+ attrs: { },
431
489
  content: [
432
490
  {
433
491
  tag: buttonType,
434
492
  attrs: getButtonArgs(message),
435
493
  }
436
494
  ]
437
- });
438
- logger.debug({ jid }, 'adding business node');
439
- }
495
+ })
496
+
497
+ logger.debug({ jid }, 'adding business node')
498
+ }
499
+ */
440
500
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
441
501
  await sendNode(stanza);
442
502
  });
443
503
  return msgId;
444
504
  };
505
+ const getTypeMessage = (msg) => {
506
+ if (msg.viewOnceMessage) {
507
+ return getTypeMessage(msg.viewOnceMessage.message);
508
+ }
509
+ else if (msg.viewOnceMessageV2) {
510
+ return getTypeMessage(msg.viewOnceMessageV2.message);
511
+ }
512
+ else if (msg.viewOnceMessageV2Extension) {
513
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
514
+ }
515
+ else if (msg.ephemeralMessage) {
516
+ return getTypeMessage(msg.ephemeralMessage.message);
517
+ }
518
+ else if (msg.documentWithCaptionMessage) {
519
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
520
+ }
521
+ else if (msg.reactionMessage) {
522
+ return 'reaction';
523
+ }
524
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
525
+ return 'reaction';
526
+ }
527
+ else if (getMediaType(msg)) {
528
+ return 'media';
529
+ }
530
+ else {
531
+ return 'text';
532
+ }
533
+ };
445
534
  const getMediaType = (message) => {
446
535
  if (message.imageMessage) {
447
536
  return 'image';
@@ -485,6 +574,9 @@ const makeMessagesSocket = (config) => {
485
574
  else if (message.interactiveResponseMessage) {
486
575
  return 'native_flow_response';
487
576
  }
577
+ else if (message.groupInviteMessage) {
578
+ return 'url';
579
+ }
488
580
  };
489
581
  const getButtonType = (message) => {
490
582
  if (message.buttonsMessage) {
@@ -554,11 +646,14 @@ const makeMessagesSocket = (config) => {
554
646
  relayMessage,
555
647
  sendReceipt,
556
648
  sendReceipts,
557
- getButtonArgs,
649
+ // getButtonArgs,
558
650
  readMessages,
559
651
  refreshMediaConn,
560
652
  waUploadToServer,
561
653
  fetchPrivacySettings,
654
+ sendPeerDataOperationMessage,
655
+ createParticipantNodes,
656
+ getUSyncDevices,
562
657
  updateMediaMessage: async (message) => {
563
658
  const content = (0, Utils_1.assertMediaContent)(message.message);
564
659
  const mediaKey = content.mediaKey;
@@ -601,7 +696,7 @@ const makeMessagesSocket = (config) => {
601
696
  return message;
602
697
  },
603
698
  sendMessage: async (jid, content, options = {}) => {
604
- var _a, _b;
699
+ var _a, _b, _c;
605
700
  const userJid = authState.creds.me.id;
606
701
  if (typeof content === 'object' &&
607
702
  'disappearingMessagesInChat' in content &&
@@ -614,6 +709,7 @@ const makeMessagesSocket = (config) => {
614
709
  await groupToggleEphemeral(jid, value);
615
710
  }
616
711
  else {
712
+ let mediaHandle;
617
713
  const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
618
714
  logger,
619
715
  userJid,
@@ -628,18 +724,29 @@ const makeMessagesSocket = (config) => {
628
724
  ? waUploadToServer
629
725
  : undefined
630
726
  }),
727
+ //TODO: CACHE
728
+ getProfilePicUrl: sock.profilePictureUrl,
729
+ upload: async (readStream, opts) => {
730
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
731
+ mediaHandle = up.handle;
732
+ return up;
733
+ },
734
+ /**
631
735
  upload: waUploadToServer,
736
+ */
632
737
  mediaCache: config.mediaCache,
633
738
  options: config.options,
739
+ messageId: (0, Utils_1.generateMessageIDV3)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
634
740
  ...options,
635
741
  });
636
742
  const isDeleteMsg = 'delete' in content && !!content.delete;
637
743
  const isEditMsg = 'edit' in content && !!content.edit;
744
+ const isPinMsg = 'pin' in content && !!content.pin;
638
745
  const additionalAttributes = {};
639
746
  // required for delete
640
747
  if (isDeleteMsg) {
641
748
  // if the chat is a group, and I am not the author, then delete the message as an admin
642
- if ((0, WABinary_1.isJidGroup)((_a = content.delete) === null || _a === void 0 ? void 0 : _a.remoteJid) && !((_b = content.delete) === null || _b === void 0 ? void 0 : _b.fromMe)) {
749
+ if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsletter)(jid)) {
643
750
  additionalAttributes.edit = '8';
644
751
  }
645
752
  else {
@@ -647,9 +754,18 @@ const makeMessagesSocket = (config) => {
647
754
  }
648
755
  }
649
756
  else if (isEditMsg) {
650
- additionalAttributes.edit = '1';
757
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
758
+ }
759
+ else if (isPinMsg) {
760
+ additionalAttributes.edit = '2';
761
+ }
762
+ if (mediaHandle) {
763
+ additionalAttributes['media_id'] = mediaHandle;
764
+ }
765
+ if ('cachedGroupMetadata' in options) {
766
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
651
767
  }
652
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList });
768
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList });
653
769
  if (config.emitOwnEvents) {
654
770
  process.nextTick(() => {
655
771
  processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
@@ -0,0 +1,140 @@
1
+ /// <reference types="node" />
2
+ import { SocketConfig, WAMediaUpload, NewsletterMetadata, NewsletterReactionMode, NewsletterViewRole, NewsletterFetchedUpdate } from '../Types';
3
+ import { BinaryNode } from '../WABinary';
4
+ export declare const makeNewsletterSocket: (config: SocketConfig) => {
5
+ subscribeNewsletterUpdates: (jid: string) => Promise<{
6
+ duration: string;
7
+ }>;
8
+ newsletterReactionMode: (jid: string, mode: NewsletterReactionMode) => Promise<void>;
9
+ newsletterUpdateDescription: (jid: string, description?: string) => Promise<void>;
10
+ newsletterUpdateName: (jid: string, name: string) => Promise<void>;
11
+ newsletterUpdatePicture: (jid: string, content: WAMediaUpload) => Promise<void>;
12
+ newsletterRemovePicture: (jid: string) => Promise<void>;
13
+ newsletterUnfollow: (jid: string) => Promise<void>;
14
+ newsletterFollow: (jid: string) => Promise<void>;
15
+ newsletterUnmute: (jid: string) => Promise<void>;
16
+ newsletterMute: (jid: string) => Promise<void>;
17
+ newsletterCreate: (name: string, description: string) => Promise<NewsletterMetadata>;
18
+ newsletterMetadata: (type: 'invite' | 'jid', key: string, role?: NewsletterViewRole) => Promise<NewsletterMetadata>;
19
+ newsletterAdminCount: (jid: string) => Promise<number>;
20
+ /**user is Lid, not Jid */
21
+ newsletterChangeOwner: (jid: string, user: string) => Promise<void>;
22
+ /**user is Lid, not Jid */
23
+ newsletterDemote: (jid: string, user: string) => Promise<void>;
24
+ newsletterDelete: (jid: string) => Promise<void>;
25
+ /**if code wasn't passed, the reaction will be removed (if is reacted) */
26
+ newsletterReactMessage: (jid: string, server_id: string, code?: string) => Promise<void>;
27
+ newsletterFetchMessages: (type: 'invite' | 'jid', key: string, count: number, after?: number) => Promise<NewsletterFetchedUpdate[]>;
28
+ newsletterFetchUpdates: (jid: string, count: number, after?: number, since?: number) => Promise<NewsletterFetchedUpdate[]>;
29
+ groupMetadata: (jid: string) => Promise<import("../Types").GroupMetadata>;
30
+ groupCreate: (subject: string, participants: string[]) => Promise<import("../Types").GroupMetadata>;
31
+ groupLeave: (id: string) => Promise<void>;
32
+ groupUpdateSubject: (jid: string, subject: string) => Promise<void>;
33
+ groupRequestParticipantsList: (jid: string) => Promise<{
34
+ [key: string]: string;
35
+ }[]>;
36
+ groupRequestParticipantsUpdate: (jid: string, participants: string[], action: "reject" | "approve") => Promise<{
37
+ status: string;
38
+ jid: string;
39
+ }[]>;
40
+ groupParticipantsUpdate: (jid: string, participants: string[], action: import("../Types").ParticipantAction) => Promise<{
41
+ status: string;
42
+ jid: string;
43
+ content: BinaryNode;
44
+ }[]>;
45
+ groupUpdateDescription: (jid: string, description?: string | undefined) => Promise<void>;
46
+ groupInviteCode: (jid: string) => Promise<string | undefined>;
47
+ groupRevokeInvite: (jid: string) => Promise<string | undefined>;
48
+ groupAcceptInvite: (code: string) => Promise<string | undefined>;
49
+ groupRevokeInviteV4: (groupJid: string, invitedJid: string) => Promise<boolean>;
50
+ groupAcceptInviteV4: (key: string | import("../Types").WAMessageKey, inviteMessage: import("../Types").WAProto.Message.IGroupInviteMessage) => Promise<string>;
51
+ groupGetInviteInfo: (code: string) => Promise<import("../Types").GroupMetadata>;
52
+ groupToggleEphemeral: (jid: string, ephemeralExpiration: number) => Promise<void>;
53
+ groupSettingUpdate: (jid: string, setting: "announcement" | "locked" | "not_announcement" | "unlocked") => Promise<void>;
54
+ groupMemberAddMode: (jid: string, mode: "all_member_add" | "admin_add") => Promise<void>;
55
+ groupJoinApprovalMode: (jid: string, mode: "on" | "off") => Promise<void>;
56
+ groupFetchAllParticipating: () => Promise<{
57
+ [_: string]: import("../Types").GroupMetadata;
58
+ }>;
59
+ processingMutex: {
60
+ mutex<T>(code: () => T | Promise<T>): Promise<T>;
61
+ };
62
+ fetchPrivacySettings: (force?: boolean) => Promise<{
63
+ [_: string]: string;
64
+ }>;
65
+ upsertMessage: (msg: import("../Types").WAProto.IWebMessageInfo, type: import("../Types").MessageUpsertType) => Promise<void>;
66
+ appPatch: (patchCreate: import("../Types").WAPatchCreate) => Promise<void>;
67
+ sendPresenceUpdate: (type: import("../Types").WAPresence, toJid?: string | undefined) => Promise<void>;
68
+ presenceSubscribe: (toJid: string, tcToken?: Buffer | undefined) => Promise<void>;
69
+ profilePictureUrl: (jid: string, type?: "image" | "preview", timeoutMs?: number | undefined) => Promise<string | undefined>;
70
+ onWhatsApp: (...jids: string[]) => Promise<{
71
+ exists: boolean;
72
+ jid: string;
73
+ }[]>;
74
+ fetchBlocklist: () => Promise<string[]>;
75
+ fetchDisappearingDuration: (...jids: string[]) => Promise<{
76
+ user: string;
77
+ duration: number;
78
+ setAt: Date;
79
+ }[]>;
80
+ fetchStatus: (jid: string) => Promise<{
81
+ status: string | undefined;
82
+ setAt: Date;
83
+ } | undefined>;
84
+ updateProfilePicture: (jid: string, content: WAMediaUpload) => Promise<void>;
85
+ removeProfilePicture: (jid: string) => Promise<void>;
86
+ updateProfileStatus: (status: string) => Promise<void>;
87
+ updateProfileName: (name: string) => Promise<void>;
88
+ updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;
89
+ updateCallPrivacy: (value: import("../Types").WAPrivacyCallValue) => Promise<void>;
90
+ updateLastSeenPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
91
+ updateOnlinePrivacy: (value: import("../Types").WAPrivacyOnlineValue) => Promise<void>;
92
+ updateProfilePicturePrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
93
+ updateStatusPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
94
+ updateReadReceiptsPrivacy: (value: import("../Types").WAReadReceiptsValue) => Promise<void>;
95
+ updateGroupsAddPrivacy: (value: import("../Types").WAPrivacyGroupAddValue) => Promise<void>;
96
+ updateDefaultDisappearingMode: (duration: number) => Promise<void>;
97
+ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;
98
+ resyncAppState: (collections: readonly ("critical_block" | "critical_unblock_low" | "regular_high" | "regular_low" | "regular")[], isInitialSync: boolean) => Promise<void>;
99
+ chatModify: (mod: import("../Types").ChatModification, jid: string) => Promise<void>;
100
+ cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
101
+ addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
102
+ addChatLabel: (jid: string, labelId: string) => Promise<void>;
103
+ removeChatLabel: (jid: string, labelId: string) => Promise<void>;
104
+ addMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
105
+ removeMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
106
+ star: (jid: string, messages: {
107
+ id: string;
108
+ fromMe?: boolean | undefined;
109
+ }[], star: boolean) => Promise<void>;
110
+ type: "md";
111
+ ws: any;
112
+ ev: import("../Types").BaileysEventEmitter & {
113
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
114
+ buffer(): void;
115
+ createBufferedFunction<A extends any[], T_1>(work: (...args: A) => Promise<T_1>): (...args: A) => Promise<T_1>;
116
+ flush(force?: boolean | undefined): boolean;
117
+ isBuffering(): boolean;
118
+ };
119
+ authState: {
120
+ creds: import("../Types").AuthenticationCreds;
121
+ keys: import("../Types").SignalKeyStoreWithTransaction;
122
+ };
123
+ signalRepository: import("../Types").SignalRepository;
124
+ user: import("../Types").Contact | undefined;
125
+ generateMessageTag: () => string;
126
+ query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
127
+ waitForMessage: <T_2>(msgId: string, timeoutMs?: number | undefined) => Promise<T_2>;
128
+ waitForSocketOpen: () => Promise<void>;
129
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
130
+ sendNode: (frame: BinaryNode) => Promise<void>;
131
+ logout: (msg?: string | undefined) => Promise<void>;
132
+ end: (error: Error | undefined) => void;
133
+ onUnexpectedError: (err: Error | import("@hapi/boom").Boom<any>, msg: string) => void;
134
+ uploadPreKeys: (count?: number) => Promise<void>;
135
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
136
+ requestPairingCode: (phoneNumber: string) => Promise<string>;
137
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
138
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
139
+ };
140
+ export declare const extractNewsletterMetadata: (node: BinaryNode, isCreate?: boolean) => NewsletterMetadata;