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

249 lines
9 KiB
TypeScript
Raw Normal View History

2024-06-05 15:12:48 +02:00
import { db, getWorkerUtils } from "@link-stack/bridge-common";
2025-06-10 14:02:21 +02:00
import * as signalApi from "@link-stack/signal-api";
const { Configuration, GroupsApi } = signalApi;
2024-04-30 13:13:49 +02:00
interface ReceiveSignalMessageTaskOptions {
2024-06-05 15:12:48 +02:00
token: string;
2024-07-18 11:08:01 +02:00
to: string;
from: string;
messageId: string;
sentAt: string;
2024-06-05 15:12:48 +02:00
message: string;
2024-07-18 11:08:01 +02:00
attachment?: string;
filename?: string;
mimeType?: string;
2025-06-10 14:02:21 +02:00
isGroup?: boolean;
2025-07-07 20:02:54 +02:00
groupId?: string; // Group ID from the message envelope
2024-04-30 13:13:49 +02:00
}
const receiveSignalMessageTask = async ({
2024-06-05 15:12:48 +02:00
token,
2024-07-18 11:08:01 +02:00
to,
from,
messageId,
sentAt,
2024-04-30 13:13:49 +02:00
message,
2024-07-18 11:08:01 +02:00
attachment,
filename,
mimeType,
2025-06-10 14:02:21 +02:00
isGroup,
2025-07-07 20:02:54 +02:00
groupId,
2024-06-05 15:12:48 +02:00
}: ReceiveSignalMessageTaskOptions): Promise<void> => {
2025-07-07 20:02:54 +02:00
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',
});
2024-06-05 15:12:48 +02:00
const worker = await getWorkerUtils();
const row = await db
.selectFrom("SignalBot")
.selectAll()
.where("id", "=", token)
.executeTakeFirstOrThrow();
const backendId = row.id;
2025-06-10 14:02:21 +02:00
let finalTo = to;
2025-07-07 20:02:54 +02:00
let createdInternalId: string | undefined;
2025-06-10 14:02:21 +02:00
// Check if auto-group creation is enabled and this is NOT already a group message
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
2025-07-07 20:02:54 +02:00
console.log(`[receive-signal-message] Auto-groups config:`, {
enableAutoGroups,
isGroup,
shouldCreateGroup: enableAutoGroups && !isGroup && from && to,
});
2025-06-10 14:02:21 +02:00
2025-07-07 20:02:54 +02:00
// 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) {
2025-06-10 14:02:21 +02:00
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) {
2025-07-07 20:02:54 +02:00
// 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}`,
);
}
2025-06-10 14:02:21 +02:00
finalTo = createGroupResponse.id;
console.log(
2025-07-07 20:02:54 +02:00
`[receive-signal-message] Created new Signal group:`,
{
groupId: finalTo,
internalId,
groupName,
forPhoneNumber: from,
botNumber: row.phoneNumber,
response: createGroupResponse,
},
2025-06-10 14:02:21 +02:00
);
2025-07-07 20:02:54 +02:00
// 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,
});
2025-06-10 14:02:21 +02:00
}
// Continue with original 'to' if group creation fails
}
}
2025-07-07 20:02:54 +02:00
// 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);
2024-06-05 15:12:48 +02:00
const payload = {
2025-07-07 20:02:54 +02:00
to: to, // Always use the bot's phone number, not the group ID
2024-07-18 11:08:01 +02:00
from,
message_id: messageId,
sent_at: sentAt,
2024-06-05 15:12:48 +02:00
message,
2024-07-18 11:08:01 +02:00
attachment,
filename,
mime_type: mimeType,
2025-07-07 20:02:54 +02:00
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 } : {}),
2024-06-05 15:12:48 +02:00
};
2025-07-07 20:02:54 +02:00
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,
});
2024-06-05 15:12:48 +02:00
await worker.addJob("common/notify-webhooks", { backendId, payload });
};
2024-04-30 13:13:49 +02:00
export default receiveSignalMessageTask;