@badzz88/baileys 8.5.7 → 8.5.9

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 (142) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +284 -264
  3. package/WAProto/index.js +5 -5
  4. package/engine-requirements.js +7 -15
  5. package/lib/Defaults/index.js +130 -187
  6. package/lib/Signal/Group/ciphertext-message.js +11 -14
  7. package/lib/Signal/Group/group-session-builder.js +29 -91
  8. package/lib/Signal/Group/group_cipher.js +81 -88
  9. package/lib/Signal/Group/index.js +12 -136
  10. package/lib/Signal/Group/keyhelper.js +15 -70
  11. package/lib/Signal/Group/sender-chain-key.js +25 -31
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -65
  13. package/lib/Signal/Group/sender-key-message.js +65 -68
  14. package/lib/Signal/Group/sender-key-name.js +41 -43
  15. package/lib/Signal/Group/sender-key-record.js +40 -43
  16. package/lib/Signal/Group/sender-key-state.js +83 -96
  17. package/lib/Signal/Group/sender-message-key.js +25 -29
  18. package/lib/Signal/libsignal.js +425 -453
  19. package/lib/Signal/lid-mapping.js +276 -259
  20. package/lib/Socket/Client/index.js +3 -30
  21. package/lib/Socket/Client/types.js +10 -12
  22. package/lib/Socket/Client/websocket.js +53 -61
  23. package/lib/Socket/business.js +379 -422
  24. package/lib/Socket/chats.js +1193 -1816
  25. package/lib/Socket/communities.js +431 -549
  26. package/lib/Socket/graphql.js +672 -612
  27. package/lib/Socket/groups.js +374 -764
  28. package/lib/Socket/index.js +17 -38
  29. package/lib/Socket/interop.js +417 -503
  30. package/lib/Socket/messages-recv.js +1915 -2441
  31. package/lib/Socket/messages-send.js +1213 -1630
  32. package/lib/Socket/mex.js +9 -15
  33. package/lib/Socket/newsletter.js +746 -808
  34. package/lib/Socket/privacy.js +310 -441
  35. package/lib/Socket/socket.js +1025 -1022
  36. package/lib/Socket/username.js +8 -15
  37. package/lib/Store/index.js +10 -36
  38. package/lib/Store/make-cache-manager-store.js +80 -85
  39. package/lib/Store/make-in-memory-store.js +231 -591
  40. package/lib/Store/make-ordered-dictionary.js +72 -78
  41. package/lib/Store/object-repository.js +28 -25
  42. package/lib/Types/Auth.js +2 -38
  43. package/lib/Types/Bussines.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +8 -4
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +11 -95
  52. package/lib/Types/Mex.js +111 -112
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +3 -2
  56. package/lib/Types/State.js +56 -70
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +26 -55
  59. package/lib/Utils/auth-utils.js +288 -292
  60. package/lib/Utils/browser-utils.js +47 -113
  61. package/lib/Utils/business.js +224 -240
  62. package/lib/Utils/chat-utils.js +869 -1205
  63. package/lib/Utils/companion-reg-client-utils.js +34 -41
  64. package/lib/Utils/crypto.js +107 -144
  65. package/lib/Utils/decode-wa-message.js +308 -518
  66. package/lib/Utils/event-buffer.js +611 -596
  67. package/lib/Utils/generics.js +355 -515
  68. package/lib/Utils/history.js +134 -244
  69. package/lib/Utils/identity-change-handler.js +49 -51
  70. package/lib/Utils/index.js +23 -57
  71. package/lib/Utils/link-preview.js +77 -135
  72. package/lib/Utils/logger.js +3 -9
  73. package/lib/Utils/lt-hash.js +6 -37
  74. package/lib/Utils/make-mutex.js +33 -36
  75. package/lib/Utils/message-composer.js +233 -439
  76. package/lib/Utils/message-retry-manager.js +260 -265
  77. package/lib/Utils/messages-media.js +829 -855
  78. package/lib/Utils/messages.js +961 -2528
  79. package/lib/Utils/noise-handler.js +200 -195
  80. package/lib/Utils/offline-node-processor.js +33 -35
  81. package/lib/Utils/pre-key-manager.js +102 -103
  82. package/lib/Utils/process-message.js +560 -978
  83. package/lib/Utils/reporting-utils.js +253 -257
  84. package/lib/Utils/signal.js +195 -218
  85. package/lib/Utils/stanza-ack.js +29 -31
  86. package/lib/Utils/sticker.js +109 -144
  87. package/lib/Utils/sync-action-utils.js +45 -50
  88. package/lib/Utils/tc-token-utils.js +139 -137
  89. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  90. package/lib/Utils/validate-connection.js +202 -218
  91. package/lib/WABinary/constants.js +1299 -1302
  92. package/lib/WABinary/decode.js +262 -343
  93. package/lib/WABinary/encode.js +4 -12
  94. package/lib/WABinary/generic-utils.js +187 -223
  95. package/lib/WABinary/index.js +6 -33
  96. package/lib/WABinary/jid-utils.js +88 -351
  97. package/lib/WABinary/types.js +2 -2
  98. package/lib/WAM/BinaryInfo.js +9 -12
  99. package/lib/WAM/constants.js +22853 -39486
  100. package/lib/WAM/encode.js +140 -132
  101. package/lib/WAM/index.js +4 -31
  102. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +21 -23
  103. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +9 -9
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -7
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +10 -10
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +7 -7
  107. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +11 -12
  108. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +4 -5
  109. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +7 -7
  110. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +7 -8
  111. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -7
  112. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +8 -8
  113. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +7 -7
  114. package/lib/WAUSync/Protocols/index.js +12 -39
  115. package/lib/WAUSync/USyncQuery.js +67 -49
  116. package/lib/WAUSync/USyncUser.js +11 -5
  117. package/lib/WAUSync/index.js +3 -31
  118. package/lib/index.js +15 -48
  119. package/package.json +129 -99
  120. package/LICENSE +0 -21
  121. package/lib/Defaults/phonenumber-mcc.json +0 -223
  122. package/lib/Socket/aigroups.js +0 -240
  123. package/lib/Socket/interactive-handler.js +0 -522
  124. package/lib/Socket/managed-account.js +0 -183
  125. package/lib/Socket/registration.js +0 -427
  126. package/lib/Socket/text-router.js +0 -83
  127. package/lib/Types/Newsletter.js +0 -121
  128. package/lib/Utils/command-loader.d.ts +0 -31
  129. package/lib/Utils/command-loader.js +0 -100
  130. package/lib/Utils/consumer-application.js +0 -107
  131. package/lib/Utils/curve25519-js.js +0 -275
  132. package/lib/Utils/group-history.js +0 -60
  133. package/lib/Utils/jid-display-normalization.js +0 -218
  134. package/lib/Utils/meta-ai-msmsg.js +0 -262
  135. package/lib/Utils/native-bridge.js +0 -82
  136. package/lib/Utils/session-pool.d.ts +0 -16
  137. package/lib/Utils/session-pool.js +0 -94
  138. package/lib/Utils/sticker.d.ts +0 -17
  139. package/lib/Utils/view-once-cache.d.ts +0 -9
  140. package/lib/Utils/view-once-cache.js +0 -79
  141. package/lib/Utils/voip-rekey.js +0 -22
  142. package/lib/antiban.js +0 -4637
