@badzz88/baileys 8.4.7 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/index.js +5 -5
  4. package/lib/Defaults/index.js +187 -127
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +14 -11
  7. package/lib/Signal/Group/group-session-builder.js +91 -29
  8. package/lib/Signal/Group/group_cipher.js +88 -81
  9. package/lib/Signal/Group/index.js +136 -12
  10. package/lib/Signal/Group/keyhelper.js +70 -15
  11. package/lib/Signal/Group/sender-chain-key.js +31 -25
  12. package/lib/Signal/Group/sender-key-distribution-message.js +65 -62
  13. package/lib/Signal/Group/sender-key-message.js +68 -65
  14. package/lib/Signal/Group/sender-key-name.js +43 -41
  15. package/lib/Signal/Group/sender-key-record.js +43 -40
  16. package/lib/Signal/Group/sender-key-state.js +96 -83
  17. package/lib/Signal/Group/sender-message-key.js +29 -25
  18. package/lib/Signal/libsignal.js +483 -424
  19. package/lib/Signal/lid-mapping.js +261 -276
  20. package/lib/Socket/Client/index.js +30 -3
  21. package/lib/Socket/Client/types.js +12 -10
  22. package/lib/Socket/Client/websocket.js +61 -53
  23. package/lib/Socket/aigroups.js +240 -0
  24. package/lib/Socket/business.js +422 -379
  25. package/lib/Socket/chats.js +1816 -1193
  26. package/lib/Socket/communities.js +549 -431
  27. package/lib/Socket/graphql.js +656 -0
  28. package/lib/Socket/groups.js +764 -374
  29. package/lib/Socket/index.js +38 -11
  30. package/lib/Socket/interactive-handler.js +522 -0
  31. package/lib/Socket/interop.js +549 -0
  32. package/lib/Socket/luxu.js +6 -5
  33. package/lib/Socket/managed-account.js +183 -0
  34. package/lib/Socket/messages-recv.js +2439 -1915
  35. package/lib/Socket/messages-send.js +1642 -1242
  36. package/lib/Socket/mex.js +59 -40
  37. package/lib/Socket/newsletter.js +812 -249
  38. package/lib/Socket/privacy.js +449 -0
  39. package/lib/Socket/registration.js +427 -0
  40. package/lib/Socket/socket.js +1077 -965
  41. package/lib/Socket/text-router.js +83 -0
  42. package/lib/Socket/username.js +237 -140
  43. package/lib/Store/index.js +36 -10
  44. package/lib/Store/make-cache-manager-store.js +85 -80
  45. package/lib/Store/make-in-memory-store.js +591 -185
  46. package/lib/Store/make-ordered-dictionary.js +78 -72
  47. package/lib/Store/object-repository.js +25 -28
  48. package/lib/Types/Auth.js +38 -2
  49. package/lib/Types/Bussines.js +2 -2
  50. package/lib/Types/Call.js +2 -2
  51. package/lib/Types/Chat.js +4 -8
  52. package/lib/Types/Contact.js +2 -2
  53. package/lib/Types/Events.js +2 -2
  54. package/lib/Types/GroupMetadata.js +2 -2
  55. package/lib/Types/Label.js +26 -24
  56. package/lib/Types/LabelAssociation.js +8 -6
  57. package/lib/Types/Message.js +95 -11
  58. package/lib/Types/Mex.js +112 -37
  59. package/lib/Types/Newsletter.js +121 -0
  60. package/lib/Types/Product.js +2 -2
  61. package/lib/Types/Signal.js +2 -2
  62. package/lib/Types/Socket.js +2 -3
  63. package/lib/Types/State.js +70 -56
  64. package/lib/Types/USync.js +2 -2
  65. package/lib/Types/index.js +55 -26
  66. package/lib/Utils/auth-utils.js +292 -288
  67. package/lib/Utils/browser-utils.js +113 -48
  68. package/lib/Utils/business.js +240 -224
  69. package/lib/Utils/chat-utils.js +1205 -869
  70. package/lib/Utils/command-loader.d.ts +31 -0
  71. package/lib/Utils/command-loader.js +100 -0
  72. package/lib/Utils/companion-reg-client-utils.js +41 -34
  73. package/lib/Utils/consumer-application.js +107 -0
  74. package/lib/Utils/crypto.js +144 -107
  75. package/lib/Utils/curve25519-js.js +275 -0
  76. package/lib/Utils/decode-wa-message.js +518 -308
  77. package/lib/Utils/event-buffer.js +596 -611
  78. package/lib/Utils/generics.js +514 -354
  79. package/lib/Utils/group-history.js +60 -0
  80. package/lib/Utils/history.js +244 -134
  81. package/lib/Utils/identity-change-handler.js +51 -49
  82. package/lib/Utils/index.js +57 -23
  83. package/lib/Utils/jid-display-normalization.js +218 -0
  84. package/lib/Utils/link-preview.js +135 -77
  85. package/lib/Utils/logger.js +9 -3
  86. package/lib/Utils/lt-hash.js +37 -6
  87. package/lib/Utils/make-mutex.js +36 -33
  88. package/lib/Utils/message-composer.js +439 -233
  89. package/lib/Utils/message-retry-manager.js +265 -260
  90. package/lib/Utils/messages-media.js +855 -747
  91. package/lib/Utils/messages.js +2528 -884
  92. package/lib/Utils/meta-ai-msmsg.js +262 -0
  93. package/lib/Utils/native-bridge.js +82 -0
  94. package/lib/Utils/noise-handler.js +195 -200
  95. package/lib/Utils/offline-node-processor.js +35 -33
  96. package/lib/Utils/pre-key-manager.js +103 -102
  97. package/lib/Utils/process-message.js +978 -560
  98. package/lib/Utils/reporting-utils.js +257 -253
  99. package/lib/Utils/session-pool.d.ts +16 -0
  100. package/lib/Utils/session-pool.js +94 -0
  101. package/lib/Utils/signal.js +218 -195
  102. package/lib/Utils/stanza-ack.js +31 -29
  103. package/lib/Utils/sticker.d.ts +17 -0
  104. package/lib/Utils/sticker.js +145 -0
  105. package/lib/Utils/sync-action-utils.js +50 -45
  106. package/lib/Utils/tc-token-utils.js +137 -139
  107. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  108. package/lib/Utils/validate-connection.js +218 -202
  109. package/lib/Utils/view-once-cache.d.ts +9 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +22 -0
  112. package/lib/WABinary/constants.js +1302 -1299
  113. package/lib/WABinary/decode.js +343 -262
  114. package/lib/WABinary/encode.js +12 -4
  115. package/lib/WABinary/generic-utils.js +223 -187
  116. package/lib/WABinary/index.js +33 -6
  117. package/lib/WABinary/jid-utils.js +351 -88
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.js +12 -9
  120. package/lib/WAM/constants.js +39486 -22853
  121. package/lib/WAM/encode.js +132 -140
  122. package/lib/WAM/index.js +31 -4
  123. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -51
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -53
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -26
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  129. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  131. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -37
  133. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -24
  135. package/lib/WAUSync/Protocols/index.js +39 -6
  136. package/lib/WAUSync/USyncQuery.js +132 -97
  137. package/lib/WAUSync/USyncUser.js +49 -30
  138. package/lib/WAUSync/index.js +31 -4
  139. package/lib/antiban.js +4637 -0
  140. package/lib/index.js +48 -15
  141. package/package.json +55 -92
  142. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  143. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  144. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -1,198 +1,604 @@
