@bellaxchuu/flowred 0.8.6

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/LICENSE +21 -0
  2. package/README.md +214 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +190 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +92 -0
  12. package/lib/Signal/Group/group_cipher.js +89 -0
  13. package/lib/Signal/Group/index.js +136 -0
  14. package/lib/Signal/Group/keyhelper.js +73 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-message.js +69 -0
  18. package/lib/Signal/Group/sender-key-name.js +50 -0
  19. package/lib/Signal/Group/sender-key-record.js +44 -0
  20. package/lib/Signal/Group/sender-key-state.js +97 -0
  21. package/lib/Signal/Group/sender-message-key.js +30 -0
  22. package/lib/Signal/libsignal.js +490 -0
  23. package/lib/Signal/lid-mapping.js +262 -0
  24. package/lib/Socket/Client/index.js +30 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +62 -0
  27. package/lib/Socket/aigroups.js +240 -0
  28. package/lib/Socket/business.js +422 -0
  29. package/lib/Socket/chats.js +1816 -0
  30. package/lib/Socket/communities.js +549 -0
  31. package/lib/Socket/graphql.js +656 -0
  32. package/lib/Socket/groups.js +764 -0
  33. package/lib/Socket/index.js +39 -0
  34. package/lib/Socket/interactive-handler.js +522 -0
  35. package/lib/Socket/interop.js +549 -0
  36. package/lib/Socket/luxu.js +387 -0
  37. package/lib/Socket/managed-account.js +183 -0
  38. package/lib/Socket/messages-recv.js +2440 -0
  39. package/lib/Socket/messages-send.js +1853 -0
  40. package/lib/Socket/mex.js +60 -0
  41. package/lib/Socket/newsletter.js +820 -0
  42. package/lib/Socket/privacy.js +449 -0
  43. package/lib/Socket/registration.js +427 -0
  44. package/lib/Socket/socket.js +1092 -0
  45. package/lib/Socket/text-router.js +83 -0
  46. package/lib/Socket/username.js +243 -0
  47. package/lib/Store/index.js +36 -0
  48. package/lib/Store/keyed-db.js +108 -0
  49. package/lib/Store/make-cache-manager-store.js +90 -0
  50. package/lib/Store/make-in-memory-store.js +604 -0
  51. package/lib/Store/make-ordered-dictionary.js +81 -0
  52. package/lib/Store/object-repository.js +29 -0
  53. package/lib/Types/Auth.js +38 -0
  54. package/lib/Types/Bussines.js +2 -0
  55. package/lib/Types/Call.js +2 -0
  56. package/lib/Types/Chat.js +4 -0
  57. package/lib/Types/Contact.js +2 -0
  58. package/lib/Types/Events.js +2 -0
  59. package/lib/Types/GroupMetadata.js +2 -0
  60. package/lib/Types/Label.js +27 -0
  61. package/lib/Types/LabelAssociation.js +9 -0
  62. package/lib/Types/Message.js +95 -0
  63. package/lib/Types/Mex.js +112 -0
  64. package/lib/Types/Newsletter.js +121 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +70 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +55 -0
  71. package/lib/Utils/auth-utils.js +306 -0
  72. package/lib/Utils/browser-utils.js +114 -0
  73. package/lib/Utils/business.js +247 -0
  74. package/lib/Utils/chat-utils.js +1208 -0
  75. package/lib/Utils/command-loader.js +100 -0
  76. package/lib/Utils/companion-reg-client-utils.js +42 -0
  77. package/lib/Utils/consumer-application.js +107 -0
  78. package/lib/Utils/crypto.js +155 -0
  79. package/lib/Utils/curve25519-js.js +275 -0
  80. package/lib/Utils/decode-wa-message.js +560 -0
  81. package/lib/Utils/event-buffer.js +607 -0
  82. package/lib/Utils/generics.js +563 -0
  83. package/lib/Utils/group-history.js +60 -0
  84. package/lib/Utils/history.js +244 -0
  85. package/lib/Utils/identity-change-handler.js +52 -0
  86. package/lib/Utils/index.js +57 -0
  87. package/lib/Utils/jid-display-normalization.js +218 -0
  88. package/lib/Utils/link-preview.js +143 -0
  89. package/lib/Utils/logger.js +9 -0
  90. package/lib/Utils/lt-hash.js +39 -0
  91. package/lib/Utils/make-mutex.js +36 -0
  92. package/lib/Utils/message-composer.js +479 -0
  93. package/lib/Utils/message-retry-manager.js +270 -0
  94. package/lib/Utils/messages-media.js +896 -0
  95. package/lib/Utils/messages.js +2904 -0
  96. package/lib/Utils/meta-ai-msmsg.js +262 -0
  97. package/lib/Utils/native-bridge.js +82 -0
  98. package/lib/Utils/noise-handler.js +196 -0
  99. package/lib/Utils/offline-node-processor.js +42 -0
  100. package/lib/Utils/pre-key-manager.js +107 -0
  101. package/lib/Utils/process-message.js +1048 -0
  102. package/lib/Utils/reporting-utils.js +262 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.js +145 -0
  107. package/lib/Utils/sync-action-utils.js +54 -0
  108. package/lib/Utils/tc-token-utils.js +161 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/validate-connection.js +219 -0
  111. package/lib/Utils/view-once-cache.js +79 -0
  112. package/lib/Utils/voip-rekey.js +22 -0
  113. package/lib/WABinary/constants.js +1304 -0
  114. package/lib/WABinary/decode.js +343 -0
  115. package/lib/WABinary/encode.js +228 -0
  116. package/lib/WABinary/generic-utils.js +240 -0
  117. package/lib/WABinary/index.js +33 -0
  118. package/lib/WABinary/jid-utils.js +361 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +13 -0
  121. package/lib/WAM/constants.js +39486 -0
  122. package/lib/WAM/encode.js +142 -0
  123. package/lib/WAM/index.js +31 -0
  124. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  125. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  128. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  129. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  130. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  136. package/lib/WAUSync/Protocols/index.js +39 -0
  137. package/lib/WAUSync/USyncQuery.js +133 -0
  138. package/lib/WAUSync/USyncUser.js +50 -0
  139. package/lib/WAUSync/index.js +31 -0
  140. package/lib/antiban.js +4637 -0
  141. package/lib/index.js +45 -0
  142. package/package.json +107 -0
@@ -0,0 +1,604 @@
1
+ 'use strict'
2
+
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod }
7
+ }
8
+
9
+ Object.defineProperty(exports, '__esModule', { value: true })
10
+
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')
18
+
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
+ })
27
+
28
+ const waMessageID = m => m.key.id || ''
29
+
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
+ }
37
+
38
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
39
+
40
+ const ENCRYPTED_STORE_MARKER = 'xazbails-store-v1'
41
+
42
+ const deriveStoreKey = secret => {
43
+ const { createHash } = require('crypto')
44
+ return createHash('sha256').update(String(secret)).digest()
45
+ }
46
+
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
+ }
61
+
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
+ }
77
+
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
+ }
600
+
601
+ exports.waChatKey = waChatKey
602
+ exports.waMessageID = waMessageID
603
+ exports.waLabelAssociationKey = waLabelAssociationKey
604
+ exports.makeInMemoryStore = makeInMemoryStore
@@ -0,0 +1,81 @@
1
+ 'use strict'
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true })
4
+
5
+ function makeOrderedDictionary(idGetter) {
6
+ const array = []
7
+ const dict = {}
8
+ const get = id => dict[id]
9
+ const update = item => {
10
+ const id = idGetter(item)
11
+ const idx = array.findIndex(i => idGetter(i) === id)
12
+ if (idx >= 0) {
13
+ array[idx] = item
14
+ dict[id] = item
15
+ }
16
+ return false
17
+ }
18
+ const upsert = (item, mode) => {
19
+ const id = idGetter(item)
20
+ if (get(id)) {
21
+ update(item)
22
+ } else {
23
+ if (mode === 'append') {
24
+ array.push(item)
25
+ } else {
26
+ array.splice(0, 0, item)
27
+ }
28
+ dict[id] = item
29
+ }
30
+ }
31
+ const remove = item => {
32
+ const id = idGetter(item)
33
+ const idx = array.findIndex(i => idGetter(i) === id)
34
+ if (idx >= 0) {
35
+ array.splice(idx, 1)
36
+ delete dict[id]
37
+ return true
38
+ }
39
+ return false
40
+ }
41
+ return {
42
+ array,
43
+ get,
44
+ upsert,
45
+ update,
46
+ remove,
47
+ updateAssign: (id, update) => {
48
+ const item = get(id)
49
+ if (item) {
50
+ Object.assign(item, update)
51
+ delete dict[id]
52
+ dict[idGetter(item)] = item
53
+ return true
54
+ }
55
+ return false
56
+ },
57
+ clear: () => {
58
+ array.splice(0, array.length)
59
+ for (const key of Object.keys(dict)) {
60
+ delete dict[key]
61
+ }
62
+ },
63
+ filter: contain => {
64
+ let i = 0
65
+ while (i < array.length) {
66
+ if (!contain(array[i])) {
67
+ delete dict[idGetter(array[i])]
68
+ array.splice(i, 1)
69
+ } else {
70
+ i += 1
71
+ }
72
+ }
73
+ },
74
+ toJSON: () => array,
75
+ fromJSON: newItems => {
76
+ array.splice(0, array.length, ...newItems)
77
+ }
78
+ }
79
+ }
80
+
81
+ exports.makeOrderedDictionary = makeOrderedDictionary
@@ -0,0 +1,29 @@
1
+ 'use strict'
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true })
4
+
5
+ class ObjectRepository {
6
+ constructor(entities = {}) {
7
+ this.entityMap = new Map(Object.entries(entities))
8
+ }
9
+ findById(id) {
10
+ return this.entityMap.get(id)
11
+ }
12
+ findAll() {
13
+ return Array.from(this.entityMap.values())
14
+ }
15
+ upsertById(id, entity) {
16
+ return this.entityMap.set(id, { ...entity })
17
+ }
18
+ deleteById(id) {
19
+ return this.entityMap.delete(id)
20
+ }
21
+ count() {
22
+ return this.entityMap.size
23
+ }
24
+ toJSON() {
25
+ return this.findAll()
26
+ }
27
+ }
28
+
29
+ exports.ObjectRepository = ObjectRepository