import { db, getWorkerUtils } from "@link-stack/bridge-common"; import * as signalApi from "@link-stack/signal-api"; const { Configuration, GroupsApi } = signalApi; interface ReceiveSignalMessageTaskOptions { token: string; to: string; from: string; messageId: string; sentAt: string; message: string; attachment?: string; filename?: string; mimeType?: string; isGroup?: boolean; } const receiveSignalMessageTask = async ({ token, to, from, messageId, sentAt, message, attachment, filename, mimeType, isGroup, }: ReceiveSignalMessageTaskOptions): Promise => { const worker = await getWorkerUtils(); const row = await db .selectFrom("SignalBot") .selectAll() .where("id", "=", token) .executeTakeFirstOrThrow(); const backendId = row.id; let finalTo = to; // Check if auto-group creation is enabled and this is NOT already a group message const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true"; if (enableAutoGroups && !isGroup && from && to) { try { const config = new Configuration({ basePath: process.env.BRIDGE_SIGNAL_URL, }); const groupsClient = new GroupsApi(config); // Create new group for this conversation const groupName = `Support: ${from}`; const createGroupResponse = await groupsClient.v1GroupsNumberPost({ number: row.phoneNumber, data: { name: groupName, members: [from], description: "Private support conversation", }, }); if (createGroupResponse.id) { finalTo = createGroupResponse.id; console.log( `Created new Signal group ${finalTo} for conversation with ${from}`, ); } } catch (error) { console.error("Error creating Signal group:", error); // Continue with original 'to' if group creation fails } } const payload = { to: finalTo, from, message_id: messageId, sent_at: sentAt, message, attachment, filename, mime_type: mimeType, }; await worker.addJob("common/notify-webhooks", { backendId, payload }); }; export default receiveSignalMessageTask;