import type KeyedDB from '@adiwajshing/keyed-db' import type { Comparable } from '@adiwajshing/keyed-db/lib/Types' 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 { Label } from '../Types/Label' import { LabelAssociation, LabelAssociationType, MessageLabelAssociation } from '../Types/LabelAssociation' import { md5, toNumber, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils' import { ILogger } from '../Utils/logger' import { jidDecode, jidNormalizedUser } from '../WABinary' import makeOrderedDictionary from './make-ordered-dictionary' import { ObjectRepository } from './object-repository' type WASocket = ReturnType 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 const waLabelAssociationKey: Comparable = { key: (la: LabelAssociation) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId), compare: (k1: string, k2: string) => k2.localeCompare(k1) } export type BaileysInMemoryStoreConfig = { chatKey?: Comparable labelAssociationKey?: Comparable logger?: ILogger socket?: WASocket } const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID) export default (config: BaileysInMemoryStoreConfig) => { const socket = config.socket const chatKey = config.chatKey || waChatKey(true) const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey const logger: ILogger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' }) const KeyedDB = require('@adiwajshing/keyed-db').default const chats = new KeyedDB(chatKey, c => c.id) as KeyedDB const messages: { [_: string]: ReturnType } = {} const contacts: { [_: string]: Contact } = {} const groupMetadata: { [_: string]: GroupMetadata } = {} const presences: { [id: string]: { [participant: string]: PresenceData } } = {} const state: ConnectionState = { connection: 'close' } const labels = new ObjectRepository