link-stack/apps/bridge-worker/tasks/signal/signald-message.ts

94 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-02-13 12:41:30 +00:00
/* eslint-disable camelcase */
2024-04-21 16:59:50 +02:00
// import logger from "../logger";
// import { IncomingMessagev1 } from "@digiresilience/node-signald/build/main/generated";
import { withDb, AppDatabase } from "../../lib/db";
import workerUtils from "../../lib/utils";
type IncomingMessagev1 = any;
2023-02-13 12:41:30 +00:00
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;
attachment: string;
filename: string;
mimetype: string;
2023-02-13 12:41:30 +00:00
}
const formatPayload = (opts: SignaldMessageTaskOptions): WebhookPayload => {
2024-04-21 16:59:50 +02:00
const { botId, botPhoneNumber, message, attachment, filename, mimetype } =
opts;
2023-02-13 12:41:30 +00:00
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,
filename,
mime_type: mimetype,
2023-02-13 12:41:30 +00:00
};
};
const notifyWebhooks = async (
db: AppDatabase,
2024-04-21 16:59:50 +02:00
messageInfo: SignaldMessageTaskOptions,
2023-02-13 12:41:30 +00:00
) => {
const {
botId,
message: { timestamp },
} = messageInfo;
const webhooks = await db.webhooks.findAllByBackendId("signal", botId);
if (webhooks && webhooks.length === 0) {
2024-04-21 16:59:50 +02:00
// logger.debug({ botId }, "no webhooks registered for signal bot");
2023-02-13 12:41:30 +00:00
return;
}
webhooks.forEach(({ id }) => {
const payload = formatPayload(messageInfo);
2024-04-21 16:59:50 +02:00
// logger.debug(
// { payload },
// "formatted signal bot payload for notify-webhook",
// );
2023-02-13 12:41:30 +00:00
workerUtils.addJob(
"notify-webhook",
{
payload,
webhookId: id,
},
{
// this de-deduplicates the job
jobKey: `webhook-${id}-message-${botId}-${timestamp}`,
2024-04-21 16:59:50 +02:00
},
2023-02-13 12:41:30 +00:00
);
});
};
const signaldMessageTask = async (
2024-04-21 16:59:50 +02:00
options: SignaldMessageTaskOptions,
2023-02-13 12:41:30 +00:00
): Promise<void> => {
console.log(options);
withDb(async (db: AppDatabase) => {
await notifyWebhooks(db, options);
});
};
export default signaldMessageTask;