diff --git a/src/server/main.ts b/src/server/main.ts index 49312a3..5704d2f 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -75,6 +75,18 @@ function call( }); } +const forwardedMessages = new Map(); + +function cleanupForwardedMessages() { + const now = Date.now(); + + for (const [id, timestamp] of forwardedMessages) { + if (now - timestamp > 60_000) { + forwardedMessages.delete(id); + } + } +} + function handleWhatsAppMessage(ws: WebSocket, data: string) { const message = JSON.parse(data) as | RpcResponse @@ -125,15 +137,22 @@ function handleWhatsAppMessage(ws: WebSocket, data: string) { } if (message.event === "message") { + const m = message.data as MessageDTO; + const msgId = m.id.id || m.id._serialized || ""; + + if (forwardedMessages.has(msgId)) { + return; + } + + forwardedMessages.set(msgId, Date.now()); + // forward to clients clientSockets.forEach((ws) => { ws.send(JSON.stringify(message)); }); - const m = message.data as MessageDTO; - insertMessage({ - id: m.id.id || m.id._serialized || "", + id: msgId, chatId: m.chatId || "", from: typeof m.from === "string" ? m.from : m.from?._serialized || "", to: typeof m.to === "string" ? m.to : m.to?._serialized || "", @@ -276,4 +295,5 @@ wss.on("connection", (ws) => { }); initDb(); +setInterval(cleanupForwardedMessages, 30_000); console.log(`WhatsApp bridge listening on ws://127.0.0.1:${PORT}`);