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; groupId?: string; // Group ID from the message envelope } const receiveSignalMessageTask = async ({ token, to, from, messageId, sentAt, message, attachment, filename, mimeType, isGroup, groupId, }: ReceiveSignalMessageTaskOptions): Promise => { console.log(`[receive-signal-message] Processing incoming message:`, { messageId, from, to, isGroup, groupId, hasMessage: !!message, hasAttachment: !!attachment, token, toFormat: to?.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i) ? 'UUID' : 'phone', }); const worker = await getWorkerUtils(); const row = await db .selectFrom("SignalBot") .selectAll() .where("id", "=", token) .executeTakeFirstOrThrow(); const backendId = row.id; let finalTo = to; let createdInternalId: string | undefined; // Check if auto-group creation is enabled and this is NOT already a group message const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true"; console.log(`[receive-signal-message] Auto-groups config:`, { enableAutoGroups, isGroup, shouldCreateGroup: enableAutoGroups && !isGroup && from && to, }); // If this is already a group message and auto-groups is enabled, // use the provided groupId or keep the original 'to' if (enableAutoGroups && isGroup && groupId) { // Store the group ID for metadata but keep using phone number for 'to' console.log(`[receive-signal-message] Message is from existing group: ${groupId}`); finalTo = groupId; // Store for metadata } else 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) { // We need to 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: row.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(`[receive-signal-message] Group not found in list yet, retrying...`); await new Promise(resolve => setTimeout(resolve, 1000)); } } catch (error) { console.error(`[receive-signal-message] Error fetching groups:`, error); } retries--; } createdInternalId = internalId; // Store for use in webhook payload if (!internalId) { console.warn( `[receive-signal-message] Warning: Could not get internal_id for group ${createGroupResponse.id}. Group matching may fail for subsequent messages.`, ); } else { console.log( `[receive-signal-message] Successfully retrieved internal_id: ${internalId} for group: ${createGroupResponse.id}`, ); } finalTo = createGroupResponse.id; console.log( `[receive-signal-message] Created new Signal group:`, { groupId: finalTo, internalId, groupName, forPhoneNumber: from, botNumber: row.phoneNumber, response: createGroupResponse, }, ); // Send a system notification to Zammad about group creation try { const systemNote = `Signal Auto-Group Created\n` + `Group Name: ${groupName}\n` + `Group ID: ${finalTo}\n\n` + `Note: The user's initial message has been forwarded to the Signal group with attribution.`; await worker.addJob("common/notify-webhooks", { backendId, payload: { to: to, from: "system", message_id: `system-group-created-${Date.now()}`, sent_at: new Date().toISOString(), message: systemNote, isGroup: true, group_id: finalTo, internal_group_id: internalId, // Also pass the internal_id internal: true, // Mark as internal note system_message: true // Additional flag to indicate system message } }); console.log(`[receive-signal-message] Sent group creation notification to Zammad`); } catch (notifyError) { console.error("[receive-signal-message] Error sending system notification:", notifyError); // Continue processing even if notification fails } // Forward the user's initial message to the group using quote feature try { console.log(`[receive-signal-message] Forwarding initial message to group using quote feature`); // Build the attribution message const attributionMessage = `Message from ${from}:\n"${message}"\n\n---\nSupport team: Your request has been received. An agent will respond shortly.`; await worker.addJob("signal/send-signal-message", { token: backendId, to: finalTo, // Send to the newly created group message: attributionMessage, conversationId: null, // No ticket ID yet since we're still processing the initial message // Quote the original message for context quoteMessage: message, quoteAuthor: from, quoteTimestamp: Date.parse(sentAt), // Convert ISO string to milliseconds }); console.log(`[receive-signal-message] Successfully forwarded initial message to group ${finalTo}`); } catch (forwardError) { console.error("[receive-signal-message] Error forwarding message to group:", forwardError); // Continue processing even if forwarding fails } } } catch (error: any) { // Check if error is because group already exists const errorMessage = error?.response?.data?.error || error?.message || error; const isAlreadyExists = errorMessage?.toString().toLowerCase().includes('already') || errorMessage?.toString().toLowerCase().includes('exists'); if (isAlreadyExists) { console.log(`[receive-signal-message] Group might already exist for ${from}, continuing with original recipient`); } else { console.error("[receive-signal-message] Error creating Signal group:", { error: errorMessage, from, to, botNumber: row.phoneNumber, }); } // Continue with original 'to' if group creation fails } } // WORKAROUND: Zammad doesn't accept UUID group IDs in the 'to' field // Instead, we use the bot's phone number and include group metadata const isGroupMessage = isGroup || finalTo !== to || !!groupId; const effectiveGroupId = groupId || (finalTo !== to ? finalTo : undefined); const payload = { to: to, // Always use the bot's phone number, not the group ID from, message_id: messageId, sent_at: sentAt, message, attachment, filename, mime_type: mimeType, isGroup: isGroupMessage, // Include group ID as metadata if this is a group message ...(effectiveGroupId ? { group_id: effectiveGroupId } : {}), // Include internal_group_id if we created a new group ...(createdInternalId ? { internal_group_id: createdInternalId } : {}), }; console.log(`[receive-signal-message] Sending webhook notification:`, { backendId, originalTo: to, finalTo, toChanged: to !== finalTo, payloadIsGroup: payload.isGroup, payloadTo: payload.to, payloadGroupId: (payload as any).group_id, payloadInternalGroupId: (payload as any).internal_group_id, messageId: payload.message_id, createdNewGroup: !!createdInternalId, }); await worker.addJob("common/notify-webhooks", { backendId, payload }); }; export default receiveSignalMessageTask;