Switch to Hono

This commit is contained in:
Darren Clarke 2026-02-15 08:29:10 +01:00
parent 9601e179bc
commit 9f0e1f8b61
10 changed files with 152 additions and 331 deletions

View file

@ -1,39 +1,29 @@
import * as Hapi from "@hapi/hapi";
import hapiPino from "hapi-pino";
import Schmervice from "@hapipal/schmervice";
import { serve } from "@hono/node-server";
import WhatsappService from "./service.ts";
import {
RegisterBotRoute,
UnverifyBotRoute,
GetBotRoute,
SendMessageRoute,
ReceiveMessageRoute,
} from "./routes.ts";
import { createRoutes } from "./routes.ts";
import { createLogger } from "./lib/logger";
const logger = createLogger("bridge-whatsapp-index");
const server = Hapi.server({ port: 5000 });
const startServer = async () => {
await server.register({ plugin: hapiPino });
server.route(RegisterBotRoute);
server.route(UnverifyBotRoute);
server.route(GetBotRoute);
server.route(SendMessageRoute);
server.route(ReceiveMessageRoute);
await server.register(Schmervice);
server.registerService(WhatsappService);
await server.start();
return server;
};
const main = async () => {
await startServer();
const service = new WhatsappService();
await service.initialize();
const app = createRoutes(service);
const port = parseInt(process.env.PORT || "5000", 10);
serve({ fetch: app.fetch, port }, (info) => {
logger.info({ port: info.port }, "bridge-whatsapp listening");
});
const shutdown = async () => {
logger.info("Shutting down...");
await service.teardown();
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
};
main().catch((err) => {

View file

@ -1,125 +1,58 @@
import * as Hapi from "@hapi/hapi";
import Toys from "@hapipal/toys";
import WhatsappService from "./service.ts";
import { Hono } from "hono";
import type WhatsappService from "./service.ts";
import { createLogger } from "./lib/logger";
const withDefaults = Toys.withRouteDefaults({
options: {
cors: true,
},
});
const logger = createLogger("bridge-whatsapp-routes");
const getService = (request: Hapi.Request): WhatsappService => {
const { whatsappService } = request.services();
export function createRoutes(service: WhatsappService): Hono {
const app = new Hono();
return whatsappService as WhatsappService;
};
app.post("/api/bots/:id/send", async (c) => {
const id = c.req.param("id");
const { phoneNumber, message, attachments } = await c.req.json<{
phoneNumber: string;
message: string;
attachments?: Array<{ data: string; filename: string; mime_type: string }>;
}>();
interface MessageRequest {
phoneNumber: string;
message: string;
attachments?: Array<{ data: string; filename: string; mime_type: string }>;
await service.send(id, phoneNumber, message, attachments);
logger.info({ id, attachmentCount: attachments?.length || 0 }, "Sent message");
return c.json({
result: {
recipient: phoneNumber,
timestamp: new Date().toISOString(),
source: id,
},
});
});
app.get("/api/bots/:id/receive", async (c) => {
const id = c.req.param("id");
const date = new Date();
const twoDaysAgo = new Date(date.getTime());
twoDaysAgo.setDate(date.getDate() - 2);
const messages = await service.receive(id, twoDaysAgo);
return c.json(messages);
});
app.post("/api/bots/:id/register", async (c) => {
const id = c.req.param("id");
await service.register(id);
return c.body(null, 200);
});
app.post("/api/bots/:id/unverify", async (c) => {
const id = c.req.param("id");
await service.unverify(id);
return c.body(null, 200);
});
app.get("/api/bots/:id", async (c) => {
const id = c.req.param("id");
return c.json(service.getBot(id));
});
return app;
}
export const SendMessageRoute = withDefaults({
method: "post",
path: "/api/bots/{id}/send",
options: {
description: "Send a message",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const { phoneNumber, message, attachments } = request.payload as MessageRequest;
const whatsappService = getService(request);
await whatsappService.send(id, phoneNumber, message as string, attachments);
request.logger.info(
{
id,
attachmentCount: attachments?.length || 0,
},
"Sent a message at %s",
new Date().toISOString(),
);
return _h
.response({
result: {
recipient: phoneNumber,
timestamp: new Date().toISOString(),
source: id,
},
})
.code(200);
},
},
});
export const ReceiveMessageRoute = withDefaults({
method: "get",
path: "/api/bots/{id}/receive",
options: {
description: "Receive messages",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const whatsappService = getService(request);
const date = new Date();
const twoDaysAgo = new Date(date.getTime());
twoDaysAgo.setDate(date.getDate() - 2);
request.logger.info({ id }, "Received messages at %s", new Date().toISOString());
return whatsappService.receive(id, twoDaysAgo);
},
},
});
export const RegisterBotRoute = withDefaults({
method: "post",
path: "/api/bots/{id}/register",
options: {
description: "Register a bot",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const whatsappService = getService(request);
await whatsappService.register(id);
/*
, (error: string) => {
if (error) {
return _h.response(error).code(500);
}
request.logger.info({ id }, "Register bot at %s", new Date());
return _h.response().code(200);
});
*/
return _h.response().code(200);
},
},
});
export const UnverifyBotRoute = withDefaults({
method: "post",
path: "/api/bots/{id}/unverify",
options: {
description: "Unverify bot",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const whatsappService = getService(request);
return whatsappService.unverify(id);
},
},
});
export const GetBotRoute = withDefaults({
method: "get",
path: "/api/bots/{id}",
options: {
description: "Get bot info",
async handler(request: Hapi.Request, _h: Hapi.ResponseToolkit) {
const { id } = request.params;
const whatsappService = getService(request);
return whatsappService.getBot(id);
},
},
});

