/* eslint-disable camelcase */ import logger from "../logger"; import { IncomingMessagev1 } from "@digiresilience/node-signald/dist/generated"; import { withDb, AppDatabase } from "../db"; import workerUtils from "../utils"; interface WebhookPayload { to: string; from: string; message_id: string; sent_at: string; message: string; attachment: string | null; filename: string | null; mime_type: string | null; } interface SignaldMessageTaskOptions { message: IncomingMessagev1; botId: string; botPhoneNumber: string; } const formatPayload = (opts: SignaldMessageTaskOptions): WebhookPayload => { const { botId, botPhoneNumber, message } = opts; const { source, timestamp, data_message: dataMessage } = message; const { number }: any = source; const { body, attachments }: any = dataMessage; return { to: botPhoneNumber, from: number, message_id: `${botId}-${timestamp}`, sent_at: `${timestamp}`, message: body, attachment: null, filename: null, mime_type: null, }; }; const notifyWebhooks = async ( db: AppDatabase, messageInfo: SignaldMessageTaskOptions ) => { const { botId, message: { timestamp }, } = messageInfo; const webhooks = await db.webhooks.findAllByBackendId("signal", botId); if (webhooks && webhooks.length === 0) { logger.debug({ botId }, "no webhooks registered for signal bot"); return; } webhooks.forEach(({ id }) => { const payload = formatPayload(messageInfo); logger.debug( { payload }, "formatted signal bot payload for notify-webhook" ); workerUtils.addJob( "notify-webhook", { payload, webhookId: id, }, { // this de-deduplicates the job jobKey: `webhook-${id}-message-${botId}-${timestamp}`, } ); }); }; const signaldMessageTask = async ( options: SignaldMessageTaskOptions ): Promise => { console.log(options); withDb(async (db: AppDatabase) => { await notifyWebhooks(db, options); }); }; export default signaldMessageTask;