@zervonexx/baileys 5.0.0 → 5.0.2

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