@@ -1,604 +1,244 @@
1
- 'use strict'
1
+ import fs from "fs";
2
+ import * as WAProto_1 from "../../WAProto/index.js";
3
+ import * as Defaults_1 from "../Defaults/index.js";
4
+ import { LabelAssociationType } from "../Types/LabelAssociation.js";
5
+ import * as Utils_1 from "../Utils/index.js";
6
+ import * as WABinary_1 from "../WABinary/index.js";
7
+ import makeOrderedDictionary from "./make-ordered-dictionary.js";
8
+ import { ObjectRepository } from "./object-repository.js";
9
+ import KeyedDB from "./keyed-db.js";
2
10
 
3
- var __importDefault =
4
- (this && this.__importDefault) ||
5
- function (mod) {
6
- return mod && mod.__esModule ? mod : { default: mod }
7
- }
11
+ const waChatKey = (pin) => ({
12
+ key: (c) =>
13
+ (pin ? (c.pinned ? "1" : "0") : "") +
14
+ (c.archived ? "0" : "1") +
15
+ (c.conversationTimestamp
16
+ ? c.conversationTimestamp.toString(16).padStart(8, "0")
17
+ : "") +
18
+ c.id,
19
+ compare: (k1, k2) => k2.localeCompare(k1)
20
+ });
8
21
 