1
- import * as WAProto_1 from "../../WAProto/index.js";
2
- import * as Defaults_1 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
- import KeyedDB from "./keyed-db.js";
1
+ 'use strict'
9
2
 
10
- const waChatKey = (pin) => ({
11
- key: (c) =>
12
- (pin ? (c.pinned ? "1" : "0") : "") +
13
- (c.archived ? "0" : "1") +
14
- (c.conversationTimestamp
15
- ? c.conversationTimestamp.toString(16).padStart(8, "0")
16
- : "") +
17
- c.id,
18
- compare: (k1, k2) => k2.localeCompare(k1)
19
- });
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod }
7
+ }
20
8
 
21
- export const waMessageID = (m) => m.key.id || "";
9
+ Object.defineProperty(exports, '__esModule', { value: true })
22
10
 
23
- export const waLabelAssociationKey = {
24
- key: (la) =>
25
- la.type === LabelAssociationType.Chat
26
- ? la.chatId + la.labelId
27
- : la.chatId + la.messageId + la.labelId,
28
- compare: (k1, k2) => k2.localeCompare(k1)
29
- };
11
+ const WAProto_1 = require('../../WAProto')
12
+ const Defaults_1 = require('../Defaults')
13
+ const LabelAssociation_1 = require('../Types/LabelAssociation')
14
+ const Utils_1 = require('../Utils')
15
+ const WABinary_1 = require('../WABinary')
16
+ const Store_1 = require('./make-ordered-dictionary')
17
+ const object_repository_1 = require('./object-repository')
30
18
 
