@baileys-md/baileys 11.2.4 → 12.0.1

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