@vinzsocket/baileys 2.8.10 → 2.8.20

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