More Whatsapp Docker updates

This commit is contained in:
Darren Clarke 2024-05-17 09:20:00 +02:00
parent 3da103c010
commit e26e5832ff
8 changed files with 63 additions and 21 deletions

View file

@ -32,6 +32,7 @@ RUN chown -R node:node ${APP_DIR}
WORKDIR ${APP_DIR}/apps/bridge-whatsapp/ WORKDIR ${APP_DIR}/apps/bridge-whatsapp/
RUN chmod +x docker-entrypoint.sh RUN chmod +x docker-entrypoint.sh
USER node USER node
RUN mkdir /home/node/baileys
EXPOSE 5000 EXPOSE 5000
ENV PORT 5000 ENV PORT 5000
ENV NODE_ENV production ENV NODE_ENV production

View file

@ -10,7 +10,7 @@ import {
ReceiveMessageRoute, ReceiveMessageRoute,
} from "./routes.js"; } from "./routes.js";
const server = Hapi.server({ host: "localhost", port: 5000 }); const server = Hapi.server({ port: 5000 });
const startServer = async () => { const startServer = async () => {
await server.register({ plugin: hapiPino }); await server.register({ plugin: hapiPino });

View file

@ -72,7 +72,9 @@ export const RegisterBotRoute = withDefaults({
const { id } = request.params; const { id } = request.params;
const whatsappService = getService(request); const whatsappService = getService(request);
await whatsappService.register(id, (error: string) => { await whatsappService.register(id);
/*
, (error: string) => {
if (error) { if (error) {
return _h.response(error).code(500); return _h.response(error).code(500);
} }
@ -80,6 +82,9 @@ export const RegisterBotRoute = withDefaults({
return _h.response().code(200); return _h.response().code(200);
}); });
*/
return _h.response().code(200);
}, },
}, },
}); });

View file

@ -28,8 +28,12 @@ export default class WhatsappService extends Service {
super(server, options); super(server, options);
} }
getBaseDirectory(): string {
return `/home/node/baileys`;
}
getBotDirectory(id: string): string { getBotDirectory(id: string): string {
return `/baileys/${id}`; return `${this.getBaseDirectory()}/${id}`;
} }
getAuthDirectory(id: string): string { getAuthDirectory(id: string): string {
@ -141,7 +145,8 @@ export default class WhatsappService extends Service {
private async updateConnections() { private async updateConnections() {
this.resetConnections(); this.resetConnections();
const botIDs = fs.readdirSync("/baileys"); const baseDirectory = this.getBaseDirectory();
const botIDs = fs.readdirSync(baseDirectory);
console.log({ botIDs }); console.log({ botIDs });
for await (const botID of botIDs) { for await (const botID of botIDs) {
const directory = this.getBotDirectory(botID); const directory = this.getBotDirectory(botID);
@ -220,6 +225,17 @@ export default class WhatsappService extends Service {
whatsappBotId: botID, whatsappBotId: botID,
}; };
const message =
webMessageInfo?.message?.conversation ??
webMessageInfo?.message?.extendedTextMessage?.text ??
webMessageInfo?.message?.imageMessage?.caption ??
webMessageInfo?.message?.videoMessage?.caption;
const payload = {
message,
sender: webMessageInfo.key.remoteJid?.split("@")[0],
};
await fetch( await fetch(
`${process.env.BRIDGE_FRONTEND_URL}/api/whatsapp/bots/${botID}/receive`, `${process.env.BRIDGE_FRONTEND_URL}/api/whatsapp/bots/${botID}/receive`,
{ {
@ -227,7 +243,7 @@ export default class WhatsappService extends Service {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(receivedMessage), body: JSON.stringify(payload),
}, },
); );
} }
@ -258,10 +274,18 @@ export default class WhatsappService extends Service {
fs.rmSync(botDirectory, { recursive: true, force: true }); fs.rmSync(botDirectory, { recursive: true, force: true });
} }
async register(botID: string, callback: AuthCompleteCallback): Promise<void> { async register(
botID: string,
callback?: AuthCompleteCallback,
): Promise<void> {
const { version } = await fetchLatestBaileysVersion(); const { version } = await fetchLatestBaileysVersion();
await this.createConnection(botID, this.server, { version }, callback); await this.createConnection(
callback(); botID,
this.server,
{ version, browser: WhatsappService.browserDescription },
callback,
);
callback?.();
} }
async send( async send(

View file

@ -1,8 +1,8 @@
{ {
"extends": "ts-config", "extends": "ts-config",
"compilerOptions": { "compilerOptions": {
"module": "esnext", "module": "commonjs",
"target": "esnext", "target": "es2018",
"esModuleInterop": true, "esModuleInterop": true,
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "build/main", "outDir": "build/main",

View file

@ -1,21 +1,33 @@
import { db, getWorkerUtils } from "bridge-common"; import { db, getWorkerUtils } from "bridge-common";
interface ReceiveWhatsappMessageTaskOptions { interface ReceiveWhatsappMessageTaskOptions {
token; token: string;
message: any; sender: string;
message: string;
} }
const receiveWhatsappMessageTask = async ({ const receiveWhatsappMessageTask = async ({
token, token,
sender,
message, message,
}: ReceiveWhatsappMessageTaskOptions): Promise<void> => { }: ReceiveWhatsappMessageTaskOptions): Promise<void> => {
const bot = await db console.log({ token, sender, message });
const worker = await getWorkerUtils();
const row = await db
.selectFrom("WhatsappBot") .selectFrom("WhatsappBot")
.selectAll() .selectAll()
.where((eb) => eb.or([eb("token", "=", token), eb("id", "=", token)])) .where("id", "=", token)
.executeTakeFirstOrThrow(); .executeTakeFirstOrThrow();
console.log(bot); console.log(row);
const backendId = row.id;
const payload = {
message,
recipient: sender,
};
await worker.addJob("common/notify-webhooks", { backendId, payload });
}; };
export default receiveWhatsappMessageTask; export default receiveWhatsappMessageTask;

View file

@ -95,12 +95,12 @@ export class Service {
{ params: { service, token } }: ServiceParams, { params: { service, token } }: ServiceParams,
): Promise<NextResponse> { ): Promise<NextResponse> {
console.log("INTO receiveMessage"); console.log("INTO receiveMessage");
const message = await req.json(); const json = await req.json();
console.log({ message }); console.log({ json });
const worker = await getWorkerUtils(); const worker = await getWorkerUtils();
await worker.addJob(`${service}/receive-${service}-message`, { await worker.addJob(`${service}/receive-${service}-message`, {
token, token,
message, ...json,
}); });
return NextResponse.json({ response: "ok" }); return NextResponse.json({ response: "ok" });

View file

@ -22,14 +22,14 @@ export class Whatsapp extends Service {
.where("id", "=", id) .where("id", "=", id)
.execute(); .execute();
revalidatePath(`/whatsapp/${id}`);
if (!json.verified) { if (!json.verified) {
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/register`; const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/register`;
const result = await fetch(url, { method: "POST", cache: "no-store" }); const result = await fetch(url, { method: "POST" });
console.log({ result2: result }); console.log({ result2: result });
} }
revalidatePath(`/whatsapp/${id}`);
return NextResponse.json(json); return NextResponse.json(json);
} }
} }