More groups WIP
This commit is contained in:
parent
f20cd5a53c
commit
7be5cb1478
8 changed files with 488 additions and 261 deletions
|
|
@ -9,6 +9,12 @@ const notifyWebhooksTask = async (
|
|||
options: NotifyWebhooksOptions,
|
||||
): Promise<void> => {
|
||||
const { backendId, payload } = options;
|
||||
|
||||
console.log(`[notify-webhooks] Processing webhook notification:`, {
|
||||
backendId,
|
||||
payloadKeys: Object.keys(payload),
|
||||
payload: JSON.stringify(payload, null, 2),
|
||||
});
|
||||
|
||||
const webhooks = await db
|
||||
.selectFrom("Webhook")
|
||||
|
|
@ -16,14 +22,49 @@ const notifyWebhooksTask = async (
|
|||
.where("backendId", "=", backendId)
|
||||
.execute();
|
||||
|
||||
console.log(`[notify-webhooks] Found ${webhooks.length} webhooks for backend ${backendId}`);
|
||||
|
||||
for (const webhook of webhooks) {
|
||||
const { endpointUrl, httpMethod, headers } = webhook;
|
||||
const finalHeaders = { "Content-Type": "application/json", ...headers };
|
||||
const result = await fetch(endpointUrl, {
|
||||
const body = JSON.stringify(payload);
|
||||
|
||||
console.log(`[notify-webhooks] Sending webhook:`, {
|
||||
url: endpointUrl,
|
||||
method: httpMethod,
|
||||
headers: finalHeaders,
|
||||
body: JSON.stringify(payload),
|
||||
bodyLength: body.length,
|
||||
headers: Object.keys(finalHeaders),
|
||||
payload: body,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await fetch(endpointUrl, {
|
||||
method: httpMethod,
|
||||
headers: finalHeaders,
|
||||
body,
|
||||
});
|
||||
|
||||
console.log(`[notify-webhooks] Webhook response:`, {
|
||||
url: endpointUrl,
|
||||
status: result.status,
|
||||
statusText: result.statusText,
|
||||
ok: result.ok,
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const responseText = await result.text();
|
||||
console.error(`[notify-webhooks] Webhook error response:`, {
|
||||
url: endpointUrl,
|
||||
status: result.status,
|
||||
response: responseText.substring(0, 500), // First 500 chars
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[notify-webhooks] Webhook request failed:`, {
|
||||
url: endpointUrl,
|
||||
error: error instanceof Error ? error.message : error,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -58,14 +58,44 @@ const processMessage = async ({
|
|||
|
||||
const { attachments } = dataMessage;
|
||||
const rawTimestamp = dataMessage?.timestamp;
|
||||
|
||||
// Debug logging for group detection
|
||||
console.log(`[fetch-signal-messages] Processing message:`, {
|
||||
sourceUuid,
|
||||
source,
|
||||
rawTimestamp,
|
||||
hasGroupV2: !!dataMessage?.groupV2,
|
||||
hasGroupContext: !!dataMessage?.groupContext,
|
||||
hasGroupInfo: !!dataMessage?.groupInfo,
|
||||
isGroup,
|
||||
groupV2Id: dataMessage?.groupV2?.id,
|
||||
groupContextType: dataMessage?.groupContext?.type,
|
||||
groupInfoType: dataMessage?.groupInfo?.type,
|
||||
});
|
||||
const timestamp = new Date(rawTimestamp);
|
||||
|
||||
const formattedAttachments = await fetchAttachments(attachments);
|
||||
const primaryAttachment = formattedAttachments[0] ?? {};
|
||||
const additionalAttachments = formattedAttachments.slice(1);
|
||||
|
||||
// Extract group ID if this is a group message
|
||||
const groupId = dataMessage?.groupV2?.id || dataMessage?.groupContext?.id || dataMessage?.groupInfo?.groupId;
|
||||
|
||||
// IMPORTANT: Always use phoneNumber as 'to' for compatibility with Zammad
|
||||
// The group ID will be passed via the isGroup flag and potentially in metadata
|
||||
const toRecipient = phoneNumber;
|
||||
|
||||
console.log(`[fetch-signal-messages] Setting recipient:`, {
|
||||
isGroup,
|
||||
groupId,
|
||||
phoneNumber,
|
||||
toRecipient,
|
||||
note: 'Using phoneNumber as to for Zammad compatibility',
|
||||
});
|
||||
|
||||
const primaryMessage = {
|
||||
token: id,
|
||||
to: phoneNumber,
|
||||
to: toRecipient,
|
||||
from: source,
|
||||
messageId: `${sourceUuid}-${rawTimestamp}`,
|
||||
message: dataMessage?.message,
|
||||
|
|
@ -74,6 +104,8 @@ const processMessage = async ({
|
|||
filename: primaryAttachment.filename,
|
||||
mimeType: primaryAttachment.mimeType,
|
||||
isGroup,
|
||||
// Include groupId if this is a group message
|
||||
...(isGroup && groupId ? { groupId } : {}),
|
||||
};
|
||||
const formattedMessages = [primaryMessage];
|
||||
|
||||
|
|
@ -125,6 +157,8 @@ const fetchSignalMessagesTask = async ({
|
|||
number: phoneNumber,
|
||||
});
|
||||
|
||||
console.log(`[fetch-signal-messages] Fetching messages for bot ${id} (${phoneNumber})`);
|
||||
|
||||
for (const message of messages) {
|
||||
const formattedMessages = await processMessage({
|
||||
id,
|
||||
|
|
@ -133,6 +167,15 @@ const fetchSignalMessagesTask = async ({
|
|||
});
|
||||
for (const formattedMessage of formattedMessages) {
|
||||
if (formattedMessage.to !== formattedMessage.from) {
|
||||
console.log(`[fetch-signal-messages] Creating job for message:`, {
|
||||
messageId: formattedMessage.messageId,
|
||||
from: formattedMessage.from,
|
||||
to: formattedMessage.to,
|
||||
isGroup: formattedMessage.isGroup,
|
||||
hasMessage: !!formattedMessage.message,
|
||||
hasAttachment: !!formattedMessage.attachment,
|
||||
});
|
||||
|
||||
await worker.addJob(
|
||||
"signal/receive-signal-message",
|
||||
formattedMessage,
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ interface ReceiveSignalMessageTaskOptions {
|
|||
filename?: string;
|
||||
mimeType?: string;
|
||||
isGroup?: boolean;
|
||||
groupId?: string; // Group ID from the message envelope
|
||||
}
|
||||
|
||||
const receiveSignalMessageTask = async ({
|
||||
|
|
@ -26,7 +27,19 @@ const receiveSignalMessageTask = async ({
|
|||
filename,
|
||||
mimeType,
|
||||
isGroup,
|
||||
groupId,
|
||||
}: ReceiveSignalMessageTaskOptions): Promise<void> => {
|
||||
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")
|
||||
|
|
@ -36,11 +49,24 @@ const receiveSignalMessageTask = async ({
|
|||
|
||||
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 (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,
|
||||
|
|
@ -59,19 +85,136 @@ const receiveSignalMessageTask = async ({
|
|||
});
|
||||
|
||||
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(
|
||||
`Created new Signal group ${finalTo} for conversation with ${from}`,
|
||||
`[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,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating Signal group:", error);
|
||||
// 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: finalTo,
|
||||
to: to, // Always use the bot's phone number, not the group ID
|
||||
from,
|
||||
message_id: messageId,
|
||||
sent_at: sentAt,
|
||||
|
|
@ -79,7 +222,25 @@ const receiveSignalMessageTask = async ({
|
|||
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 });
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ interface SendSignalMessageTaskOptions {
|
|||
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 ({
|
||||
|
|
@ -14,7 +17,16 @@ const sendSignalMessageTask = async ({
|
|||
to,
|
||||
message,
|
||||
conversationId,
|
||||
quoteMessage,
|
||||
quoteAuthor,
|
||||
quoteTimestamp,
|
||||
}: SendSignalMessageTaskOptions): Promise<void> => {
|
||||
console.log(`[send-signal-message] Processing outgoing message:`, {
|
||||
token,
|
||||
to,
|
||||
conversationId,
|
||||
messageLength: message?.length,
|
||||
});
|
||||
const bot = await db
|
||||
.selectFrom("SignalBot")
|
||||
.selectAll()
|
||||
|
|
@ -39,6 +51,13 @@ const sendSignalMessageTask = async ({
|
|||
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) {
|
||||
|
|
@ -54,10 +73,43 @@ const sendSignalMessageTask = async ({
|
|||
});
|
||||
|
||||
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(
|
||||
`Created new Signal group ${finalTo} for conversation ${conversationId} with ${to}`,
|
||||
`[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
|
||||
|
|
@ -68,26 +120,60 @@ const sendSignalMessageTask = async ({
|
|||
conversation_id: conversationId,
|
||||
original_recipient: to,
|
||||
group_id: finalTo,
|
||||
internal_group_id: internalId,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (groupError) {
|
||||
console.error("Error creating Signal group:", 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: {
|
||||
number,
|
||||
recipients: [finalTo],
|
||||
message,
|
||||
},
|
||||
data: messageData,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`Message sent successfully to ${finalTo}${groupCreated ? " (new group)" : ""}`,
|
||||
`[send-signal-message] Message sent successfully:`,
|
||||
{
|
||||
to: finalTo,
|
||||
groupCreated,
|
||||
response: response?.timestamp || 'no timestamp',
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error({ error });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue