From 64d09c70b4b09acd05781a45d3299f5fd8c1a21e Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Mon, 10 Mar 2025 17:35:46 +0200 Subject: [PATCH] store: remove built-in store --- Example/example.ts | 36 +- src/Store/index.ts | 3 - src/Store/make-cache-manager-store.ts | 100 ------ src/Store/make-in-memory-store.ts | 479 -------------------------- src/Store/make-ordered-dictionary.ts | 86 ----- src/Store/object-repository.ts | 32 -- src/Utils/generics.ts | 1 - 7 files changed, 11 insertions(+), 726 deletions(-) delete mode 100644 src/Store/index.ts delete mode 100644 src/Store/make-cache-manager-store.ts delete mode 100644 src/Store/make-in-memory-store.ts delete mode 100644 src/Store/make-ordered-dictionary.ts delete mode 100644 src/Store/object-repository.ts diff --git a/Example/example.ts b/Example/example.ts index ad0a94c..8bf4ebf 100644 --- a/Example/example.ts +++ b/Example/example.ts @@ -1,7 +1,7 @@ import { Boom } from '@hapi/boom' import NodeCache from '@cacheable/node-cache' import readline from 'readline' -import makeWASocket, { AnyMessageContent, BinaryInfo, delay, DisconnectReason, downloadAndProcessHistorySyncNotification, encodeWAM, fetchLatestBaileysVersion, getAggregateVotesInPollMessage, getHistoryMsg, isJidNewsletter, makeCacheableSignalKeyStore, makeInMemoryStore, proto, useMultiFileAuthState, WAMessageContent, WAMessageKey } from '../src' +import makeWASocket, { AnyMessageContent, BinaryInfo, delay, DisconnectReason, downloadAndProcessHistorySyncNotification, encodeWAM, fetchLatestBaileysVersion, getAggregateVotesInPollMessage, getHistoryMsg, isJidNewsletter, makeCacheableSignalKeyStore, proto, useMultiFileAuthState, WAMessageContent, WAMessageKey } from '../src' //import MAIN_LOGGER from '../src/Utils/logger' import open from 'open' import fs from 'fs' @@ -10,7 +10,6 @@ import P from 'pino' const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }, P.destination('./wa-logs.txt')) logger.level = 'trace' -const useStore = !process.argv.includes('--no-store') const doReplies = process.argv.includes('--do-reply') const usePairingCode = process.argv.includes('--use-pairing-code') @@ -24,15 +23,6 @@ const onDemandMap = new Map() const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) const question = (text: string) => new Promise((resolve) => rl.question(text, resolve)) -// the store maintains the data of the WA connection in memory -// can be written out to a file & read from it -const store = useStore ? makeInMemoryStore({ logger }) : undefined -store?.readFromFile('./baileys_store_multi.json') -// save every 10s -setInterval(() => { - store?.writeToFile('./baileys_store_multi.json') -}, 10_000) - // start a connection const startSock = async() => { const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info') @@ -58,8 +48,6 @@ const startSock = async() => { getMessage, }) - store?.bind(sock.ev) - // Pairing code for Web clients if (usePairingCode && !sock.authState.creds.registered) { // todo move to QR event @@ -98,7 +86,7 @@ const startSock = async() => { console.log('Connection closed. You are logged out.') } } - + // WARNING: THIS WILL SEND A WAM EXAMPLE AND THIS IS A ****CAPTURED MESSAGE.**** // DO NOT ACTUALLY ENABLE THIS UNLESS YOU MODIFIED THE FILE.JSON!!!!! // THE ANALYTICS IN THE FILE ARE OLD. DO NOT USE THEM. @@ -124,7 +112,7 @@ const startSock = async() => { }) const buffer = encodeWAM(binaryInfo); - + const result = await sock.sendWAMBuffer(buffer) console.log(result) } @@ -182,11 +170,11 @@ const startSock = async() => { {} ) - + const chatId = onDemandMap.get( historySyncNotification!.peerDataRequestSessionId! ) - + console.log(messages) onDemandMap.delete( @@ -209,7 +197,7 @@ const startSock = async() => { if (msg.message?.conversation || msg.message?.extendedTextMessage?.text) { const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text if (text == "requestPlaceholder" && !upsert.requestId) { - const messageId = await sock.requestPlaceholderResend(msg.key) + const messageId = await sock.requestPlaceholderResend(msg.key) console.log('requested placeholder resync, id=', messageId) } else if (upsert.requestId) { console.log('Message received from phone, id=', upsert.requestId, msg) @@ -217,7 +205,7 @@ const startSock = async() => { // go to an old chat and send this if (text == "onDemandHistSync") { - const messageId = await sock.fetchMessageHistory(50, msg.key, msg.messageTimestamp!) + const messageId = await sock.fetchMessageHistory(50, msg.key, msg.messageTimestamp!) console.log('requested on-demand sync, id=', messageId) } } @@ -240,7 +228,7 @@ const startSock = async() => { for(const { key, update } of events['messages.update']) { if(update.pollUpdates) { - const pollCreation = await getMessage(key) + const pollCreation: proto.IMessage = {} // get the poll creation message somehow if(pollCreation) { console.log( 'got poll update, aggregation: ', @@ -292,14 +280,12 @@ const startSock = async() => { return sock async function getMessage(key: WAMessageKey): Promise { - if(store) { - const msg = await store.loadMessage(key.remoteJid!, key.id!) - return msg?.message || undefined - } + // Implement a way to retreive messages that were upserted from messages.upsert + // up to you // only if store is present return proto.Message.fromObject({}) } } -startSock() \ No newline at end of file +startSock() diff --git a/src/Store/index.ts b/src/Store/index.ts deleted file mode 100644 index 74be5a3..0000000 --- a/src/Store/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import makeCacheManagerAuthState from './make-cache-manager-store' -import makeInMemoryStore from './make-in-memory-store' -export { makeInMemoryStore, makeCacheManagerAuthState } \ No newline at end of file diff --git a/src/Store/make-cache-manager-store.ts b/src/Store/make-cache-manager-store.ts deleted file mode 100644 index d5e53b7..0000000 --- a/src/Store/make-cache-manager-store.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { caching, Store } from 'cache-manager' -import { proto } from '../../WAProto' -import { AuthenticationCreds } from '../Types' -import { BufferJSON, initAuthCreds } from '../Utils' -import logger from '../Utils/logger' - -const makeCacheManagerAuthState = async(store: Store, sessionKey: string) => { - const defaultKey = (file: string): string => `${sessionKey}:${file}` - - const databaseConn = await caching(store) - - const writeData = async(file: string, data: object) => { - let ttl: number | undefined = undefined - if(file === 'creds') { - ttl = 63115200 // 2 years - } - - await databaseConn.set( - defaultKey(file), - JSON.stringify(data, BufferJSON.replacer), - ttl - ) - } - - const readData = async(file: string): Promise => { - try { - const data = await databaseConn.get(defaultKey(file)) - - if(data) { - return JSON.parse(data as string, BufferJSON.reviver) - } - - return null - } catch(error) { - logger.error(error) - return null - } - } - - const removeData = async(file: string) => { - try { - return await databaseConn.del(defaultKey(file)) - } catch{ - logger.error(`Error removing ${file} from session ${sessionKey}`) - } - } - - const clearState = async() => { - try { - const result = await databaseConn.store.keys(`${sessionKey}*`) - await Promise.all( - result.map(async(key) => await databaseConn.del(key)) - ) - } catch(err) { - } - } - - const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds() - - return { - clearState, - saveCreds: () => writeData('creds', creds), - state: { - creds, - keys: { - get: async(type: string, ids: string[]) => { - const data = {} - await Promise.all( - ids.map(async(id) => { - let value: proto.Message.AppStateSyncKeyData | AuthenticationCreds | null = - await readData(`${type}-${id}`) - if(type === 'app-state-sync-key' && value) { - value = proto.Message.AppStateSyncKeyData.fromObject(value) - } - - data[id] = value - }) - ) - - return data - }, - set: async(data) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const tasks: Promise[] = [] - for(const category in data) { - for(const id in data[category]) { - const value = data[category][id] - const key = `${category}-${id}` - tasks.push(value ? writeData(key, value) : removeData(key)) - } - } - - await Promise.all(tasks) - }, - } - } - } -} - -export default makeCacheManagerAuthState diff --git a/src/Store/make-in-memory-store.ts b/src/Store/make-in-memory-store.ts deleted file mode 100644 index 83492f7..0000000 --- a/src/Store/make-in-memory-store.ts +++ /dev/null @@ -1,479 +0,0 @@ -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