@fanzxnothuman/baileys 2.0.17

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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +479 -0
  3. package/WAProto/index.js +204542 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +158 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Function/Download/tiktok.js +19 -0
  9. package/lib/Function/Tools/bypass.js +19 -0
  10. package/lib/Function/index.js +13 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +99 -0
  13. package/lib/Signal/Group/group_cipher.js +131 -0
  14. package/lib/Signal/Group/index.js +141 -0
  15. package/lib/Signal/Group/keyhelper.js +78 -0
  16. package/lib/Signal/Group/queue-job.js +54 -0
  17. package/lib/Signal/Group/sender-chain-key.js +39 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +76 -0
  19. package/lib/Signal/Group/sender-key-message.js +86 -0
  20. package/lib/Signal/Group/sender-key-name.js +53 -0
  21. package/lib/Signal/Group/sender-key-record.js +71 -0
  22. package/lib/Signal/Group/sender-key-state.js +123 -0
  23. package/lib/Signal/Group/sender-message-key.js +33 -0
  24. package/lib/Signal/libsignal.js +223 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +35 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +96 -0
  28. package/lib/Socket/Client/web-socket-client.js +96 -0
  29. package/lib/Socket/business.js +289 -0
  30. package/lib/Socket/chats.js +1230 -0
  31. package/lib/Socket/dugong.js +689 -0
  32. package/lib/Socket/groups.js +401 -0
  33. package/lib/Socket/index.js +12 -0
  34. package/lib/Socket/messages-recv.js +1531 -0
  35. package/lib/Socket/messages-send.js +1011 -0
  36. package/lib/Socket/newsletter.js +526 -0
  37. package/lib/Socket/registration.js +212 -0
  38. package/lib/Socket/socket.js +842 -0
  39. package/lib/Socket/usync.js +67 -0
  40. package/lib/Store/index.js +16 -0
  41. package/lib/Store/make-cache-manager-store.js +90 -0
  42. package/lib/Store/make-in-memory-store.js +520 -0
  43. package/lib/Store/make-ordered-dictionary.js +78 -0
  44. package/lib/Store/object-repository.js +27 -0
  45. package/lib/Types/Auth.js +2 -0
  46. package/lib/Types/Call.js +2 -0
  47. package/lib/Types/Chat.js +10 -0
  48. package/lib/Types/Contact.js +2 -0
  49. package/lib/Types/Events.js +2 -0
  50. package/lib/Types/GroupMetadata.js +2 -0
  51. package/lib/Types/Label.js +27 -0
  52. package/lib/Types/LabelAssociation.js +12 -0
  53. package/lib/Types/Message.js +14 -0
  54. package/lib/Types/Newsletter.js +38 -0
  55. package/lib/Types/Product.js +2 -0
  56. package/lib/Types/Signal.js +2 -0
  57. package/lib/Types/Socket.js +2 -0
  58. package/lib/Types/State.js +2 -0
  59. package/lib/Types/USync.js +2 -0
  60. package/lib/Types/index.js +67 -0
  61. package/lib/Utils/auth-utils.js +223 -0
  62. package/lib/Utils/baileys-event-stream.js +67 -0
  63. package/lib/Utils/business.js +308 -0
  64. package/lib/Utils/chat-utils.js +1030 -0
  65. package/lib/Utils/crypto.js +210 -0
  66. package/lib/Utils/decode-wa-message.js +225 -0
  67. package/lib/Utils/event-buffer.js +559 -0
  68. package/lib/Utils/generics.js +599 -0
  69. package/lib/Utils/history.js +132 -0
  70. package/lib/Utils/index.js +49 -0
  71. package/lib/Utils/link-preview.js +112 -0
  72. package/lib/Utils/logger.js +11 -0
  73. package/lib/Utils/lt-hash.js +58 -0
  74. package/lib/Utils/make-mutex.js +41 -0
  75. package/lib/Utils/messages-media.js +978 -0
  76. package/lib/Utils/messages.js +1052 -0
  77. package/lib/Utils/noise-handler.js +185 -0
  78. package/lib/Utils/process-message.js +466 -0
  79. package/lib/Utils/signal.js +199 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +129 -0
  81. package/lib/Utils/validate-connection.js +285 -0
  82. package/lib/WABinary/constants.js +1307 -0
  83. package/lib/WABinary/decode.js +287 -0
  84. package/lib/WABinary/encode.js +286 -0
  85. package/lib/WABinary/generic-utils.js +227 -0
  86. package/lib/WABinary/index.js +37 -0
  87. package/lib/WABinary/jid-utils.js +92 -0
  88. package/lib/WABinary/types.js +2 -0
  89. package/lib/WAM/BinaryInfo.js +13 -0
  90. package/lib/WAM/constants.js +15260 -0
  91. package/lib/WAM/encode.js +153 -0
  92. package/lib/WAM/index.js +35 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +37 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +78 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  99. package/lib/WAUSync/Protocols/index.js +36 -0
  100. package/lib/WAUSync/USyncQuery.js +105 -0
  101. package/lib/WAUSync/USyncUser.js +26 -0
  102. package/lib/WAUSync/index.js +35 -0
  103. package/lib/index.js +65 -0
  104. package/package.json +109 -0
