feat: add db

This commit is contained in:
2026-09-14 18:27:27 +08:00
parent e4b77e1c11
commit 193e5fff31
9 changed files with 88 additions and 10 deletions
+1
View File
@@ -32,3 +32,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Finder (MacOS) folder config # Finder (MacOS) folder config
.DS_Store .DS_Store
*.db
+5 -3
View File
@@ -115,6 +115,7 @@
pushname: contact.pushname ?? null, pushname: contact.pushname ?? null,
shortName: contact.shortName ?? null, shortName: contact.shortName ?? null,
formattedName: contact.formattedName ?? null, formattedName: contact.formattedName ?? null,
notifyName: contact.notifyName ?? null,
number: contact.number ?? null, number: contact.number ?? null,
isMe: contact.isMe ?? false, isMe: contact.isMe ?? false,
isUser: contact.isUser ?? false, isUser: contact.isUser ?? false,
@@ -211,6 +212,7 @@
forwardingScore: message.forwardingScore ?? 0, forwardingScore: message.forwardingScore ?? 0,
isStarred: message.isStarred ?? false, isStarred: message.isStarred ?? false,
broadcast: message.broadcast ?? false, broadcast: message.broadcast ?? false,
notifyName: message.notifyName ?? null,
mentionedIds: Array.isArray(message.mentionedIds) ? message.mentionedIds.map(serializeId) : [], mentionedIds: Array.isArray(message.mentionedIds) ? message.mentionedIds.map(serializeId) : [],
quotedMsgId: serializeMessageId(quotedMsgId), quotedMsgId: serializeMessageId(quotedMsgId),
quotedMsg, quotedMsg,
@@ -269,7 +271,7 @@
return chats.filter(Boolean).map(serializeChat); return chats.filter(Boolean).map(serializeChat);
} }
case "listContacts": { case "listContacts": {
const contacts = await WPP.contact.getAllContacts(); const contacts = await WPP.contact.list();
const result = request.params?.limit ? contacts.slice(0, request.params.limit) : contacts; const result = request.params?.limit ? contacts.slice(0, request.params.limit) : contacts;
return result.filter(Boolean).map(serializeContact); return result.filter(Boolean).map(serializeContact);
} }
@@ -396,14 +398,14 @@
WPP.loader.onReady(() => { WPP.loader.onReady(() => {
console.log("[WA Bridge] WA-JS ready"); console.log("[WA Bridge] WA-JS ready");
connect(); connect();
WPP.chat.on("chat.new_message", (message) => { WPP.on("chat.new_message", (message) => {
if (socket?.readyState !== WebSocket.OPEN) { if (socket?.readyState !== WebSocket.OPEN) {
return; return;
} }
send({ send({
type: "event", type: "event",
event: "message", event: "message",
data: serialize(message) data: serializeMessage(message)
}); });
}); });
}); });
+2 -2
View File
File diff suppressed because one or more lines are too long
+53
View File
@@ -0,0 +1,53 @@
import { Database } from "bun:sqlite";
export const db = new Database(process.cwd() + "/data.db");
export interface Message {
id: string;
chatId: string;
from: string;
to: string;
fromMe: boolean;
data: any;
}
export interface Contact {
id: string;
accountLid: string;
from: string;
to: string;
fromMe: boolean;
data: any;
}
export function initDb() {
db.run(`
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
chat_id TEXT NOT NULL,
sender TEXT NOT NULL,
receiver TEXT NOT NULL,
from_me INTEGER NOT NULL DEFAULT 0,
data TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_messages_chat_id ON messages(chat_id);
CREATE INDEX IF NOT EXISTS idx_messages_chat_id_id ON messages(chat_id, id);
`);
const msg = db.query("SELECT * FROM messages").all();
console.log(msg);
}
export function insertMessage(message: Message): void {
db.query(
`INSERT INTO messages (id, chat_id, sender, receiver, from_me, data)
VALUES ($id, $chatId, $from, $to, $fromMe, $data)`,
).run({
$id: message.id,
$chatId: message.chatId,
$from: message.from,
$to: message.to,
$fromMe: message.fromMe ? 1 : 0,
$data: JSON.stringify(message.data),
});
}
+17 -1
View File
@@ -1,6 +1,8 @@
import { WebSocketServer, WebSocket } from "ws"; import { WebSocketServer, WebSocket } from "ws";
import type { BridgeRequest, RpcResponse } from "../shared/protocol"; import type { BridgeRequest, RpcResponse } from "../shared/protocol";
import { initDb, insertMessage } from "./db";
import type { MessageDTO } from "../shared/dto";
const PORT = 8787; const PORT = 8787;
@@ -89,7 +91,20 @@ function handleWhatsAppMessage(data: string) {
} }
if (message.type === "event") { if (message.type === "event") {
console.log("[WhatsApp event]", message.event, message.data); // console.log("[WhatsApp event]", message.event, message.data);
if (message.event === "message") {
const m = message.data as MessageDTO;
insertMessage({
id: m.id.id || m.id._serialized || "",
chatId: m.chatId || "",
from: typeof m.from === "string" ? m.from : m.from?._serialized || "",
to: typeof m.to === "string" ? m.to : m.to?._serialized || "",
fromMe: !!m.fromMe,
data: m,
});
}
} }
} }
@@ -203,4 +218,5 @@ wss.on("connection", (ws) => {
}); });
}); });
initDb();
console.log(`WhatsApp bridge listening on ws://127.0.0.1:${PORT}`); console.log(`WhatsApp bridge listening on ws://127.0.0.1:${PORT}`);
+2
View File
@@ -27,6 +27,7 @@ export interface ContactDTO {
pushname?: string | null; pushname?: string | null;
shortName?: string | null; shortName?: string | null;
formattedName?: string | null; formattedName?: string | null;
notifyName?: string | null;
number?: string | null; number?: string | null;
@@ -134,6 +135,7 @@ export interface MessageDTO {
isStarred?: boolean; isStarred?: boolean;
broadcast?: boolean; broadcast?: boolean;
notifyName?: string | null;
mentionedIds?: (SerializedId | string)[]; mentionedIds?: (SerializedId | string)[];
+3 -3
View File
@@ -61,7 +61,7 @@ async function handleRequest(request: BridgeRequest) {
} }
case "listContacts": { case "listContacts": {
const contacts = await WPP.contact.getAllContacts(); const contacts = await WPP.contact.list();
const result = request.params?.limit const result = request.params?.limit
? contacts.slice(0, request.params.limit) ? contacts.slice(0, request.params.limit)
@@ -240,7 +240,7 @@ function start() {
/* /*
* Forward new-message events to Node. * Forward new-message events to Node.
*/ */
WPP.chat.on("chat.new_message", (message: unknown) => { WPP.on("chat.new_message", (message: unknown) => {
if (socket?.readyState !== WebSocket.OPEN) { if (socket?.readyState !== WebSocket.OPEN) {
return; return;
} }
@@ -248,7 +248,7 @@ function start() {
send({ send({
type: "event", type: "event",
event: "message", event: "message",
data: serialize(message), data: serializeMessage(message),
}); });
}); });
}); });
+2
View File
@@ -163,6 +163,7 @@ export function serializeContact(contact: any): ContactDTO {
pushname: contact.pushname ?? null, pushname: contact.pushname ?? null,
shortName: contact.shortName ?? null, shortName: contact.shortName ?? null,
formattedName: contact.formattedName ?? null, formattedName: contact.formattedName ?? null,
notifyName: contact.notifyName ?? null,
number: contact.number ?? null, number: contact.number ?? null,
isMe: contact.isMe ?? false, isMe: contact.isMe ?? false,
@@ -279,6 +280,7 @@ export function serializeMessage(message: any): MessageDTO {
forwardingScore: message.forwardingScore ?? 0, forwardingScore: message.forwardingScore ?? 0,
isStarred: message.isStarred ?? false, isStarred: message.isStarred ?? false,
broadcast: message.broadcast ?? false, broadcast: message.broadcast ?? false,
notifyName: message.notifyName ?? null,
mentionedIds: Array.isArray(message.mentionedIds) mentionedIds: Array.isArray(message.mentionedIds)
? message.mentionedIds.map(serializeId) ? message.mentionedIds.map(serializeId)
: [], : [],
+3 -1
View File
@@ -52,11 +52,13 @@ declare const WPP: {
}; };
contact: { contact: {
getAllContacts(): Promise<any[]>; list(): Promise<any[]>;
get(contactId: string): any | undefined; get(contactId: string): any | undefined;
}; };
group: { group: {
getAllGroups(): Promise<any[]>; getAllGroups(): Promise<any[]>;
}; };
on(event: string, callback: (...args: any[]) => void): void;
}; };