9
- Object.defineProperty(exports, '__esModule', { value: true })
22
+ export const waMessageID = (m) => m.key.id || "";
10
23
 
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')
24
+ export const waLabelAssociationKey = {
25
+ key: (la) =>
26
+ la.type === LabelAssociationType.Chat
27
+ ? la.chatId + la.labelId
28
+ : la.chatId + la.messageId + la.labelId,
29
+ compare: (k1, k2) => k2.localeCompare(k1)
30
+ };
18
31
 
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
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
27
33
 
28
- const waMessageID = m => m.key.id || ''
34
+ export default function makeInMemoryStore(config) {
35
+ const socket = config.socket;
36
+ const chatKey = config.chatKey || waChatKey(true);
37
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
38
+ const logger =
39
+ config.logger ||
40
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
41
+ stream: "in-mem-store"
42
+ });
29
43
 
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
- }
44
+ const chats = new KeyedDB(chatKey.compare, chatKey.key);
45
+ const messages = {};
46
+ const contacts = {};
47
+ const groupMetadata = {};
48
+ const presences = {};
49
+ const state = { connection: "close" };
50
+ const labels = new ObjectRepository();
51
+ const labelAssociations = new KeyedDB(labelAssociationKey.compare, labelAssociationKey.key);
37
52
 
38
- const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
53
+ const assertMessageList = (jid) => {
54
+ if (!messages[jid]) messages[jid] = makeMessagesDictionary();
55
+ return messages[jid];
56
+ };
39
57
 
40
- const ENCRYPTED_STORE_MARKER = 'xazbails-store-v1'
58
+ const contactsUpsert = (newContacts) => {
59
+ const oldContacts = new Set(Object.keys(contacts));
60
+ for (const contact of newContacts) {
61
+ oldContacts.delete(contact.id);
62
+ contacts[contact.id] = { ...(contacts[contact.id] || {}), ...contact };
63
+ }
64
+ return oldContacts;
65
+ };
41
66
 
42
- const deriveStoreKey = secret => {
43
- const { createHash } = require('crypto')
44
- return createHash('sha256').update(String(secret)).digest()
45
- }
67
+ const labelsUpsert = (newLabels) => {
68
+ for (const label of newLabels) labels.upsertById(label.id, label);
69
+ };
46
70
 
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
- }
71
+ const bind = (ev) => {
72
+ ev.on("connection.update", (update) => Object.assign(state, update));
61
73
 
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
- }
74
+ ev.on("messaging-history.set", ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
75
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) return;
76
+ if (isLatest) {
77
+ chats.clear();
78
+ for (const id in messages) delete messages[id];
79
+ }
80
+ chats.insertIfAbsent(...newChats);
81
+ const oldContacts = contactsUpsert(newContacts);
82
+ if (isLatest) for (const jid of oldContacts) delete contacts[jid];
83
+ for (const msg of newMessages) {
84
+ const jid = msg.key.remoteJid;
85
+ const list = assertMessageList(jid);
86
+ list.upsert(msg, "prepend");
87
+ }
88
+ });
77
89
 
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
+ ev.on("contacts.upsert", contactsUpsert);
600
91
 