@@ -0,0 +1,67 @@
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: [queryNode, listNode],
56
+ },
57
+ ],
58
+ };
59
+ const result = await query(iq);
60
+ return usyncQuery.parseUSyncQueryResult(result);
61
+ };
62
+ return {
63
+ ...sock,
64
+ executeUSyncQuery,
65
+ };
66
+ };
67
+ exports.makeUSyncSocket = makeUSyncSocket;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.makeCacheManagerAuthState = exports.makeInMemoryStore = void 0;
9
+ const make_cache_manager_store_1 = __importDefault(
10
+ require("./make-cache-manager-store"),
11
+ );
12
+ exports.makeCacheManagerAuthState = make_cache_manager_store_1.default;
13
+ const make_in_memory_store_1 = __importDefault(
14
+ require("./make-in-memory-store"),
15
+ );
16
+ exports.makeInMemoryStore = make_in_memory_store_1.default;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ const cache_manager_1 = require("cache-manager");
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Utils_1 = require("../Utils");
11
+ const logger_1 = __importDefault(require("../Utils/logger"));
12
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
13
+ const defaultKey = (file) => `${sessionKey}:${file}`;
14
+ const databaseConn = await (0, cache_manager_1.caching)(store);
15
+ const writeData = async (file, data) => {
16
+ let ttl = undefined;
17
+ if (file === "creds") {
18
+ ttl = 63115200; // 2 years
19
+ }
20
+ await databaseConn.set(
21
+ defaultKey(file),
22
+ JSON.stringify(data, Utils_1.BufferJSON.replacer),
23
+ ttl,
24
+ );
25
+ };
26
+ const readData = async (file) => {
27
+ try {
28
+ const data = await databaseConn.get(defaultKey(file));
29
+ if (data) {
30
+ return JSON.parse(data, Utils_1.BufferJSON.reviver);
31
+ }
32
+ return null;
33
+ } catch (error) {
34
+ logger_1.default.error(error);
35
+ return null;
36
+ }
37
+ };
38
+ const removeData = async (file) => {
39
+ try {
40
+ return await databaseConn.del(defaultKey(file));
41
+ } catch (_a) {
42
+ logger_1.default.error(
43
+ `Error removing ${file} from session ${sessionKey}`,
44
+ );
45
+ }
46
+ };
47
+ const clearState = async () => {
48
+ try {
49
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
50
+ await Promise.all(result.map(async (key) => await databaseConn.del(key)));
51
+ } catch (err) {}
52
+ };
53
+ const creds = (await readData("creds")) || (0, Utils_1.initAuthCreds)();
54
+ return {
55
+ clearState,
56
+ saveCreds: () => writeData("creds", creds),
57
+ state: {
58
+ creds,
59
+ keys: {
60
+ get: async (type, ids) => {
61
+ const data = {};
62
+ await Promise.all(
63
+ ids.map(async (id) => {
64
+ let value = await readData(`${type}-${id}`);
65
+ if (type === "app-state-sync-key" && value) {
66
+ value =
67
+ WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
68
+ }
69
+ data[id] = value;
70
+ }),
71
+ );
72
+ return data;
73
+ },
74
+ set: async (data) => {
75
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
+ const tasks = [];
77
+ for (const category in data) {
78
+ for (const id in data[category]) {
79
+ const value = data[category][id];
80
+ const key = `${category}-${id}`;
81
+ tasks.push(value ? writeData(key, value) : removeData(key));
82
+ }
83
+ }
84
+ await Promise.all(tasks);
85
+ },
86
+ },
87
+ },
88
+ };
89
+ };
90
+ exports.default = makeCacheManagerAuthState;
@@ -0,0 +1,520 @@
1
+ "use strict";
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.waLabelAssociationKey =
9
+ exports.waMessageID =
10
+ exports.waChatKey =
11
+ void 0;
12
+ const WAProto_1 = require("../../WAProto");
13
+ const Defaults_1 = require("../Defaults");
14
+ const LabelAssociation_1 = require("../Types/LabelAssociation");
15
+ const Utils_1 = require("../Utils");
16
+ const WABinary_1 = require("../WABinary");
17
+ const make_ordered_dictionary_1 = __importDefault(
18
+ require("./make-ordered-dictionary"),
19
+ );
20
+ const object_repository_1 = require("./object-repository");
21
+ const waChatKey = (pin) => ({
22
+ key: (c) =>
23
+ (pin ? (c.pinned ? "1" : "0") : "") +
24
+ (c.archived ? "0" : "1") +
25
+ (c.conversationTimestamp
26
+ ? c.conversationTimestamp.toString(16).padStart(8, "0")
27
+ : "") +
28
+ c.id,
29
+ compare: (k1, k2) => k2.localeCompare(k1),
30
+ });
31
+ exports.waChatKey = waChatKey;
32
+ const waMessageID = (m) => m.key.id || "";
33
+ exports.waMessageID = waMessageID;
34
+ exports.waLabelAssociationKey = {
35
+ key: (la) =>
36
+ la.type === LabelAssociation_1.LabelAssociationType.Chat
37
+ ? la.chatId + la.labelId
38
+ : la.chatId + la.messageId + la.labelId,
39
+ compare: (k1, k2) => k2.localeCompare(k1),
40
+ };
41
+ const makeMessagesDictionary = () =>
42
+ (0, make_ordered_dictionary_1.default)(exports.waMessageID);
43
+ exports.default = (config) => {
44
+ const socket = config.socket;
45
+ const chatKey = config.chatKey || (0, exports.waChatKey)(true);
46
+ const labelAssociationKey =
47
+ config.labelAssociationKey || exports.waLabelAssociationKey;
48
+ const logger =
49
+ config.logger ||
50
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
51
+ stream: "in-mem-store",
52
+ });
53
+ const KeyedDB = require("@adiwajshing/keyed-db").default;
54
+ const chats = new KeyedDB(chatKey, (c) => c.id);
55
+ const messages = {};
56
+ const contacts = {};
57
+ const groupMetadata = {};
58
+ const presences = {};
59
+ const state = { connection: "close" };
60
+ const labels = new object_repository_1.ObjectRepository();
61
+ const labelAssociations = new KeyedDB(
62
+ labelAssociationKey,
63
+ labelAssociationKey.key,
64
+ );
65
+ const assertMessageList = (jid) => {
66
+ if (!messages[jid]) {
67
+ messages[jid] = makeMessagesDictionary();
68
+ }
69
+ return messages[jid];
70
+ };
71
+ const contactsUpsert = (newContacts) => {
72
+ const oldContacts = new Set(Object.keys(contacts));
73
+ for (const contact of newContacts) {
74
+ oldContacts.delete(contact.id);
75
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
76
+ }
77
+ return oldContacts;
78
+ };
79
+ const labelsUpsert = (newLabels) => {
80
+ for (const label of newLabels) {
81
+ labels.upsertById(label.id, label);
82
+ }
83
+ };
84
+ const getValidContacts = () => {
85
+ for (const contact of Object.keys(contacts)) {
86
+ if (contact.indexOf("@") < 0) {
87
+ delete contacts[contact];
88
+ }
89
+ }
90
+ return Object.keys(contacts);
91
+ };
92
+ /**
93
+ * binds to a BaileysEventEmitter.
94
+ * It listens to all events and constructs a state that you can query accurate data from.
95
+ * Eg. can use the store to fetch chats, contacts, messages etc.
96
+ * @param ev typically the event emitter from the socket connection
97
+ */
98
+ const bind = (ev) => {
99
+ ev.on("connection.update", (update) => {
100
+ Object.assign(state, update);
101
+ });
102
+ ev.on(
103
+ "messaging-history.set",
104
+ ({
105
+ chats: newChats,
106
+ contacts: newContacts,
107
+ messages: newMessages,
108
+ isLatest,
109
+ }) => {
110
+ if (isLatest) {
111
+ chats.clear();
112
+ for (const id in messages) {
113
+ delete messages[id];
114
+ }
115
+ }
116
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
117
+ logger.debug({ chatsAdded }, "synced chats");
118
+ const oldContacts = contactsUpsert(newContacts);
119
+ if (isLatest) {
120
+ for (const jid of oldContacts) {
121
+ delete contacts[jid];
122
+ }
123
+ }
124
+ logger.debug(
125
+ { deletedContacts: isLatest ? oldContacts.size : 0, newContacts },
126
+ "synced contacts",
127
+ );
128
+ for (const msg of newMessages) {
129
+ const jid = msg.key.remoteJid;
130
+ const list = assertMessageList(jid);
131
+ list.upsert(msg, "prepend");
132
+ }
133
+ logger.debug({ messages: newMessages.length }, "synced messages");
134
+ },
135
+ );
136
+ ev.on("contacts.upsert", (contacts) => {
137
+ contactsUpsert(contacts);
138
+ });
139
+ ev.on("contacts.update", async (updates) => {
140
+ var _a;
141
+ for (const update of updates) {
142
+ let contact;
143
+ if (contacts[update.id]) {
144
+ contact = contacts[update.id];
145
+ } else {
146
+ const validContacts = getValidContacts();
147
+ const contactHashes = validContacts.map((contactId) => {
148
+ const { user } = (0, WABinary_1.jidDecode)(contactId);
149
+ return [
150
+ contactId,
151
+ (0, Utils_1.md5)(Buffer.from(user + "WA_ADD_NOTIF", "utf8"))
152
+ .toString("base64")
153
+ .slice(0, 3),
154
+ ];
155
+ });
156
+ contact =
157
+ contacts[
158
+ ((_a = contactHashes.find(([, b]) => b === update.id)) === null ||
159
+ _a === void 0
160
+ ? void 0
161
+ : _a[0]) || ""
162
+ ]; // find contact by attrs.hash, when user is not saved as a contact
163
+ }
164
+ if (contact) {
165
+ if (update.imgUrl === "changed") {
166
+ contact.imgUrl = socket
167
+ ? await (socket === null || socket === void 0
168
+ ? void 0
169
+ : socket.profilePictureUrl(contact.id))
170
+ : undefined;
171
+ } else if (update.imgUrl === "removed") {
172
+ delete contact.imgUrl;
173
+ }
174
+ Object.assign(contacts[contact.id], contact);
175
+ } else {
176
+ logger.debug({ update }, "got update for non-existant contact");
177
+ }
178
+ }
179
+ });
180
+ ev.on("chats.upsert", (newChats) => {
181
+ chats.upsert(...newChats);
182
+ });
183
+ ev.on("chats.update", (updates) => {
184
+ for (let update of updates) {
185
+ const result = chats.update(update.id, (chat) => {
186
+ if (update.unreadCount > 0) {
187
+ update = { ...update };
188
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
189
+ }
190
+ Object.assign(chat, update);
191
+ });
192
+ if (!result) {
193
+ logger.debug({ update }, "got update for non-existant chat");
194
+ }
195
+ }
196
+ });
197
+ ev.on("labels.edit", (label) => {
198
+ if (label.deleted) {
199
+ return labels.deleteById(label.id);
200
+ }
201
+ // WhatsApp can store only up to 20 labels
202
+ if (labels.count() < 20) {
203
+ return labels.upsertById(label.id, label);
204
+ }
205
+ logger.error("Labels count exceed");
206
+ });
207
+ ev.on("labels.association", ({ type, association }) => {
208
+ switch (type) {
209
+ case "add":
210
+ labelAssociations.upsert(association);
211
+ break;
212
+ case "remove":
213
+ labelAssociations.delete(association);
214
+ break;
215
+ default:
216
+ console.error(`unknown operation type [${type}]`);
217
+ }
218
+ });
219
+ ev.on("presence.update", ({ id, presences: update }) => {
220
+ presences[id] = presences[id] || {};
221
+ Object.assign(presences[id], update);
222
+ });
223
+ ev.on("chats.delete", (deletions) => {
224
+ for (const item of deletions) {
225
+ if (chats.get(item)) {
226
+ chats.deleteById(item);
227
+ }
228
+ }
229
+ });
230
+ ev.on("messages.upsert", ({ messages: newMessages, type }) => {
231
+ switch (type) {
232
+ case "append":
233
+ case "notify":
234
+ for (const msg of newMessages) {
235
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
236
+ const list = assertMessageList(jid);
237
+ list.upsert(msg, "append");
238
+ if (type === "notify") {
239
+ if (!chats.get(jid)) {
240
+ ev.emit("chats.upsert", [
241
+ {
242
+ id: jid,
243
+ conversationTimestamp: (0, Utils_1.toNumber)(
244
+ msg.messageTimestamp,
245
+ ),
246
+ unreadCount: 1,
247
+ },
248
+ ]);
249
+ }
250
+ }
251
+ }
252
+ break;
253
+ }
254
+ });
255
+ ev.on("messages.update", (updates) => {
256
+ var _a;
257
+ for (const { update, key } of updates) {
258
+ const list = assertMessageList(
259
+ (0, WABinary_1.jidNormalizedUser)(key.remoteJid),
260
+ );
261
+ if (update === null || update === void 0 ? void 0 : update.status) {
262
+ const listStatus =
263
+ (_a = list.get(key.id)) === null || _a === void 0
264
+ ? void 0
265
+ : _a.status;
266
+ if (
267
+ listStatus &&
268
+ (update === null || update === void 0 ? void 0 : update.status) <=
269
+ listStatus
270
+ ) {
271
+ logger.debug(
272
+ { update, storedStatus: listStatus },
273
+ "status stored newer then update",
274
+ );
275
+ delete update.status;
276
+ logger.debug({ update }, "new update object");
277
+ }
278
+ }
279
+ const result = list.updateAssign(key.id, update);
280
+ if (!result) {
281
+ logger.debug({ update }, "got update for non-existent message");
282
+ }
283
+ }
284
+ });
285
+ ev.on("messages.delete", (item) => {
286
+ if ("all" in item) {
287
+ const list = messages[item.jid];
288
+ list === null || list === void 0 ? void 0 : list.clear();
289
+ } else {
290
+ const jid = item.keys[0].remoteJid;
291
+ const list = messages[jid];
292
+ if (list) {
293
+ const idSet = new Set(item.keys.map((k) => k.id));
294
+ list.filter((m) => !idSet.has(m.key.id));
295
+ }
296
+ }
297
+ });
298
+ ev.on("groups.update", (updates) => {
299
+ for (const update of updates) {
300
+ const id = update.id;
301
+ if (groupMetadata[id]) {
302
+ Object.assign(groupMetadata[id], update);
303
+ } else {
304
+ logger.debug(
305
+ { update },
306
+ "got update for non-existant group metadata",
307
+ );
308
+ }
309
+ }
310
+ });
311
+ ev.on("group-participants.update", ({ id, participants, action }) => {
312
+ const metadata = groupMetadata[id];
313
+ if (metadata) {
314
+ switch (action) {
315
+ case "add":
316
+ metadata.participants.push(
317
+ ...participants.map((id) => ({
318
+ id,
319
+ isAdmin: false,
320
+ isSuperAdmin: false,
321
+ })),
322
+ );
323
+ break;
324
+ case "demote":
325
+ case "promote":
326
+ for (const participant of metadata.participants) {
327
+ if (participants.includes(participant.id)) {
328
+ participant.isAdmin = action === "promote";
329
+ }
330
+ }
331
+ break;
332
+ case "remove":
333
+ metadata.participants = metadata.participants.filter(
334
+ (p) => !participants.includes(p.id),
335
+ );
336
+ break;
337
+ }
338
+ }
339
+ });
340
+ ev.on("message-receipt.update", (updates) => {
341
+ for (const { key, receipt } of updates) {
342
+ const obj = messages[key.remoteJid];
343
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
344
+ if (msg) {
345
+ (0, Utils_1.updateMessageWithReceipt)(msg, receipt);
346
+ }
347
+ }
348
+ });
349
+ ev.on("messages.reaction", (reactions) => {
350
+ for (const { key, reaction } of reactions) {
351
+ const obj = messages[key.remoteJid];
352
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
353
+ if (msg) {
354
+ (0, Utils_1.updateMessageWithReaction)(msg, reaction);
355
+ }
356
+ }
357
+ });
358
+ };
359
+ const toJSON = () => ({
360
+ chats,
361
+ contacts,
362
+ messages,
363
+ labels,
364
+ labelAssociations,
365
+ });
366
+ const fromJSON = (json) => {
367
+ chats.upsert(...json.chats);
368
+ labelAssociations.upsert(...(json.labelAssociations || []));
369
+ contactsUpsert(Object.values(json.contacts));
370
+ labelsUpsert(Object.values(json.labels || {}));
371
+ for (const jid in json.messages) {
372
+ const list = assertMessageList(jid);
373
+ for (const msg of json.messages[jid]) {
374
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), "append");
375
+ }
376
+ }
377
+ };
378
+ return {
379
+ chats,
380
+ contacts,
381
+ messages,
382
+ groupMetadata,
383
+ state,
384
+ presences,
385
+ labels,
386
+ labelAssociations,
387
+ bind,
388
+ /** loads messages from the store, if not found -- uses the legacy connection */
389
+ loadMessages: async (jid, count, cursor) => {
390
+ const list = assertMessageList(jid);
391
+ const mode = !cursor || "before" in cursor ? "before" : "after";
392
+ const cursorKey = !!cursor
393
+ ? "before" in cursor
394
+ ? cursor.before
395
+ : cursor.after
396
+ : undefined;
397
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
398
+ let messages;
399
+ if (list && mode === "before" && (!cursorKey || cursorValue)) {
400
+ if (cursorValue) {
401
+ const msgIdx = list.array.findIndex(
402
+ (m) =>
403
+ m.key.id ===
404
+ (cursorKey === null || cursorKey === void 0
405
+ ? void 0
406
+ : cursorKey.id),
407
+ );
408
+ messages = list.array.slice(0, msgIdx);
409
+ } else {
410
+ messages = list.array;
411
+ }
412
+ const diff = count - messages.length;
413
+ if (diff < 0) {
414
+ messages = messages.slice(-count); // get the last X messages
415
+ }
416
+ } else {
417
+ messages = [];
418
+ }
419
+ return messages;
420
+ },
421
+ /**
422
+ * Get all available labels for profile
423
+ *
424
+ * Keep in mind that the list is formed from predefined tags and tags
425
+ * that were "caught" during their editing.
426
+ */
427
+ getLabels: () => {
428
+ return labels;
429
+ },
430
+ /**
431
+ * Get labels for chat
432
+ *
433
+ * @returns Label IDs
434
+ **/
435
+ getChatLabels: (chatId) => {
436
+ return labelAssociations.filter((la) => la.chatId === chatId).all();
437
+ },
438
+ /**
439
+ * Get labels for message
440
+ *
441
+ * @returns Label IDs
442
+ **/
443
+ getMessageLabels: (messageId) => {
444
+ const associations = labelAssociations
445
+ .filter((la) => la.messageId === messageId)
446
+ .all();
447
+ return associations.map(({ labelId }) => labelId);
448
+ },
449
+ loadMessage: async (jid, id) => {
450
+ var _a;
451
+ return (_a = messages[jid]) === null || _a === void 0
452
+ ? void 0
453
+ : _a.get(id);
454
+ },
455
+ mostRecentMessage: async (jid) => {
456
+ var _a;
457
+ const message =
458
+ (_a = messages[jid]) === null || _a === void 0
459
+ ? void 0
460
+ : _a.array.slice(-1)[0];
461
+ return message;
462
+ },
463
+ fetchImageUrl: async (jid, sock) => {
464
+ const contact = contacts[jid];
465
+ if (!contact) {
466
+ return sock === null || sock === void 0
467
+ ? void 0
468
+ : sock.profilePictureUrl(jid);
469
+ }
470
+ if (typeof contact.imgUrl === "undefined") {
471
+ contact.imgUrl = await (sock === null || sock === void 0
472
+ ? void 0
473
+ : sock.profilePictureUrl(jid));
474
+ }
475
+ return contact.imgUrl;
476
+ },
477
+ fetchGroupMetadata: async (jid, sock) => {
478
+ if (!groupMetadata[jid]) {
479
+ const metadata = await (sock === null || sock === void 0
480
+ ? void 0
481
+ : sock.groupMetadata(jid));
482
+ if (metadata) {
483
+ groupMetadata[jid] = metadata;
484
+ }
485
+ }
486
+ return groupMetadata[jid];
487
+ },
488
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
489
+ // if(!groupMetadata[jid]) {
490
+ // const metadata = await sock?.getBroadcastListInfo(jid)
491
+ // if(metadata) {
492
+ // groupMetadata[jid] = metadata
493
+ // }
494
+ // }
495
+ // return groupMetadata[jid]
496
+ // },
497
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
498
+ const list = messages[remoteJid];
499
+ const msg = list === null || list === void 0 ? void 0 : list.get(id);
500
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
501
+ },
502
+ toJSON,
503
+ fromJSON,
504
+ writeToFile: (path) => {
505
+ // require fs here so that in case "fs" is not available -- the app does not crash
506
+ const { writeFileSync } = require("fs");
507
+ writeFileSync(path, JSON.stringify(toJSON()));
508
+ },
509
+ readFromFile: (path) => {
510
+ // require fs here so that in case "fs" is not available -- the app does not crash
511
+ const { readFileSync, existsSync } = require("fs");
512
+ if (existsSync(path)) {
513
+ logger.debug({ path }, "reading from file");
514
+ const jsonStr = readFileSync(path, { encoding: "utf-8" });
515
+ const json = JSON.parse(jsonStr);
516
+ fromJSON(json);
517
+ }
518
+ },
519
+ };
520
+ };