UNPKG

@fatihjr/wa-wrapper

Version:

Baileys WhatsApp Web API wrapper.

79 lines (78 loc) 3.21 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const keyed_db_1 = __importDefault(require("@adiwajshing/keyed-db")); const fs_1 = require("fs"); class keyDBHandler { constructor(databasePath) { this.waChatKey = (pin) => ({ key: (c) => (pin ? (c.pinned ? "1" : "0") : "") + (c.archived ? "0" : "1") + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, "0") : "") + c.id, compare: (k1, k2) => k2.localeCompare(k1), }); this.chatKey = (0, this.waChatKey)(true); this.chats = new keyed_db_1.default(this.chatKey, c => c.id); this.toJSON = () => ({ chats: this.chats, }); this.fromJSON = (json) => { this.chats.upsert(...json.chats); }; this.writeToFile = (path = this.databasePath) => { (0, fs_1.writeFileSync)(path, JSON.stringify(this.toJSON())); }; this.readFromFile = (path = this.databasePath) => { if ((0, fs_1.existsSync)(path)) { const jsonStr = (0, fs_1.readFileSync)(path, { encoding: "utf-8" }); const json = JSON.parse(jsonStr); this.fromJSON(json); } }; this.bind = (ev) => { ev.on("messaging-history.set", ({ chats: newChats, isLatest }) => { if (isLatest) { this.chats.clear(); } this.chats.insertIfAbsent(...newChats.filter(item => !item.messages)).length; this.writeToFile(); }); ev.on("chats.upsert", newChats => { this.chats.upsert(...newChats.filter(item => !item.messages)); this.writeToFile(); }); ev.on("chats.update", updates => { for (let update of updates) { const result = this.chats.update(update.id, chat => { if (update.unreadCount > 0) { update = { ...update }; update.unreadCount = (chat.unreadCount || 0) + update.unreadCount; } Object.assign(chat, update); }); if (!result) { console.log({ update }, "got update for non-existent chat"); } } this.writeToFile(); }); ev.on("chats.delete", deletions => { for (const item of deletions) { this.chats.deleteById(item); } this.writeToFile(); }); }; this.end = (ev) => { ev.removeAllListeners("messaging-history.set"); ev.removeAllListeners("chats.upsert"); ev.removeAllListeners("chats.update"); ev.removeAllListeners("chats.delete"); }; this.databasePath = databasePath; } } exports.default = keyDBHandler;