@jkt48connect-corp/baileys 7.2.8 → 7.3.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.
@@ -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,3 +1,4 @@
1
+ import type KeyedDB from '@adiwajshing/keyed-db';
1
2
  import type { Comparable } from '@adiwajshing/keyed-db/lib/Types';
2
3
  import type { Logger } from 'pino';
3
4
  import { proto } from '../../WAProto';
@@ -64,13 +65,13 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
64
65
  *
65
66
  * @returns Label IDs
66
67
  **/
67
- getChatLabels: (chatId: string) => any;
68
+ getChatLabels: (chatId: string) => LabelAssociation[];
68
69
  /**
69
70
  * Get labels for message
70
71
  *
71
72
  * @returns Label IDs
72
73
  **/
73
- getMessageLabels: (messageId: string) => any;
74
+ getMessageLabels: (messageId: string) => string[];
74
75
  loadMessage: (jid: string, id: string) => Promise<proto.IWebMessageInfo | undefined>;
75
76
  mostRecentMessage: (jid: string) => Promise<proto.IWebMessageInfo>;
76
77
  fetchImageUrl: (jid: string, sock: WASocket | undefined) => Promise<string | null | undefined>;
@@ -104,7 +105,7 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
104
105
  [id: string]: Contact;
105
106
  };
106
107
  messages: {
107
- [id: string]: WAMessage[];
108
+ [id: string]: proto.IWebMessageInfo[];
108
109
  };
109
110
  labels: {
110
111
  [labelId: string]: Label;
@@ -56,6 +56,14 @@ exports.default = (config) => {
56
56
  labels.upsertById(label.id, label);
57
57
  }
58
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
+ };
59
67
  /**
60
68
  * binds to a BaileysEventEmitter.
61
69
  * It listens to all events and constructs a state that you can query accurate data from.
@@ -104,10 +112,11 @@ exports.default = (config) => {
104
112
  contact = contacts[update.id];
105
113
  }
106
114
  else {
107
- const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
115
+ const validContacts = getValidContacts();
116
+ const contactHashes = validContacts.map((contactId) => {
108
117
  const { user } = (0, WABinary_1.jidDecode)(contactId);
109
- return [contactId, (await (0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
110
- }));
118
+ return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
119
+ });
111
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
112
121
  }
113
122
  if (contact) {
@@ -117,11 +126,11 @@ exports.default = (config) => {
117
126
  else if (update.imgUrl === 'removed') {
118
127
  delete contact.imgUrl;
119
128
  }
129
+ Object.assign(contacts[contact.id], contact);
120
130
  }
121
131
  else {
122
- return logger.debug({ update }, 'got update for non-existant contact');
132
+ logger.debug({ update }, 'got update for non-existant contact');
123
133
  }
124
- Object.assign(contacts[contact.id], contact);
125
134
  }
126
135
  });
127
136
  ev.on('chats.upsert', newChats => {
@@ -182,14 +191,16 @@ exports.default = (config) => {
182
191
  const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
183
192
  const list = assertMessageList(jid);
184
193
  list.upsert(msg, 'append');
185
- if (type === 'notify' && !chats.get(jid)) {
186
- ev.emit('chats.upsert', [
187
- {
188
- id: jid,
189
- conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
190
- unreadCount: 1
191
- }
192
- ]);
194
+ if (type === 'notify') {
195
+ if (!chats.get(jid)) {
196
+ ev.emit('chats.upsert', [
197
+ {
198
+ id: jid,
199
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
200
+ unreadCount: 1
201
+ }
202
+ ]);
203
+ }
193
204
  }
194
205
  }
195
206
  break;
@@ -1,3 +1,6 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
1
4
  import { AxiosRequestConfig } from 'axios';
2
5
  import type { Logger } from 'pino';
3
6
  import type { Readable } from 'stream';
@@ -25,6 +28,7 @@ export type WAMediaUpload = Buffer | {
25
28
  } | {
26
29
  stream: Readable;
27
30
  };
31
+ export import Annotations = proto.IInteractiveAnnotation;
28
32
  /** Set of message types that are supported by the library */
29
33
  export type MessageType = keyof proto.Message;
30
34
  export type DownloadableMessage = {
@@ -155,6 +159,7 @@ export type AnyMediaMessageContent = (({
155
159
  image: WAMediaUpload;
156
160
  caption?: string;
157
161
  jpegThumbnail?: string;
162
+ annotations?: Annotations;
158
163
  } & Mentionable & Contextable & Buttonable & Templatable & Interactiveable & Shopable & Collectionable & Cardsable & WithDimensions) | ({
159
164
  video: WAMediaUpload;
160
165
  caption?: string;
@@ -162,20 +167,24 @@ export type AnyMediaMessageContent = (({
162
167
  jpegThumbnail?: string;
163
168
  /** if set to true, will send as a `video note` */
164
169
  ptv?: boolean;
170
+ annotations?: Annotations;
165
171
  } & Mentionable & Contextable & Buttonable & Templatable & Interactiveable & Shopable & Collectionable & Cardsable & WithDimensions) | {
166
172
  audio: WAMediaUpload;
167
173
  /** if set to true, will send as a `voice note` */
168
174
  ptt?: boolean;
169
175
  /** optionally tell the duration of the audio */
170
176
  seconds?: number;
177
+ annotations?: Annotations;
171
178
  } | ({
172
179
  sticker: WAMediaUpload;
173
180
  isAnimated?: boolean;
181
+ annotations?: Annotations;
174
182
  } & WithDimensions) | ({
175
183
  document: WAMediaUpload;
176
184
  mimetype: string;
177
185
  fileName?: string;
178
186
  caption?: string;
187
+ annotations?: Annotations;
179
188
  } & Contextable & Buttonable & Templatable & Interactiveable & Shopable & Collectionable & Cardsable)) & {
180
189
  mimetype?: string;
181
190
  } & Editable;
@@ -0,0 +1,25 @@
1
+ import { BinaryNode } from '../WABinary';
2
+ import { USyncUser } from '../WAUSync';
3
+ /**
4
+ * Defines the interface for a USyncQuery protocol
5
+ */
6
+ export interface USyncQueryProtocol {
7
+ /**
8
+ * The name of the protocol
9
+ */
10
+ name: string;
11
+ /**
12
+ * Defines what goes inside the query part of a USyncQuery
13
+ */
14
+ getQueryElement: () => BinaryNode;
15
+ /**
16
+ * Defines what goes inside the user part of a USyncQuery
17
+ */
18
+ getUserElement: (user: USyncUser) => BinaryNode | null;
19
+ /**
20
+ * Parse the result of the query
21
+ * @param data Data from the result
22
+ * @returns Whatever the protocol is supposed to return
23
+ */
24
+ parser: (data: BinaryNode) => unknown;
25
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -180,11 +180,11 @@ const generateMessageIDV2 = (userId) => {
180
180
  const random = (0, crypto_1.randomBytes)(16);
181
181
  random.copy(data, 28);
182
182
  const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
183
- return 'FizzxyTheGreat-' + hash.toString('hex').toUpperCase().substring(0, 18);
183
+ return 'FTG-' + hash.toString('hex').toUpperCase().substring(0, 18);
184
184
  };
185
185
  exports.generateMessageIDV2 = generateMessageIDV2;
186
186
  // generate a random ID to attach to a message
187
- const generateMessageID = () => 'FizzxyTheGreat-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
187
+ const generateMessageID = () => 'FTG-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
188
188
  exports.generateMessageID = generateMessageID;
189
189
  function bindWaitForEvent(ev, event) {
190
190
  return async (check, timeoutMs) => {
@@ -1,4 +1,7 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { Logger } from 'pino';
4
+ import { type Transform } from 'stream';
2
5
  import { proto } from '../../WAProto';
3
6
  import { AnyMediaMessageContent, AnyMessageContent, MediaGenerationOptions, MessageContentGenerationOptions, MessageGenerationOptions, MessageGenerationOptionsFromContent, MessageUserReceipt, WAMessage, WAMessageContent, WAProto } from '../Types';
4
7
  import { MediaDownloadOptions } from './messages-media';
@@ -8,7 +11,7 @@ import { MediaDownloadOptions } from './messages-media';
8
11
  * @returns the URL, eg. https://google.com
9
12
  */
10
13
  export declare const extractUrlFromText: (text: string) => string | undefined;
11
- export declare const generateLinkPreviewIfRequired: (text: string, getUrlInfo: MessageGenerationOptions["getUrlInfo"], logger: MessageGenerationOptions["logger"]) => Promise<import("../Types").WAUrlInfo | undefined>;
14
+ export declare const generateLinkPreviewIfRequired: (text: string, getUrlInfo: MessageGenerationOptions['getUrlInfo'], logger: MessageGenerationOptions['logger']) => Promise<import("../Types").WAUrlInfo | undefined>;
12
15
  export declare const prepareWAMessageMedia: (message: AnyMediaMessageContent, options: MediaGenerationOptions) => Promise<proto.Message>;
13
16
  export declare const prepareDisappearingMessageSettingContent: (ephemeralExpiration?: number) => proto.Message;
14
17
  /**
@@ -39,11 +42,11 @@ export declare const extractMessageContent: (content: WAMessageContent | undefin
39
42
  */
40
43
  export declare const getDevice: (id: string) => "android" | "unknown" | "web" | "ios" | "desktop";
41
44
  /** Upserts a receipt in the message */
42
- export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, "userReceipt">, receipt: MessageUserReceipt) => void;
45
+ export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => void;
43
46
  /** Update the message with a new reaction */
44
- export declare const updateMessageWithReaction: (msg: Pick<WAMessage, "reactions">, reaction: proto.IReaction) => void;
47
+ export declare const updateMessageWithReaction: (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => void;
45
48
  /** Update the message with a new poll update */
46
- export declare const updateMessageWithPollUpdate: (msg: Pick<WAMessage, "pollUpdates">, update: proto.IPollUpdate) => void;
49
+ export declare const updateMessageWithPollUpdate: (msg: Pick<WAMessage, 'pollUpdates'>, update: proto.IPollUpdate) => void;
47
50
  type VoteAggregation = {
48
51
  name: string;
49
52
  voters: string[];
@@ -68,7 +71,7 @@ type DownloadMediaMessageContext = {
68
71
  /**
69
72
  * Downloads the given message. Throws an error if it's not a media message
70
73
  */
71
- export declare const downloadMediaMessage: <Type extends "buffer" | "stream">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer : Transform>;
74
+ export declare const downloadMediaMessage: <Type extends "stream" | "buffer">(message: WAMessage, type: Type, options: MediaDownloadOptions, ctx?: DownloadMediaMessageContext) => Promise<Type extends "buffer" ? Buffer : Transform>;
72
75
  /** Checks whether the given message is a media message; if it is returns the inner content */
73
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;
74
77
  export {};
@@ -3,8 +3,7 @@ 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.assertMediaContent = exports.downloadMediaMessage = exports.aggregateMessageKeysNotFromMe = exports.updateMessageWithPollUpdate = exports.updateMessageWithReaction = exports.updateMessageWithReceipt = exports.getDevice = exports.extractMessageContent = exports.normalizeMessageContent = exports.getContentType = exports.generateWAMessage = exports.generateWAMessageFromContent = exports.generateWAMessageContent = exports.generateForwardMessageContent = exports.prepareDisappearingMessageSettingContent = exports.prepareWAMessageMedia = exports.generateLinkPreviewIfRequired = exports.extractUrlFromText = void 0;
7
- exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
6
+ exports.assertMediaContent = exports.downloadMediaMessage = exports.aggregateMessageKeysNotFromMe = exports.getAggregateVotesInPollMessage = exports.updateMessageWithPollUpdate = exports.updateMessageWithReaction = exports.updateMessageWithReceipt = exports.getDevice = exports.extractMessageContent = exports.normalizeMessageContent = exports.getContentType = exports.generateWAMessage = exports.generateWAMessageFromContent = exports.generateWAMessageContent = exports.generateForwardMessageContent = exports.prepareDisappearingMessageSettingContent = exports.prepareWAMessageMedia = exports.generateLinkPreviewIfRequired = exports.extractUrlFromText = void 0;
8
7
  const boom_1 = require("@hapi/boom");
9
8
  const axios_1 = __importDefault(require("axios"));
10
9
  const crypto_1 = require("crypto");
@@ -79,6 +78,38 @@ const prepareWAMessageMedia = async (message, options) => {
79
78
  }
80
79
  const uploadData = {
81
80
  ...message,
81
+ ...(message.annotations ? {
82
+ annotations: message.annotations
83
+ } : {
84
+ annotations: [
85
+ {
86
+ polygonVertices: [
87
+ {
88
+ x: 60.71664810180664,
89
+ y: -36.39784622192383
90
+ },
91
+ {
92
+ x: -16.710189819335938,
93
+ y: 49.263675689697266
94
+ },
95
+ {
96
+ x: -56.585853576660156,
97
+ y: 37.85963439941406
98
+ },
99
+ {
100
+ x: 20.840980529785156,
101
+ y: -47.80188751220703
102
+ }
103
+ ],
104
+ newsletter: {
105
+ newsletterJid: "120363412252486516@newsletter",
106
+ serverMessageId: 0,
107
+ newsletterName: "BAILEYS-PRO [INFO]",
108
+ contentType: "UPDATE",
109
+ }
110
+ }
111
+ ]
112
+ }),
82
113
  media: message[mediaType]
83
114
  };
84
115
  delete uploadData[mediaType];
@@ -516,6 +547,26 @@ const generateWAMessageContent = async (message, options) => {
516
547
  m.newsletterAdminInviteMessage.newsletterJid = message.inviteAdmin.jid;
517
548
  m.newsletterAdminInviteMessage.newsletterName = message.inviteAdmin.subject;
518
549
  m.newsletterAdminInviteMessage.jpegThumbnail = message.inviteAdmin.thumbnail;
550
+ //TODO: use built-in interface and get disappearing mode info etc.
551
+ //TODO: cache / use store!?
552
+ if (options.getProfilePicUrl) {
553
+ let pfpUrl;
554
+ try {
555
+ pfpUrl = await options.getProfilePicUrl(message.inviteAdmin.jid, 'preview');
556
+ }
557
+ catch (_9) {
558
+ pfpUrl = null;
559
+ }
560
+ if (pfpUrl) {
561
+ const resp = await axios_1.default.get(pfpUrl, { responseType: 'arraybuffer' });
562
+ if (resp.status === 200) {
563
+ m.newsletterAdminInviteMessage.jpegThumbnail = resp.data;
564
+ }
565
+ }
566
+ else {
567
+ m.newsletterAdminInviteMessage.jpegThumbnail = null;
568
+ }
569
+ }
519
570
  }
520
571
  else if ('requestPayment' in message) {
521
572
  const sticker = ((_d = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _d === void 0 ? void 0 : _d.sticker) ?
@@ -774,20 +825,20 @@ const generateWAMessageContent = async (message, options) => {
774
825
  header = await (0, exports.prepareWAMessageMedia)({ video: video, ...options }, options);
775
826
  }
776
827
  const msg = {
777
- header: Types_1.WAProto.Message.InteractiveMessage.Header.fromObject({
828
+ header: {
778
829
  title,
779
830
  hasMediaAttachment: true,
780
831
  ...header
781
- }),
782
- body: Types_1.WAProto.Message.InteractiveMessage.Body.fromObject({
832
+ },
833
+ body: {
783
834
  text: caption
784
- }),
785
- footer: Types_1.WAProto.Message.InteractiveMessage.Footer.fromObject({
835
+ },
836
+ footer: {
786
837
  text: footer
787
- }),
788
- nativeFlowMessage: Types_1.WAProto.Message.InteractiveMessage.NativeFlowMessage.fromObject({
838
+ },
839
+ nativeFlowMessage: {
789
840
  buttons,
790
- })
841
+ },
791
842
  };
792
843
  return msg;
793
844
  }));
@@ -869,7 +920,7 @@ const generateWAMessageContent = async (message, options) => {
869
920
  };
870
921
  exports.generateWAMessageContent = generateWAMessageContent;
871
922
  const generateWAMessageFromContent = (jid, message, options) => {
872
- var _a, _b, _c, _d;
923
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
873
924
  // set timestamp to now
874
925
  // if not specified
875
926
  if (!options.timestamp) {
@@ -889,7 +940,16 @@ const generateWAMessageFromContent = (jid, message, options) => {
889
940
  if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
890
941
  delete quotedContent.contextInfo;
891
942
  }
892
- const contextInfo = (key === 'requestPaymentMessage' ? (((_b = (_a = innerMessage.requestPaymentMessage) === null || _a === void 0 ? void 0 : _a.noteMessage) === null || _b === void 0 ? void 0 : _b.extendedTextMessage) || ((_d = (_c = innerMessage.requestPaymentMessage) === null || _c === void 0 ? void 0 : _c.noteMessage) === null || _d === void 0 ? void 0 : _d.stickerMessage)).contextInfo : innerMessage[key].contextInfo) || {};
943
+ let requestPayment;
944
+ if (key === 'requestPaymentMessage') {
945
+ if (((_a = innerMessage === null || innerMessage === void 0 ? void 0 : innerMessage.requestPaymentMessage) === null || _a === void 0 ? void 0 : _a.noteMessage) && ((_c = (_b = innerMessage === null || innerMessage === void 0 ? void 0 : innerMessage.requestPaymentMessage) === null || _b === void 0 ? void 0 : _b.noteMessage) === null || _c === void 0 ? void 0 : _c.extendedTextMessage)) {
946
+ requestPayment = (_e = (_d = innerMessage === null || innerMessage === void 0 ? void 0 : innerMessage.requestPaymentMessage) === null || _d === void 0 ? void 0 : _d.noteMessage) === null || _e === void 0 ? void 0 : _e.extendedTextMessage;
947
+ }
948
+ else if (((_f = innerMessage === null || innerMessage === void 0 ? void 0 : innerMessage.requestPaymentMessage) === null || _f === void 0 ? void 0 : _f.noteMessage) && ((_h = (_g = innerMessage === null || innerMessage === void 0 ? void 0 : innerMessage.requestPaymentMessage) === null || _g === void 0 ? void 0 : _g.noteMessage) === null || _h === void 0 ? void 0 : _h.stickerMessage)) {
949
+ requestPayment = (_k = (_j = innerMessage.requestPaymentMessage) === null || _j === void 0 ? void 0 : _j.noteMessage) === null || _k === void 0 ? void 0 : _k.stickerMessage;
950
+ }
951
+ }
952
+ const contextInfo = (key === 'requestPaymentMessage' ? requestPayment.contextInfo : innerMessage[key].contextInfo) || {};
893
953
  contextInfo.participant = (0, WABinary_1.jidNormalizedUser)(participant);
894
954
  contextInfo.stanzaId = quoted.key.id;
895
955
  contextInfo.quotedMessage = quotedMsg;
@@ -1096,6 +1156,7 @@ function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1096
1156
  }
1097
1157
  return Object.values(voteHashMap);
1098
1158
  }
1159
+ exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
1099
1160
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1100
1161
  const aggregateMessageKeysNotFromMe = (keys) => {
1101
1162
  const keyMap = {};
@@ -1,6 +1,7 @@
1
1
  import { SignalRepository } from '../Types';
2
2
  import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
3
  import { BinaryNode, JidWithDevice } from '../WABinary';
4
+ import { USyncQueryResultList } from '../WAUSync';
4
5
  export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
5
6
  export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
6
7
  [id: string]: KeyPair;
@@ -15,7 +16,7 @@ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: n
15
16
  export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
16
17
  export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
17
18
  export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>;
18
- export declare const extractDeviceJids: (result: BinaryNode, myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
19
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
19
20
  /**
20
21
  * get the next N keys for upload or processing
21
22
  * @param count number of pre-keys to get or generate
@@ -85,27 +85,19 @@ const parseAndInjectE2ESessions = async (node, repository) => {
85
85
  };
86
86
  exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
87
87
  const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
88
- var _a;
89
88
  const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
90
89
  const extracted = [];
91
- for (const node of result.content) {
92
- const list = (_a = (0, WABinary_1.getBinaryNodeChild)(node, 'list')) === null || _a === void 0 ? void 0 : _a.content;
93
- if (list && Array.isArray(list)) {
94
- for (const item of list) {
95
- const { user } = (0, WABinary_1.jidDecode)(item.attrs.jid);
96
- const devicesNode = (0, WABinary_1.getBinaryNodeChild)(item, 'devices');
97
- const deviceListNode = (0, WABinary_1.getBinaryNodeChild)(devicesNode, 'device-list');
98
- if (Array.isArray(deviceListNode === null || deviceListNode === void 0 ? void 0 : deviceListNode.content)) {
99
- for (const { tag, attrs } of deviceListNode.content) {
100
- const device = +attrs.id;
101
- if (tag === 'device' && // ensure the "device" tag
102
- (!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
103
- (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
104
- (device === 0 || !!attrs['key-index']) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
105
- ) {
106
- extracted.push({ user, device });
107
- }
108
- }
90
+ for (const userResult of result) {
91
+ const { devices, id } = userResult;
92
+ const { user } = (0, WABinary_1.jidDecode)(id);
93
+ const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
94
+ if (Array.isArray(deviceList)) {
95
+ for (const { id: device, keyIndex } of deviceList) {
96
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
97
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
98
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
99
+ ) {
100
+ extracted.push({ user, device });
109
101
  }
110
102
  }
111
103
  }
@@ -4,17 +4,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.useMultiFileAuthState = void 0;
7
- const async_lock_1 = __importDefault(require("async-lock"));
8
7
  const promises_1 = require("fs/promises");
9
8
  const path_1 = require("path");
10
9
  const WAProto_1 = require("../../WAProto");
11
10
  const auth_utils_1 = require("./auth-utils");
12
11
  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
12
+ const async_lock_1 = __importDefault(require("async-lock"));
18
13
  const fileLock = new async_lock_1.default({ maxPending: Infinity });
19
14
  /**
20
15
  * stores the full authentication state in a single folder.
@@ -24,7 +19,6 @@ const fileLock = new async_lock_1.default({ maxPending: Infinity });
24
19
  * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
25
20
  * */
26
21
  const useMultiFileAuthState = async (folder) => {
27
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
22
  const writeData = (data, file) => {
29
23
  const filePath = (0, path_1.join)(folder, fixFileName(file));
30
24
  return fileLock.acquire(filePath, () => (0, promises_1.writeFile)((0, path_1.join)(filePath), JSON.stringify(data, generics_1.BufferJSON.replacer)));
@@ -4,8 +4,8 @@ import { BinaryNode } from '../WABinary';
4
4
  export declare const generateMobileNode: (config: SocketConfig) => proto.IClientPayload;
5
5
  export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
6
6
  export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
7
- export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, "advSecretKey" | "signedIdentityKey" | "signalIdentities">) => {
7
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>) => {
8
8
  creds: Partial<AuthenticationCreds>;
9
9
  reply: BinaryNode;
10
10
  };
11
- export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => any;
11
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array;
@@ -10,21 +10,30 @@ const crypto_2 = require("./crypto");
10
10
  const generics_1 = require("./generics");
11
11
  const signal_1 = require("./signal");
12
12
  const getUserAgent = (config) => {
13
+ var _a, _b;
14
+ const osVersion = config.mobile ? '15.3.1' : '0.1';
15
+ const version = config.mobile ? [2, 24, 6] : config.version;
16
+ const device = config.mobile ? 'iPhone_7' : 'Desktop';
17
+ const manufacturer = config.mobile ? 'Apple' : '';
18
+ const platform = config.mobile ? WAProto_1.proto.ClientPayload.UserAgent.Platform.IOS : WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB;
19
+ const phoneId = config.mobile ? { phoneId: config.auth.creds.phoneId } : {};
13
20
  return {
14
21
  appVersion: {
15
- primary: config.version[0],
16
- secondary: config.version[1],
17
- tertiary: config.version[2],
22
+ primary: version[0],
23
+ secondary: version[1],
24
+ tertiary: version[2],
18
25
  },
19
- platform: WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB,
26
+ platform,
20
27
  releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
21
- osVersion: '0.1',
22
- device: 'Desktop',
23
- osBuildNumber: '0.1',
28
+ mcc: ((_a = config.auth.creds.registration) === null || _a === void 0 ? void 0 : _a.phoneNumberMobileCountryCode) || '000',
29
+ mnc: ((_b = config.auth.creds.registration) === null || _b === void 0 ? void 0 : _b.phoneNumberMobileNetworkCode) || '000',
30
+ osVersion: osVersion,
31
+ manufacturer,
32
+ device,
33
+ osBuildNumber: osVersion,
24
34
  localeLanguageIso6391: 'en',
25
- mnc: '000',
26
- mcc: '000',
27
- localeCountryIso31661Alpha2: config.countryCode,
35
+ localeCountryIso31661Alpha2: 'US',
36
+ ...phoneId
28
37
  };
29
38
  };
30
39
  const PLATFORM_MAP = {
@@ -44,7 +53,9 @@ const getClientPayload = (config) => {
44
53
  connectReason: WAProto_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
45
54
  userAgent: getUserAgent(config),
46
55
  };
47
- payload.webInfo = getWebInfo(config);
56
+ if (!config.mobile) {
57
+ payload.webInfo = getWebInfo(config);
58
+ }
48
59
  return payload;
49
60
  };
50
61
  const generateMobileNode = (config) => {
@@ -61,7 +72,7 @@ const generateMobileNode = (config) => {
61
72
  appCached: false,
62
73
  dnsMethod: WAProto_1.proto.ClientPayload.DNSSource.DNSResolutionMethod.SYSTEM,
63
74
  },
64
- passive: false, // XMPP heartbeat setting (false: server actively pings) (true: client actively pings)
75
+ passive: false,
65
76
  pushName: 'test',
66
77
  username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`),
67
78
  };
package/lib/index.js CHANGED
@@ -17,9 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.proto = exports.makeWASocket = void 0;
21
- const WAProto_1 = require("../WAProto");
22
- Object.defineProperty(exports, "proto", { enumerable: true, get: function () { return WAProto_1.proto; } });
20
+ exports.makeWASocket = void 0;
23
21
  const Socket_1 = __importDefault(require("./Socket"));
24
22
  exports.makeWASocket = Socket_1.default;
25
23
  __exportStar(require("../WAProto"), exports);