import { db, getWorkerUtils } from "@link-stack/bridge-common"; import * as signalApi from "@link-stack/signal-api"; const { Configuration, MessagesApi, GroupsApi } = signalApi; interface SendSignalMessageTaskOptions { token: string; to: string; message: any; conversationId?: string; // Zammad ticket/conversation ID for callback quoteMessage?: string; // Optional: message text to quote quoteAuthor?: string; // Optional: author of quoted message (phone number) quoteTimestamp?: number; // Optional: timestamp of quoted message in milliseconds } const sendSignalMessageTask = async ({ token, to, message, conversationId, quoteMessage, quoteAuthor, quoteTimestamp, }: SendSignalMessageTaskOptions): Promise => { console.log(`[send-signal-message] Processing outgoing message:`, { token, to, conversationId, messageLength: message?.length, }); const bot = await db .selectFrom("SignalBot") .selectAll() .where("token", "=", token) .executeTakeFirstOrThrow(); const { phoneNumber: number } = bot; const config = new Configuration({ basePath: process.env.BRIDGE_SIGNAL_URL, }); const messagesClient = new MessagesApi(config); const groupsClient = new GroupsApi(config); const worker = await getWorkerUtils(); let finalTo = to; let groupCreated = false; try { // Check if 'to' is a group ID (UUID format) vs phone number const isGroupId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( to, ); const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true"; console.log(`[send-signal-message] Recipient analysis:`, { to, isGroupId, enableAutoGroups, shouldCreateGroup: enableAutoGroups && !isGroupId && to && conversationId, }); // If sending to a phone number and auto-groups is enabled, create a group first if (enableAutoGroups && !isGroupId && to && conversationId) { try { const groupName = `Support: ${to}`; const createGroupResponse = await groupsClient.v1GroupsNumberPost({ number: bot.phoneNumber, data: { name: groupName, members: [to], description: "Private support conversation", }, }); if (createGroupResponse.id) { // Get the internal_id for this group // Sometimes the API needs a moment to return the new group, so retry if needed let internalId: string | undefined; let retries = 3; while (retries > 0 && !internalId) { try { const groupsResponse = await groupsClient.v1GroupsNumberGet({ number: bot.phoneNumber, }); // Find the group we just created to get its internal_id const createdGroup = groupsResponse.find(g => g.id === createGroupResponse.id); internalId = createdGroup?.internal_id; if (!internalId && retries > 1) { console.log(`[send-signal-message] Group not found in list yet, retrying...`); await new Promise(resolve => setTimeout(resolve, 1000)); } } catch (error) { console.error(`[send-signal-message] Error fetching groups:`, error); } retries--; } finalTo = createGroupResponse.id; groupCreated = true; console.log( `[send-signal-message] Created new Signal group:`, { groupId: finalTo, internalId, groupName, conversationId, originalRecipient: to, botNumber: bot.phoneNumber, }, ); // Notify Zammad about the new group ID via webhook await worker.addJob("common/notify-webhooks", { backendId: bot.id, payload: { event: "group_created", conversation_id: conversationId, original_recipient: to, group_id: finalTo, internal_group_id: internalId, timestamp: new Date().toISOString(), }, }); } } catch (groupError) { console.error("[send-signal-message] Error creating Signal group:", { error: groupError instanceof Error ? groupError.message : groupError, to, conversationId, }); // Continue with original recipient if group creation fails } } console.log(`[send-signal-message] Sending message via API:`, { fromNumber: number, toRecipient: finalTo, originalTo: to, recipientChanged: to !== finalTo, groupCreated, }); // Build the message data with optional quote parameters const messageData: signalApi.ApiSendMessageV2 = { number, recipients: [finalTo], message, }; // Add quote parameters if all are provided if (quoteMessage && quoteAuthor && quoteTimestamp) { messageData.quoteTimestamp = quoteTimestamp; messageData.quoteAuthor = quoteAuthor; messageData.quoteMessage = quoteMessage; console.log(`[send-signal-message] Including quote in message:`, { quoteAuthor, quoteMessage: quoteMessage.substring(0, 50) + '...', quoteTimestamp, }); } const response = await messagesClient.v2SendPost({ data: messageData, }); console.log( `[send-signal-message] Message sent successfully:`, { to: finalTo, groupCreated, response: response?.timestamp || 'no timestamp', }, ); } catch (error) { console.error({ error }); throw error; } }; export default sendSignalMessageTask;