601
- exports.waChatKey = waChatKey
602
- exports.waMessageID = waMessageID
603
- exports.waLabelAssociationKey = waLabelAssociationKey
604
- exports.makeInMemoryStore = makeInMemoryStore
92
+ ev.on("contacts.update", async (updates) => {
93
+ for (const update of updates) {
94
+ const contact = contacts[update.id];
95
+ if (contact) Object.assign(contact, update);
96
+ }
97
+ });
98
+
99
+ ev.on("chats.upsert", (newChats) => chats.upsert(...newChats));
100
+
101
+ ev.on("chats.update", (updates) => {
102
+ for (let update of updates) {
103
+ chats.update(update.id, (chat) => Object.assign(chat, update));
104
+ }
105
+ });
106
+
107
+ ev.on("labels.edit", (label) => {
108
+ if (label.deleted) return labels.deleteById(label.id);
109
+ if (labels.count() < 20) labels.upsertById(label.id, label);
110
+ });
111
+
112
+ ev.on("labels.association", ({ type, association }) => {
113
+ if (type === "add") labelAssociations.upsert(association);
114
+ if (type === "remove") labelAssociations.delete(association);
115
+ });
116
+
117
+ ev.on("presence.update", ({ id, presences: update }) => {
118
+ presences[id] = presences[id] || {};
119
+ Object.assign(presences[id], update);
120
+ });
121
+
122
+ ev.on("chats.delete", (deletions) => {
123
+ for (const item of deletions) chats.deleteById(item);
124
+ });
125
+
126
+ ev.on("messages.upsert", ({ messages: newMessages, type }) => {
127
+ if (type !== "append" && type !== "notify") return;
128
+ for (const msg of newMessages) {
129
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
130
+ const list = assertMessageList(jid);
131
+ list.upsert(msg, "append");
132
+ if (type === "notify" && !chats.get(jid))
133
+ ev.emit("chats.upsert", [
134
+ {
135
+ id: jid,
136
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
137
+ unreadCount: 1
138
+ }
139
+ ]);
140
+ }
141
+ });
142
+
143
+ ev.on("messages.update", (updates) => {
144
+ for (const { update, key } of updates) {
145
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid));
146
+ list.updateAssign(key.id, update);
147
+ }
148
+ });
149
+
150
+ ev.on("messages.delete", (item) => {
151
+ if ("all" in item) messages[item.jid]?.clear();
152
+ else {
153
+ const jid = item.keys[0].remoteJid;
154
+ const list = messages[jid];
155
+ if (list) {
156
+ const idSet = new Set(item.keys.map((k) => k.id));
157
+ list.filter((m) => !idSet.has(m.key.id));
158
+ }
159
+ }
160
+ });
161
+ };
162
+
163
+ const toJSON = () => ({
164
+ chats,
165
+ contacts,
166
+ messages,
167
+ labels,
168
+ labelAssociations
169
+ });
170
+
171
+ const fromJSON = (json) => {
172
+ chats.upsert(...json.chats);
173
+ labelAssociations.upsert(...(json.labelAssociations || []));
174
+ contactsUpsert(Object.values(json.contacts));
175
+ labelsUpsert(Object.values(json.labels || {}));
176
+ for (const jid in json.messages) {
177
+ const list = assertMessageList(jid);
178
+ for (const msg of json.messages[jid])
179
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), "append");
180
+ }
181
+ };
182
+ const loadMessage = async (jid, id) => {
183
+ return messages[jid]?.get(id)
184
+ }
185
+
186
+ /**
187
+ * Persist the whole store to a JSON file on disk (synchronous, atomic write).
188
+ * Writes to a temp file first then renames, so a crash mid-write can't
189
+ * corrupt the existing store file.
190
+ */
191
+ const writeToFile = (path) => {
192
+ try {
193
+ const tmpPath = `${path}.tmp`;
194
+ fs.writeFileSync(tmpPath, JSON.stringify(toJSON()));
195
+ fs.renameSync(tmpPath, path);
196
+ } catch (err) {
197
+ logger.error({ err }, "failed to write store to file");
198
+ }
199
+ };
200
+
201
+ /**
202
+ * Load store state from a JSON file on disk, if it exists.
203
+ * Safe to call even if the file was never created yet.
204
+ */
205
+ const readFromFile = (path) => {
206
+ if (!fs.existsSync(path)) return;
207
+ try {
208
+ const jsonStr = fs.readFileSync(path, { encoding: "utf-8" });
209
+ const json = JSON.parse(jsonStr);
210
+ fromJSON(json);
211
+ } catch (err) {
212
+ logger.error({ err }, "failed to read store from file");
213
+ }
214
+ };
215
+
216
+ /**
217
+ * Convenience helper: load once from `path` (if present), then keep
218
+ * saving to the same file every `intervalMs` (default 10s).
219
+ * Returns a function to stop the auto-save interval.
220
+ */
221
+ const writeToFileInterval = (path, intervalMs = 10_000) => {
222
+ readFromFile(path);
223
+ const interval = setInterval(() => writeToFile(path), intervalMs);
224
+ return () => clearInterval(interval);
225
+ };
226
+
227
+ return {
228
+ chats,
229
+ contacts,
230
+ messages,
231
+ groupMetadata,
232
+ state,
233
+ presences,
234
+ labels,
235
+ labelAssociations,
236
+ bind,
237
+ toJSON,
238
+ fromJSON,
239
+ loadMessage,
240
+ writeToFile,
241
+ readFromFile,
242
+ writeToFileInterval
243
+ };
244
+ }