View file

@ -1,5 +1,3 @@
import { Server } from "@hapi/hapi";
import { Service } from "@hapipal/schmervice";
import makeWASocket, {
DisconnectReason,
proto,
@ -23,16 +21,12 @@ const logger = createLogger("bridge-whatsapp-service");
export type AuthCompleteCallback = (error?: string) => void;
export default class WhatsappService extends Service {
export default class WhatsappService {
connections: { [key: string]: any } = {};
loginConnections: { [key: string]: any } = {};
static browserDescription: [string, string, string] = ["Bridge", "Chrome", "2.0"];
constructor(server: Server, options: never) {
super(server, options);
}
getBaseDirectory(): string {
return `/home/node/baileys`;
}
@ -87,7 +81,6 @@ export default class WhatsappService extends Service {
private async createConnection(
botID: string,
server: Server,
options: any,
authCompleteCallback?: any,
) {
@ -125,13 +118,13 @@ export default class WhatsappService extends Service {
const disconnectStatusCode = (lastDisconnect?.error as any)?.output?.statusCode;
if (disconnectStatusCode === DisconnectReason.restartRequired) {
logger.info("reconnecting after got new login");
await this.createConnection(botID, server, options);
await this.createConnection(botID, options);
authCompleteCallback?.();
} else if (disconnectStatusCode !== DisconnectReason.loggedOut) {
logger.info("reconnecting");
await this.sleep(pause);
pause *= 2;
this.createConnection(botID, server, options);
this.createConnection(botID, options);
}
}
}
@ -178,7 +171,7 @@ export default class WhatsappService extends Service {
const { version, isLatest } = await fetchLatestBaileysVersion();
logger.info({ version: version.join("."), isLatest }, "using WA version");
await this.createConnection(botID, this.server, {
await this.createConnection(botID, {
browser: WhatsappService.browserDescription,
version,
});
@ -355,7 +348,6 @@ export default class WhatsappService extends Service {
const { version } = await fetchLatestBaileysVersion();
await this.createConnection(
botID,
this.server,
{ version, browser: WhatsappService.browserDescription },
callback,
);
@ -452,10 +444,6 @@ export default class WhatsappService extends Service {
_botID: string,
_lastReceivedDate: Date,
): Promise<proto.IWebMessageInfo[]> {
// loadAllUnreadMessages() was removed in Baileys 7.x
// Messages are now delivered via events (messages.upsert, messaging-history.set)
// and forwarded to webhooks automatically.
// See: https://baileys.wiki/docs/migration/to-v7.0.0/
throw new Error(
"Message polling is no longer supported in Baileys 7.x. " +
"Please configure a webhook to receive messages instead. " +

View file

@ -1,8 +0,0 @@
import type WhatsappService from "./service.ts";
declare module "@hapipal/schmervice" {
interface SchmerviceDecorator {
(namespace: "whatsapp"): WhatsappService;
}
type ServiceFunctionalInterface = { name: string };
}