31
- const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
19
+ const waChatKey = pin => ({
20
+ key: c =>
21
+ (pin ? (c.pinned ? '1' : '0') : '') +
22
+ (c.archived ? '0' : '1') +
23
+ (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') +
24
+ c.id,
25
+ compare: (k1, k2) => k2.localeCompare(k1)
26
+ })
32
27
 
33
- export default function makeInMemoryStore(config) {
34
- const socket = config.socket;
35
- const chatKey = config.chatKey || waChatKey(true);
36
- const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
37
- const logger =
38
- config.logger ||
39
- Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
40
- stream: "in-mem-store"
41
- });
28
+ const waMessageID = m => m.key.id || ''
42
29
 
43
- const chats = new KeyedDB(chatKey.compare, chatKey.key);
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.compare, labelAssociationKey.key);
30
+ const waLabelAssociationKey = {
31
+ key: la =>
32
+ la.type === LabelAssociation_1.LabelAssociationType.Chat
33
+ ? la.chatId + la.labelId
34
+ : la.chatId + la.messageId + la.labelId,
35
+ compare: (k1, k2) => k2.localeCompare(k1)
36
+ }
51
37
 
52
- const assertMessageList = (jid) => {
53
- if (!messages[jid]) messages[jid] = makeMessagesDictionary();
54
- return messages[jid];
55
- };
38
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
56
39
 
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] = { ...(contacts[contact.id] || {}), ...contact };
62
- }
63
- return oldContacts;
64
- };
40
+ const ENCRYPTED_STORE_MARKER = 'xazbails-store-v1'
65
41
 
66
- const labelsUpsert = (newLabels) => {
67
- for (const label of newLabels) labels.upsertById(label.id, label);
68
- };
42
+ const deriveStoreKey = secret => {
43
+ const { createHash } = require('crypto')
44
+ return createHash('sha256').update(String(secret)).digest()
45
+ }
69
46
 
70
- const bind = (ev) => {
71
- ev.on("connection.update", (update) => Object.assign(state, update));
47
+ const encryptStoreJSON = (jsonStr, secret) => {
48
+ const { createCipheriv, randomBytes } = require('crypto')
49
+ const key = deriveStoreKey(secret)
50
+ const iv = randomBytes(12)
51
+ const cipher = createCipheriv('aes-256-gcm', key, iv)
52
+ const encrypted = Buffer.concat([cipher.update(jsonStr, 'utf-8'), cipher.final()])
53
+ const authTag = cipher.getAuthTag()
54
+ return JSON.stringify({
55
+ marker: ENCRYPTED_STORE_MARKER,
56
+ iv: iv.toString('base64'),
57
+ authTag: authTag.toString('base64'),
58
+ data: encrypted.toString('base64')
59
+ })
60
+ }
72
61
 
73
- ev.on("messaging-history.set", ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
74
- if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) return;
75
- if (isLatest) {
76
- chats.clear();
77
- for (const id in messages) delete messages[id];
78
- }
79
- chats.insertIfAbsent(...newChats);
80
- const oldContacts = contactsUpsert(newContacts);
81
- if (isLatest) for (const jid of oldContacts) delete contacts[jid];
82
- for (const msg of newMessages) {
83
- const jid = msg.key.remoteJid;
84
- const list = assertMessageList(jid);
85
- list.upsert(msg, "prepend");
86
- }
87
- });
62
+ const decryptStoreJSON = (fileStr, secret) => {
63
+ const parsed = JSON.parse(fileStr)
64
+ if (parsed.marker !== ENCRYPTED_STORE_MARKER) {
65
+ // not an encrypted store file -- assume it's already plain JSON
66
+ return fileStr
67
+ }
68
+ const { createDecipheriv } = require('crypto')
69
+ const key = deriveStoreKey(secret)
70
+ const iv = Buffer.from(parsed.iv, 'base64')
71
+ const authTag = Buffer.from(parsed.authTag, 'base64')
72
+ const decipher = createDecipheriv('aes-256-gcm', key, iv)
73
+ decipher.setAuthTag(authTag)
74
+ const decrypted = Buffer.concat([decipher.update(Buffer.from(parsed.data, 'base64')), decipher.final()])
75
+ return decrypted.toString('utf-8')
76
+ }
88
77
 
89
- ev.on("contacts.upsert", contactsUpsert);
78
+ const makeInMemoryStore = config => {
79
+ const socket = config.socket
80
+ const chatKey = config.chatKey || waChatKey(true)
81
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
82
+ const logger =
83
+ config.logger ||
84
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
85
+ stream: 'in-mem-store'
86
+ })
87
+ const KeyedDB = require('@adiwajshing/keyed-db').default
88
+ const chats = new KeyedDB(chatKey, c => c.id)
89
+ const messages = {}
90
+ const contacts = {}
91
+ const groupMetadata = {}
92
+ const presences = {}
93
+ const state = { connection: 'close' }
94
+ const labels = new object_repository_1.ObjectRepository()
95
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
96
+ const maxMessagesPerChat = config.maxMessagesPerChat
97
+ const trimMessagesIfNeeded = jid => {
98
+ if (!maxMessagesPerChat) return
99
+ const list = messages[jid]
100
+ if (!list || list.array.length <= maxMessagesPerChat) return
101
+ while (list.array.length > maxMessagesPerChat) {
102
+ let oldest = list.array[0]
103
+ for (const m of list.array) {
104
+ if ((m.messageTimestamp || 0) < (oldest.messageTimestamp || 0)) oldest = m
105
+ }
106
+ list.remove(oldest)
107
+ }
108
+ }
109
+ const assertMessageList = jid => {
110
+ if (!messages[jid]) {
111
+ messages[jid] = makeMessagesDictionary()
112
+ }
113
+ return messages[jid]
114
+ }
115
+ const contactsUpsert = newContacts => {
116
+ const oldContacts = new Set(Object.keys(contacts))
117
+ for (const contact of newContacts) {
118
+ oldContacts.delete(contact.id)
119
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
120
+ }
121
+ return oldContacts
122
+ }
123
+ const labelsUpsert = newLabels => {
124
+ for (const label of newLabels) {
125
+ labels.upsertById(label.id, label)
126
+ }
127
+ }
128
+ /**
129
+ * binds to a BaileysEventEmitter.
130
+ * It listens to all events and constructs a state that you can query accurate data from.
131
+ * Eg. can use the store to fetch chats, contacts, messages etc.
132
+ * @param ev typically the event emitter from the socket connection
133
+ */
134
+ const bind = ev => {
135
+ ev.on('connection.update', update => {
136
+ Object.assign(state, update)
137
+ })
138
+ ev.on(
139
+ 'messaging-history.set',
140
+ ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
141
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
142
+ return // FOR NOW,
143
+ //TODO: HANDLE
144
+ }
145
+ if (isLatest) {
146
+ chats.clear()
147
+ for (const id in messages) {
148
+ delete messages[id]
149
+ }
150
+ }
151
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
152
+ logger.debug({ chatsAdded }, 'synced chats')
153
+ const oldContacts = contactsUpsert(newContacts)
154
+ if (isLatest) {
155
+ for (const jid of oldContacts) {
156
+ delete contacts[jid]
157
+ }
158
+ }
159
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
160
+ for (const msg of newMessages) {
161
+ const jid = msg.key.remoteJid
162
+ const list = assertMessageList(jid)
163
+ list.upsert(msg, 'prepend')
164
+ trimMessagesIfNeeded(jid)
165
+ }
166
+ logger.debug({ messages: newMessages.length }, 'synced messages')
167
+ }
168
+ )
169
+ ev.on('contacts.upsert', contacts => {
170
+ contactsUpsert(contacts)
171
+ })
172
+ ev.on('contacts.update', async updates => {
173
+ for (const update of updates) {
174
+ let contact
175
+ if (contacts[update.id]) {
176
+ contact = contacts[update.id]
177
+ } else {
178
+ const contactHashes = await Promise.all(
179
+ Object.keys(contacts).map(async contactId => {
180
+ const { user } = WABinary_1.jidDecode(contactId)
181
+ return [
182
+ contactId,
183
+ (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)
184
+ ]
185
+ })
186
+ )
187
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
188
+ }
189
+ if (contact) {
190
+ if (update.imgUrl === 'changed') {
191
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
192
+ } else if (update.imgUrl === 'removed') {
193
+ delete contact.imgUrl
194
+ }
195
+ } else {
196
+ return logger.debug({ update }, 'got update for non-existant contact')
197
+ }
198
+ Object.assign(contacts[contact.id], contact)
199
+ }
200
+ })
201
+ ev.on('chats.upsert', newChats => {
202
+ chats.upsert(...newChats)
203
+ })
204
+ ev.on('chats.update', updates => {
205
+ for (let update of updates) {
206
+ const result = chats.update(update.id, chat => {
207
+ if (update.unreadCount > 0) {
208
+ update = { ...update }
209
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
210
+ }
211
+ Object.assign(chat, update)
212
+ })
213
+ if (!result) {
214
+ logger.debug({ update }, 'got update for non-existant chat')
215
+ }
216
+ }
217
+ })
218
+ ev.on('labels.edit', label => {
219
+ if (label.deleted) {
220
+ return labels.deleteById(label.id)
221
+ }
222
+ // WhatsApp can store only up to 20 labels
223
+ if (labels.count() < 20) {
224
+ return labels.upsertById(label.id, label)
225
+ }
226
+ logger.error('Labels count exceed')
227
+ })
228
+ ev.on('labels.association', ({ type, association }) => {
229
+ switch (type) {
230
+ case 'add':
231
+ labelAssociations.upsert(association)
232
+ break
233
+ case 'remove':
234
+ labelAssociations.delete(association)
235
+ break
236
+ default:
237
+ logger.error({ type }, 'unknown label association operation type')
238
+ }
239
+ })
240
+ ev.on('presence.update', ({ id, presences: update }) => {
241
+ presences[id] = presences[id] || {}
242
+ Object.assign(presences[id], update)
243
+ })
244
+ ev.on('chats.delete', deletions => {
245
+ for (const item of deletions) {
246
+ if (chats.get(item)) {
247
+ chats.deleteById(item)
248
+ }
249
+ }
250
+ })
251
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
252
+ switch (type) {
253
+ case 'append':
254
+ case 'notify':
255
+ for (const msg of newMessages) {
256
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
257
+ const list = assertMessageList(jid)
258
+ list.upsert(msg, 'append')
259
+ trimMessagesIfNeeded(jid)
260
+ if (type === 'notify' && !chats.get(jid)) {
261
+ ev.emit('chats.upsert', [
262
+ {
263
+ id: jid,
264
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
265
+ unreadCount: 1
266
+ }
267
+ ])
268
+ }
269
+ }
270
+ break
271
+ }
272
+ })
273
+ ev.on('messages.update', updates => {
274
+ for (const { update, key } of updates) {
275
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
276
+ if (update?.status) {
277
+ const listStatus = list.get(key.id)?.status
278
+ if (listStatus && update?.status <= listStatus) {
279
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
280
+ delete update.status
281
+ logger.debug({ update }, 'new update object')
282
+ }
283
+ }
284
+ const result = list.updateAssign(key.id, update)
285
+ if (!result) {
286
+ logger.debug({ update }, 'got update for non-existent message')
287
+ }
288
+ }
289
+ })
290
+ ev.on('messages.delete', item => {
291
+ if ('all' in item) {
292
+ const list = messages[item.jid]
293
+ list?.clear()
294
+ } else {
295
+ const jid = item.keys[0].remoteJid
296
+ const list = messages[jid]
297
+ if (list) {
298
+ const idSet = new Set(item.keys.map(k => k.id))
299
+ list.filter(m => !idSet.has(m.key.id))
300
+ }
301
+ }
302
+ })
303
+ ev.on('groups.update', updates => {
304
+ for (const update of updates) {
305
+ const id = update.id
306
+ if (groupMetadata[id]) {
307
+ Object.assign(groupMetadata[id], update)
308
+ } else {
309
+ logger.debug({ update }, 'got update for non-existant group metadata')
310
+ }
311
+ }
312
+ })
313
+ ev.on('group-participants.update', ({ id, participants, action }) => {
314
+ const metadata = groupMetadata[id]
315
+ if (metadata) {
316
+ switch (action) {
317
+ case 'add':
318
+ metadata.participants.push(
319
+ ...participants.map(id => ({
320
+ id,
321
+ isAdmin: false,
322
+ isSuperAdmin: false
323
+ }))
324
+ )
325
+ break
326
+ case 'demote':
327
+ case 'promote':
328
+ for (const participant of metadata.participants) {
329
+ if (participants.includes(participant.id)) {
330
+ participant.isAdmin = action === 'promote'
331
+ }
332
+ }
333
+ break
334
+ case 'remove':
335
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
336
+ break
337
+ }
338
+ }
339
+ })
340
+ ev.on('message-receipt.update', updates => {
341
+ for (const { key, receipt } of updates) {
342
+ const obj = messages[key.remoteJid]
343
+ const msg = obj?.get(key.id)
344
+ if (msg) {
345
+ Utils_1.updateMessageWithReceipt(msg, receipt)
346
+ }
347
+ }
348
+ })
349
+ ev.on('messages.reaction', reactions => {
350
+ for (const { key, reaction } of reactions) {
351
+ const obj = messages[key.remoteJid]
352
+ const msg = obj?.get(key.id)
353
+ if (msg) {
354
+ Utils_1.updateMessageWithReaction(msg, reaction)
355
+ }
356
+ }
357
+ })
358
+ ev.on('settings.update', ({ setting, value }) => {
359
+ state.settings = state.settings || {}
360
+ state.settings[setting] = value
361
+ })
362
+ ev.on('labels.reorder', ({ labelIds }) => {
363
+ let order = 0
364
+ for (const id of labelIds) {
365
+ const label = labels.findById(id)
366
+ if (label) {
367
+ labels.upsertById(id, { ...label, order: order++ })
368
+ }
369
+ order++
370
+ }
371
+ })
372
+ ev.on('call.scheduled', ({ messageKey, scheduledCall, chatId }) => {
373
+ state.scheduledCalls = state.scheduledCalls || {}
374
+ state.scheduledCalls[messageKey.id] = { key: messageKey, scheduledCall, chatId }
375
+ })
376
+ ev.on('call.schedule-cancelled', ({ messageKey, editedCallKey }) => {
377
+ if (state.scheduledCalls?.[editedCallKey?.id]) {
378
+ delete state.scheduledCalls[editedCallKey.id]
379
+ }
380
+ })
381
+ ev.on('payment.split', ({ messageKey, splitPayment }) => {
382
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(messageKey.remoteJid))
383
+ const msg = list?.get(messageKey.id)
384
+ if (msg) {
385
+ msg.splitPayment = splitPayment
386
+ }
387
+ })
388
+ ev.on('message.comment', ({ commentKey, comment, targetKey }) => {
389
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(targetKey.remoteJid))
390
+ const msg = list?.get(targetKey.id)
391
+ if (msg) {
392
+ msg.commentCount = (msg.commentCount || 0) + 1
393
+ }
394
+ })
395
+ ev.on('poll.add-option', ({ pollKey, addedOption }) => {
396
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(pollKey.remoteJid))
397
+ const msg = list?.get(pollKey.id)
398
+ if (msg?.message) {
399
+ const poll =
400
+ msg.message.pollCreationMessage ||
401
+ msg.message.pollCreationMessageV3 ||
402
+ msg.message.pollCreationMessageV5 ||
403
+ msg.message.pollCreationMessageV6
404
+ if (poll && addedOption) {
405
+ poll.options = [...(poll.options || []), addedOption]
406
+ }
407
+ }
408
+ })
409
+ ev.on('chats.lock', ({ id, locked }) => {
410
+ const result = chats.update(id, chat => {
411
+ chat.locked = locked
412
+ })
413
+ if (!result) logger.debug({ id }, 'got chats.lock for non-existent chat')
414
+ })
415
+ ev.on('messaging-history.status', ({ syncType, status }) => {
416
+ state.historySyncStatus = state.historySyncStatus || {}
417
+ state.historySyncStatus[syncType] = status
418
+ })
419
+ }
420
+ const toJSON = () => ({
421
+ chats,
422
+ contacts,
423
+ messages,
424
+ labels,
425
+ labelAssociations,
426
+ groupMetadata,
427
+ presences,
428
+ state
429
+ })
430
+ const fromJSON = json => {
431
+ chats.upsert(...json.chats)
432
+ labelAssociations.upsert(...(json.labelAssociations || []))
433
+ contactsUpsert(Object.values(json.contacts))
434
+ labelsUpsert(Object.values(json.labels || {}))
435
+ for (const jid in json.messages) {
436
+ const list = assertMessageList(jid)
437
+ for (const msg of json.messages[jid]) {
438
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
439
+ }
440
+ trimMessagesIfNeeded(jid)
441
+ }
442
+ if (json.groupMetadata) {
443
+ Object.assign(groupMetadata, json.groupMetadata)
444
+ }
445
+ if (json.presences) {
446
+ Object.assign(presences, json.presences)
447
+ }
448
+ if (json.state) {
449
+ Object.assign(state, json.state)
450
+ }
451
+ }
452
+ return {
453
+ chats,
454
+ contacts,
455
+ messages,
456
+ groupMetadata,
457
+ state,
458
+ presences,
459
+ labels,
460
+ labelAssociations,
461
+ bind,
462
+ /** loads messages from the store, if not found -- uses the legacy connection */
463
+ loadMessages: async (jid, count, cursor) => {
464
+ const list = assertMessageList(jid)
465
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
466
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
467
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
468
+ let messages
469
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
470
+ if (cursorValue) {
471
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
472
+ messages = list.array.slice(0, msgIdx)
473
+ } else {
474
+ messages = list.array
475
+ }
476
+ const diff = count - messages.length
477
+ if (diff < 0) {
478
+ messages = messages.slice(-count) // get the last X messages
479
+ }
480
+ } else {
481
+ messages = []
482
+ }
483
+ return messages
484
+ },
485
+ /**
486
+ * Get all available labels for profile
487
+ *
488
+ * Keep in mind that the list is formed from predefined tags and tags
489
+ * that were "caught" during their editing.
490
+ */
491
+ getLabels: () => {
492
+ return labels
493
+ },
494
+ /**
495
+ * Get labels for chat
496
+ *
497
+ * @returns Label IDs
498
+ **/
499
+ getChatLabels: chatId => {
500
+ return labelAssociations.filter(la => la.chatId === chatId).all()
501
+ },
502
+ /**
503
+ * Get labels for message
504
+ *
505
+ * @returns Label IDs
506
+ **/
507
+ getMessageLabels: messageId => {
508
+ const associations = labelAssociations.filter(la => la.messageId === messageId).all()
509
+ return associations.map(({ labelId }) => labelId)
510
+ },
511
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
512
+ mostRecentMessage: async jid => {
513
+ const message = messages[jid]?.array.slice(-1)[0]
514
+ return message
515
+ },
516
+ fetchImageUrl: async (jid, suki) => {
517
+ const contact = contacts[jid]
518
+ if (!contact) {
519
+ return suki?.profilePictureUrl(jid)
520
+ }
521
+ if (typeof contact.imgUrl === 'undefined') {
522
+ contact.imgUrl = await suki?.profilePictureUrl(jid)
523
+ }
524
+ return contact.imgUrl
525
+ },
526
+ fetchGroupMetadata: async (jid, suki) => {
527
+ if (!groupMetadata[jid]) {
528
+ const metadata = await suki?.groupMetadata(jid)
529
+ if (metadata) {
530
+ groupMetadata[jid] = metadata
531
+ }
532
+ }
533
+ return groupMetadata[jid]
534
+ },
535
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
536
+ // if(!groupMetadata[jid]) {
537
+ // const metadata = await sock?.getBroadcastListInfo(jid)
538
+ // if(metadata) {
539
+ // groupMetadata[jid] = metadata
540
+ // }
541
+ // }
542
+ // return groupMetadata[jid]
543
+ // },
544
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
545
+ const list = messages[remoteJid]
546
+ const msg = list?.get(id)
547
+ return msg?.userReceipt
548
+ },
549
+ toJSON,
550
+ fromJSON,
551
+ writeToFile: path => {
552
+ // require fs here so that in case "fs" is not available -- the app does not crash
553
+ const { writeFileSync } = require('fs')
554
+ const jsonStr = JSON.stringify(toJSON())
555
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr)
556
+ },
557
+ readFromFile: path => {
558
+ // require fs here so that in case "fs" is not available -- the app does not crash
559
+ const { readFileSync, existsSync } = require('fs')
560
+ if (existsSync(path)) {
561
+ logger.debug({ path }, 'reading from file')
562
+ const fileStr = readFileSync(path, { encoding: 'utf-8' })
563
+ const jsonStr = config.encryptionKey ? decryptStoreJSON(fileStr, config.encryptionKey) : fileStr
564
+ const json = JSON.parse(jsonStr)
565
+ fromJSON(json)
566
+ }
567
+ },
568
+ /**
569
+ * Periodically writes the store to `path` every `intervalMs` (default 30s),
570
+ * and does one final write when the bound socket closes (if `registerSocketEndHandler`
571
+ * is available on it). Returns a function that stops the auto-save.
572
+ */
573
+ startAutoSave: (path, intervalMs = 30000) => {
574
+ const timer = setInterval(() => {
575
+ try {
576
+ const { writeFileSync } = require('fs')
577
+ const jsonStr = JSON.stringify(toJSON())
578
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr)
579
+ } catch (error) {
580
+ logger.warn({ error, path }, 'failed to auto-save store')
581
+ }
582
+ }, intervalMs)
583
+ if (timer.unref) timer.unref()
584
+ if (socket && typeof socket.registerSocketEndHandler === 'function') {
585
+ socket.registerSocketEndHandler(async () => {
586
+ try {
587
+ const { writeFileSync } = require('fs')
588
+ const jsonStr = JSON.stringify(toJSON())
589
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr)
590
+ logger.debug({ path }, 'final store flush on socket end')
591
+ } catch (error) {
592
+ logger.warn({ error, path }, 'failed to flush store on socket end')
593
+ }
594
+ })
595
+ }
596
+ return () => clearInterval(timer)
597
+ }
598
+ }
599
+ }
90
600
 
