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

260 lines
7.5 KiB
TypeScript
Raw Normal View History

2025-06-10 14:02:21 +02:00
import { db, getWorkerUtils } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
2024-06-05 15:12:48 +02:00
import * as signalApi from "@link-stack/signal-api";
2025-06-10 14:02:21 +02:00
const { Configuration, MessagesApi, GroupsApi } = signalApi;
2024-04-30 13:13:49 +02:00
const logger = createLogger("bridge-worker-send-signal-message");
2024-04-30 13:13:49 +02:00
interface SendSignalMessageTaskOptions {
2024-06-05 15:12:48 +02:00
token: string;
2024-07-18 11:08:01 +02:00
to: string;
2024-04-30 13:13:49 +02:00
message: any;
2025-06-10 14:02:21 +02:00
conversationId?: string; // Zammad ticket/conversation ID for callback
2025-07-07 20:02:54 +02:00
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
attachments?: Array<{
data: string; // base64
filename: string;
mime_type: string;
}>;
2024-04-30 13:13:49 +02:00
}
const sendSignalMessageTask = async ({
2024-06-05 15:12:48 +02:00
token,
2024-07-18 11:08:01 +02:00
to,
message,
2025-06-10 14:02:21 +02:00
conversationId,
2025-07-07 20:02:54 +02:00
quoteMessage,
quoteAuthor,
quoteTimestamp,
attachments,
2024-06-05 15:12:48 +02:00
}: SendSignalMessageTaskOptions): Promise<void> => {
logger.debug(
{
token,
to,
conversationId,
messageLength: message?.length,
},
"Processing outgoing message",
);
2024-06-05 15:12:48 +02:00
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);
2025-06-10 14:02:21 +02:00
const groupsClient = new GroupsApi(config);
const worker = await getWorkerUtils();
let finalTo = to;
let groupCreated = false;
2024-06-05 15:12:48 +02:00
2024-07-18 11:08:01 +02:00
try {
2025-07-08 18:03:01 +02:00
// Check if 'to' is a group ID (UUID format, group.base64 format, or base64) vs phone number
2025-08-20 10:20:36 +02:00
const isUUID =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
to,
);
const isGroupPrefix = to.startsWith("group.");
2025-07-08 18:03:01 +02:00
const isBase64 = /^[A-Za-z0-9+/]+=*$/.test(to) && to.length > 20; // Base64 internal_id
const isGroupId = isUUID || isGroupPrefix || isBase64;
2025-06-10 14:02:21 +02:00
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
2025-07-08 18:03:01 +02:00
logger.debug(
{
to,
isGroupId,
enableAutoGroups,
shouldCreateGroup:
enableAutoGroups && !isGroupId && to && conversationId,
},
"Recipient analysis",
);
2025-06-10 14:02:21 +02:00
// If sending to a phone number and auto-groups is enabled, create a group first
if (enableAutoGroups && !isGroupId && to && conversationId) {
try {
2025-08-20 10:20:36 +02:00
const groupName = `DPN Support Request: ${conversationId}`;
2025-06-10 14:02:21 +02:00
const createGroupResponse = await groupsClient.v1GroupsNumberPost({
number: bot.phoneNumber,
data: {
name: groupName,
members: [to],
description: "Private support conversation",
},
});
if (createGroupResponse.id) {
2025-07-08 18:03:01 +02:00
// The createGroupResponse.id already contains the full group identifier (group.BASE64)
finalTo = createGroupResponse.id;
groupCreated = true;
2025-08-20 10:20:36 +02:00
2025-07-08 18:03:01 +02:00
// Fetch the group details to get the actual internalId
let internalId: string | undefined;
try {
const groups = await groupsClient.v1GroupsNumberGet({
number: bot.phoneNumber,
});
2025-08-20 10:20:36 +02:00
const createdGroup = groups.find((g) => g.id === finalTo);
2025-07-08 18:03:01 +02:00
if (createdGroup && createdGroup.internalId) {
internalId = createdGroup.internalId;
logger.debug({ internalId }, "Got actual internalId");
2025-07-08 18:03:01 +02:00
} else {
// Fallback: extract base64 part from ID
2025-08-20 10:20:36 +02:00
if (finalTo.startsWith("group.")) {
2025-07-08 18:03:01 +02:00
internalId = finalTo.substring(6);
2025-07-07 20:02:54 +02:00
}
}
2025-07-08 18:03:01 +02:00
} catch (fetchError) {
logger.debug("Could not fetch group details, using ID base64 part");
2025-07-08 18:03:01 +02:00
// Fallback: extract base64 part from ID
2025-08-20 10:20:36 +02:00
if (finalTo.startsWith("group.")) {
2025-07-08 18:03:01 +02:00
internalId = finalTo.substring(6);
}
2025-07-07 20:02:54 +02:00
}
logger.debug(
{
groupId: finalTo,
internalId,
groupName,
conversationId,
originalRecipient: to,
botNumber: bot.phoneNumber,
},
"Created new Signal group",
);
2025-06-10 14:02:21 +02:00
// 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,
2025-07-07 20:02:54 +02:00
internal_group_id: internalId,
2025-06-10 14:02:21 +02:00
timestamp: new Date().toISOString(),
},
});
}
} catch (groupError) {
logger.error(
{
error:
groupError instanceof Error ? groupError.message : groupError,
to,
conversationId,
},
"Error creating Signal group",
);
2025-06-10 14:02:21 +02:00
// Continue with original recipient if group creation fails
}
}
logger.debug(
{
fromNumber: number,
toRecipient: finalTo,
originalTo: to,
recipientChanged: to !== finalTo,
groupCreated,
isGroupRecipient: finalTo.startsWith("group."),
},
"Sending message via API",
);
2025-07-08 18:03:01 +02:00
2025-07-07 20:02:54 +02:00
// Build the message data with optional quote parameters
const messageData: signalApi.ApiSendMessageV2 = {
number,
recipients: [finalTo],
message,
};
2025-08-20 10:20:36 +02:00
logger.debug(
{
number,
recipients: [finalTo],
2025-11-09 11:12:04 +01:00
messageLength: message?.length,
hasQuoteParams: !!(quoteMessage && quoteAuthor && quoteTimestamp),
},
"Message data being sent",
);
2025-07-07 20:02:54 +02:00
// Add quote parameters if all are provided
if (quoteMessage && quoteAuthor && quoteTimestamp) {
messageData.quoteTimestamp = quoteTimestamp;
messageData.quoteAuthor = quoteAuthor;
messageData.quoteMessage = quoteMessage;
2025-07-08 18:03:01 +02:00
logger.debug(
{
quoteAuthor,
2025-11-09 11:12:04 +01:00
quoteMessageLength: quoteMessage?.length,
quoteTimestamp,
},
"Including quote in message",
);
}
// Add attachments if provided
if (attachments && attachments.length > 0) {
messageData.base64Attachments = attachments.map((att) => att.data);
logger.debug(
{
attachmentCount: attachments.length,
attachmentNames: attachments.map((att) => att.filename),
},
"Including attachments in message",
);
2025-07-07 20:02:54 +02:00
}
2024-07-18 11:08:01 +02:00
const response = await messagesClient.v2SendPost({
2025-07-07 20:02:54 +02:00
data: messageData,
2024-07-18 11:08:01 +02:00
});
2025-06-10 14:02:21 +02:00
logger.debug(
{
to: finalTo,
groupCreated,
response: response?.timestamp || "no timestamp",
},
"Message sent successfully",
);
2025-07-08 18:03:01 +02:00
} catch (error: any) {
// Try to get the actual error message from the response
if (error.response) {
try {
const errorBody = await error.response.text();
logger.error(
{
status: error.response.status,
statusText: error.response.statusText,
body: errorBody,
sentTo: finalTo,
messageDetails: {
fromNumber: number,
toRecipients: [finalTo],
hasQuote: !!quoteMessage,
},
2025-07-08 18:03:01 +02:00
},
"Signal API error",
);
2025-07-08 18:03:01 +02:00
} catch (e) {
logger.error("Could not parse error response");
2025-07-08 18:03:01 +02:00
}
}
logger.error({ error }, "Full error details");
2024-07-18 11:08:01 +02:00
throw error;
}
2024-06-05 15:12:48 +02:00
};
2024-04-30 13:13:49 +02:00
export default sendSignalMessageTask;