-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
make-in-memory-store.ts
367 lines (327 loc) · 10.5 KB
/
make-in-memory-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import type KeyedDB from '@adiwajshing/keyed-db'
import type { Comparable } from '@adiwajshing/keyed-db/lib/Types'
import type { Logger } from 'pino'
import { proto } from '../../WAProto'
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults'
import type makeMDSocket from '../Socket'
import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, PresenceData, WAMessage, WAMessageCursor, WAMessageKey } from '../Types'
import { toNumber, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils'
import { jidNormalizedUser } from '../WABinary'
import makeOrderedDictionary from './make-ordered-dictionary'
type WASocket = ReturnType<typeof makeMDSocket>
export const waChatKey = (pin: boolean) => ({
key: (c: Chat) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
compare: (k1: string, k2: string) => k2.localeCompare (k1)
})
export const waMessageID = (m: WAMessage) => m.key.id || ''
export type BaileysInMemoryStoreConfig = {
chatKey?: Comparable<Chat, string>
logger?: Logger
}
const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID)
export default (
{ logger: _logger, chatKey }: BaileysInMemoryStoreConfig
) => {
const logger = _logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
chatKey = chatKey || waChatKey(true)
const KeyedDB = require('@adiwajshing/keyed-db').default as new (...args: any[]) => KeyedDB<Chat, string>
const chats = new KeyedDB(chatKey, c => c.id)
const messages: { [_: string]: ReturnType<typeof makeMessagesDictionary> } = { }
const contacts: { [_: string]: Contact } = { }
const groupMetadata: { [_: string]: GroupMetadata } = { }
const presences: { [id: string]: { [participant: string]: PresenceData } } = { }
const state: ConnectionState = { connection: 'close' }
const assertMessageList = (jid: string) => {
if(!messages[jid]) {
messages[jid] = makeMessagesDictionary()
}
return messages[jid]
}
const contactsUpsert = (newContacts: Contact[]) => {
const oldContacts = new Set(Object.keys(contacts))
for(const contact of newContacts) {
oldContacts.delete(contact.id)
contacts[contact.id] = Object.assign(
contacts[contact.id] || {},
contact
)
}
return oldContacts
}
/**
* binds to a BaileysEventEmitter.
* It listens to all events and constructs a state that you can query accurate data from.
* Eg. can use the store to fetch chats, contacts, messages etc.
* @param ev typically the event emitter from the socket connection
*/
const bind = (ev: BaileysEventEmitter) => {
ev.on('connection.update', update => {
Object.assign(state, update)
})
ev.on('messaging-history.set', ({
chats: newChats,
contacts: newContacts,
messages: newMessages,
isLatest
}) => {
if(isLatest) {
chats.clear()
for(const id in messages) {
delete messages[id]
}
}
const chatsAdded = chats.insertIfAbsent(...newChats).length
logger.debug({ chatsAdded }, 'synced chats')
const oldContacts = contactsUpsert(newContacts)
for(const jid of oldContacts) {
delete contacts[jid]
}
logger.debug({ deletedContacts: oldContacts.size, newContacts }, 'synced contacts')
for(const msg of newMessages) {
const jid = msg.key.remoteJid!
const list = assertMessageList(jid)
list.upsert(msg, 'prepend')
}
logger.debug({ messages: newMessages.length }, 'synced messages')
})
ev.on('contacts.update', updates => {
for(const update of updates) {
if(contacts[update.id!]) {
Object.assign(contacts[update.id!], update)
} else {
logger.debug({ update }, 'got update for non-existant contact')
}
}
})
ev.on('chats.upsert', newChats => {
chats.upsert(...newChats)
})
ev.on('chats.update', updates => {
for(let update of updates) {
const result = chats.update(update.id!, chat => {
if(update.unreadCount! > 0) {
update = { ...update }
update.unreadCount = (chat.unreadCount || 0) + update.unreadCount!
}
Object.assign(chat, update)
})
if(!result) {
logger.debug({ update }, 'got update for non-existant chat')
}
}
})
ev.on('presence.update', ({ id, presences: update }) => {
presences[id] = presences[id] || {}
Object.assign(presences[id], update)
})
ev.on('chats.delete', deletions => {
for(const item of deletions) {
chats.deleteById(item)
}
})
ev.on('messages.upsert', ({ messages: newMessages, type }) => {
switch (type) {
case 'append':
case 'notify':
for(const msg of newMessages) {
const jid = jidNormalizedUser(msg.key.remoteJid!)
const list = assertMessageList(jid)
list.upsert(msg, 'append')
if(type === 'notify') {
if(!chats.get(jid)) {
ev.emit('chats.upsert', [
{
id: jid,
conversationTimestamp: toNumber(msg.messageTimestamp),
unreadCount: 1
}
])
}
}
}
break
}
})
ev.on('messages.update', updates => {
for(const { update, key } of updates) {
const list = assertMessageList(jidNormalizedUser(key.remoteJid!))
if(update?.status) {
const listStatus = list.get(key.id!)?.status
if(listStatus && update?.status <= listStatus) {
logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
delete update.status
logger.debug({ update }, 'new update object')
}
}
const result = list.updateAssign(key.id!, update)
if(!result) {
logger.debug({ update }, 'got update for non-existent message')
}
}
})
ev.on('messages.delete', item => {
if('all' in item) {
const list = messages[item.jid]
list?.clear()
} else {
const jid = item.keys[0].remoteJid!
const list = messages[jid]
if(list) {
const idSet = new Set(item.keys.map(k => k.id))
list.filter(m => !idSet.has(m.key.id))
}
}
})
ev.on('groups.update', updates => {
for(const update of updates) {
const id = update.id!
if(groupMetadata[id]) {
Object.assign(groupMetadata[id], update)
} else {
logger.debug({ update }, 'got update for non-existant group metadata')
}
}
})
ev.on('group-participants.update', ({ id, participants, action }) => {
const metadata = groupMetadata[id]
if(metadata) {
switch (action) {
case 'add':
metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })))
break
case 'demote':
case 'promote':
for(const participant of metadata.participants) {
if(participants.includes(participant.id)) {
participant.isAdmin = action === 'promote'
}
}
break
case 'remove':
metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
break
}
}
})
ev.on('message-receipt.update', updates => {
for(const { key, receipt } of updates) {
const obj = messages[key.remoteJid!]
const msg = obj?.get(key.id!)
if(msg) {
updateMessageWithReceipt(msg, receipt)
}
}
})
ev.on('messages.reaction', (reactions) => {
for(const { key, reaction } of reactions) {
const obj = messages[key.remoteJid!]
const msg = obj?.get(key.id!)
if(msg) {
updateMessageWithReaction(msg, reaction)
}
}
})
}
const toJSON = () => ({
chats,
contacts,
messages
})
const fromJSON = (json: { chats: Chat[], contacts: { [id: string]: Contact }, messages: { [id: string]: WAMessage[] } }) => {
chats.upsert(...json.chats)
contactsUpsert(Object.values(json.contacts))
for(const jid in json.messages) {
const list = assertMessageList(jid)
for(const msg of json.messages[jid]) {
list.upsert(proto.WebMessageInfo.fromObject(msg), 'append')
}
}
}
return {
chats,
contacts,
messages,
groupMetadata,
state,
presences,
bind,
/** loads messages from the store, if not found -- uses the legacy connection */
loadMessages: async(jid: string, count: number, cursor: WAMessageCursor) => {
const list = assertMessageList(jid)
const mode = !cursor || 'before' in cursor ? 'before' : 'after'
const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
const cursorValue = cursorKey ? list.get(cursorKey.id!) : undefined
let messages: WAMessage[]
if(list && mode === 'before' && (!cursorKey || cursorValue)) {
if(cursorValue) {
const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
messages = list.array.slice(0, msgIdx)
} else {
messages = list.array
}
const diff = count - messages.length
if(diff < 0) {
messages = messages.slice(-count) // get the last X messages
}
} else {
messages = []
}
return messages
},
loadMessage: async(jid: string, id: string) => messages[jid]?.get(id),
mostRecentMessage: async(jid: string) => {
const message: WAMessage | undefined = messages[jid]?.array.slice(-1)[0]
return message
},
fetchImageUrl: async(jid: string, sock: WASocket | undefined) => {
const contact = contacts[jid]
if(!contact) {
return sock?.profilePictureUrl(jid)
}
if(typeof contact.imgUrl === 'undefined') {
contact.imgUrl = await sock?.profilePictureUrl(jid)
}
return contact.imgUrl
},
fetchGroupMetadata: async(jid: string, sock: WASocket | undefined) => {
if(!groupMetadata[jid]) {
const metadata = await sock?.groupMetadata(jid)
if(metadata) {
groupMetadata[jid] = metadata
}
}
return groupMetadata[jid]
},
// fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
// if(!groupMetadata[jid]) {
// const metadata = await sock?.getBroadcastListInfo(jid)
// if(metadata) {
// groupMetadata[jid] = metadata
// }
// }
// return groupMetadata[jid]
// },
fetchMessageReceipts: async({ remoteJid, id }: WAMessageKey) => {
const list = messages[remoteJid!]
const msg = list?.get(id!)
return msg?.userReceipt
},
toJSON,
fromJSON,
writeToFile: (path: string) => {
// require fs here so that in case "fs" is not available -- the app does not crash
const { writeFileSync } = require('fs')
writeFileSync(path, JSON.stringify(toJSON()))
},
readFromFile: (path: string) => {
// require fs here so that in case "fs" is not available -- the app does not crash
const { readFileSync, existsSync } = require('fs')
if(existsSync(path)) {
logger.debug({ path }, 'reading from file')
const jsonStr = readFileSync(path, { encoding: 'utf-8' })
const json = JSON.parse(jsonStr)
fromJSON(json)
}
}
}
}