91
- ev.on("contacts.update", async (updates) => {
92
- for (const update of updates) {
93
- const contact = contacts[update.id];
94
- if (contact) Object.assign(contact, update);
95
- }
96
- });
97
-
98
- ev.on("chats.upsert", (newChats) => chats.upsert(...newChats));
99
-
100
- ev.on("chats.update", (updates) => {
101
- for (let update of updates) {
102
- chats.update(update.id, (chat) => Object.assign(chat, update));
103
- }
104
- });
105
-
106
- ev.on("labels.edit", (label) => {
107
- if (label.deleted) return labels.deleteById(label.id);
108
- if (labels.count() < 20) labels.upsertById(label.id, label);
109
- });
110
-
111
- ev.on("labels.association", ({ type, association }) => {
112
- if (type === "add") labelAssociations.upsert(association);
113
- if (type === "remove") labelAssociations.delete(association);
114
- });
115
-
116
- ev.on("presence.update", ({ id, presences: update }) => {
117
- presences[id] = presences[id] || {};
118
- Object.assign(presences[id], update);
119
- });
120
-
121
- ev.on("chats.delete", (deletions) => {
122
- for (const item of deletions) chats.deleteById(item);
123
- });
124
-
125
- ev.on("messages.upsert", ({ messages: newMessages, type }) => {
126
- if (type !== "append" && type !== "notify") return;
127
- for (const msg of newMessages) {
128
- const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
129
- const list = assertMessageList(jid);
130
- list.upsert(msg, "append");
131
- if (type === "notify" && !chats.get(jid))
132
- ev.emit("chats.upsert", [
133
- {
134
- id: jid,
135
- conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
136
- unreadCount: 1
137
- }
138
- ]);
139
- }
140
- });
141
-
142
- ev.on("messages.update", (updates) => {
143
- for (const { update, key } of updates) {
144
- const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid));
145
- list.updateAssign(key.id, update);
146
- }
147
- });
148
-
149
- ev.on("messages.delete", (item) => {
150
- if ("all" in item) messages[item.jid]?.clear();
151
- else {
152
- const jid = item.keys[0].remoteJid;
153
- const list = messages[jid];
154
- if (list) {
155
- const idSet = new Set(item.keys.map((k) => k.id));
156
- list.filter((m) => !idSet.has(m.key.id));
157
- }
158
- }
159
- });
160
- };
161
-
162
- const toJSON = () => ({
163
- chats,
164
- contacts,
165
- messages,
166
- labels,
167
- labelAssociations
168
- });
169
-
170
- const fromJSON = (json) => {
171
- chats.upsert(...json.chats);
172
- labelAssociations.upsert(...(json.labelAssociations || []));
173
- contactsUpsert(Object.values(json.contacts));
174
- labelsUpsert(Object.values(json.labels || {}));
175
- for (const jid in json.messages) {
176
- const list = assertMessageList(jid);
177
- for (const msg of json.messages[jid])
178
- list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), "append");
179
- }
180
- };
181
- const loadMessage = async (jid, id) => {
182
- return messages[jid]?.get(id)
183
- }
184
- return {
185
- chats,
186
- contacts,
187
- messages,
188
- groupMetadata,
189
- state,
190
- presences,
191
- labels,
192
- labelAssociations,
193
- bind,
194
- toJSON,
195
- fromJSON,
196
- loadMessage
197
- };
198
- }
601
+ exports.waChatKey = waChatKey
602
+ exports.waMessageID = waMessageID
603
+ exports.waLabelAssociationKey = waLabelAssociationKey
604
+ exports.makeInMemoryStore = makeInMemoryStore