feat: Add attachment support for Signal and WhatsApp channels
- Signal: Use base64Attachments field in signal-cli-rest-api - WhatsApp: Implement Baileys attachment sending for images, videos, audio, and documents - Both channels retrieve attachments from Zammad Store model - Support multiple attachments per message
This commit is contained in:
parent
9139c8e8de
commit
d2a3c71bcd
8 changed files with 255 additions and 85 deletions
|
|
@ -3,7 +3,7 @@ import { createLogger } from "@link-stack/logger";
|
|||
import * as signalApi from "@link-stack/signal-api";
|
||||
const { Configuration, MessagesApi, GroupsApi } = signalApi;
|
||||
|
||||
const logger = createLogger('bridge-worker-send-signal-message');
|
||||
const logger = createLogger("bridge-worker-send-signal-message");
|
||||
|
||||
interface SendSignalMessageTaskOptions {
|
||||
token: string;
|
||||
|
|
@ -13,6 +13,11 @@ interface SendSignalMessageTaskOptions {
|
|||
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;
|
||||
}>;
|
||||
}
|
||||
|
||||
const sendSignalMessageTask = async ({
|
||||
|
|
@ -23,13 +28,17 @@ const sendSignalMessageTask = async ({
|
|||
quoteMessage,
|
||||
quoteAuthor,
|
||||
quoteTimestamp,
|
||||
attachments,
|
||||
}: SendSignalMessageTaskOptions): Promise<void> => {
|
||||
logger.debug({
|
||||
token,
|
||||
to,
|
||||
conversationId,
|
||||
messageLength: message?.length,
|
||||
}, 'Processing outgoing message');
|
||||
logger.debug(
|
||||
{
|
||||
token,
|
||||
to,
|
||||
conversationId,
|
||||
messageLength: message?.length,
|
||||
},
|
||||
"Processing outgoing message",
|
||||
);
|
||||
const bot = await db
|
||||
.selectFrom("SignalBot")
|
||||
.selectAll()
|
||||
|
|
@ -58,12 +67,16 @@ const sendSignalMessageTask = async ({
|
|||
const isGroupId = isUUID || isGroupPrefix || isBase64;
|
||||
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
|
||||
|
||||
logger.debug({
|
||||
to,
|
||||
isGroupId,
|
||||
enableAutoGroups,
|
||||
shouldCreateGroup: enableAutoGroups && !isGroupId && to && conversationId,
|
||||
}, 'Recipient analysis');
|
||||
logger.debug(
|
||||
{
|
||||
to,
|
||||
isGroupId,
|
||||
enableAutoGroups,
|
||||
shouldCreateGroup:
|
||||
enableAutoGroups && !isGroupId && to && conversationId,
|
||||
},
|
||||
"Recipient analysis",
|
||||
);
|
||||
|
||||
// If sending to a phone number and auto-groups is enabled, create a group first
|
||||
if (enableAutoGroups && !isGroupId && to && conversationId) {
|
||||
|
|
@ -93,7 +106,7 @@ const sendSignalMessageTask = async ({
|
|||
const createdGroup = groups.find((g) => g.id === finalTo);
|
||||
if (createdGroup && createdGroup.internalId) {
|
||||
internalId = createdGroup.internalId;
|
||||
logger.debug({ internalId }, 'Got actual internalId');
|
||||
logger.debug({ internalId }, "Got actual internalId");
|
||||
} else {
|
||||
// Fallback: extract base64 part from ID
|
||||
if (finalTo.startsWith("group.")) {
|
||||
|
|
@ -101,20 +114,23 @@ const sendSignalMessageTask = async ({
|
|||
}
|
||||
}
|
||||
} catch (fetchError) {
|
||||
logger.debug('Could not fetch group details, using ID base64 part');
|
||||
logger.debug("Could not fetch group details, using ID base64 part");
|
||||
// Fallback: extract base64 part from ID
|
||||
if (finalTo.startsWith("group.")) {
|
||||
internalId = finalTo.substring(6);
|
||||
}
|
||||
}
|
||||
logger.debug({
|
||||
groupId: finalTo,
|
||||
internalId,
|
||||
groupName,
|
||||
conversationId,
|
||||
originalRecipient: to,
|
||||
botNumber: bot.phoneNumber,
|
||||
}, 'Created new Signal group');
|
||||
logger.debug(
|
||||
{
|
||||
groupId: finalTo,
|
||||
internalId,
|
||||
groupName,
|
||||
conversationId,
|
||||
originalRecipient: to,
|
||||
botNumber: bot.phoneNumber,
|
||||
},
|
||||
"Created new Signal group",
|
||||
);
|
||||
|
||||
// Notify Zammad about the new group ID via webhook
|
||||
await worker.addJob("common/notify-webhooks", {
|
||||
|
|
@ -130,23 +146,30 @@ const sendSignalMessageTask = async ({
|
|||
});
|
||||
}
|
||||
} catch (groupError) {
|
||||
logger.error({
|
||||
error: groupError instanceof Error ? groupError.message : groupError,
|
||||
to,
|
||||
conversationId,
|
||||
}, 'Error creating Signal group');
|
||||
logger.error(
|
||||
{
|
||||
error:
|
||||
groupError instanceof Error ? groupError.message : groupError,
|
||||
to,
|
||||
conversationId,
|
||||
},
|
||||
"Error creating Signal group",
|
||||
);
|
||||
// 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');
|
||||
logger.debug(
|
||||
{
|
||||
fromNumber: number,
|
||||
toRecipient: finalTo,
|
||||
originalTo: to,
|
||||
recipientChanged: to !== finalTo,
|
||||
groupCreated,
|
||||
isGroupRecipient: finalTo.startsWith("group."),
|
||||
},
|
||||
"Sending message via API",
|
||||
);
|
||||
|
||||
// Build the message data with optional quote parameters
|
||||
const messageData: signalApi.ApiSendMessageV2 = {
|
||||
|
|
@ -155,12 +178,15 @@ const sendSignalMessageTask = async ({
|
|||
message,
|
||||
};
|
||||
|
||||
logger.debug({
|
||||
number,
|
||||
recipients: [finalTo],
|
||||
message: message.substring(0, 50) + "...",
|
||||
hasQuoteParams: !!(quoteMessage && quoteAuthor && quoteTimestamp),
|
||||
}, 'Message data being sent');
|
||||
logger.debug(
|
||||
{
|
||||
number,
|
||||
recipients: [finalTo],
|
||||
message: message.substring(0, 50) + "...",
|
||||
hasQuoteParams: !!(quoteMessage && quoteAuthor && quoteTimestamp),
|
||||
},
|
||||
"Message data being sent",
|
||||
);
|
||||
|
||||
// Add quote parameters if all are provided
|
||||
if (quoteMessage && quoteAuthor && quoteTimestamp) {
|
||||
|
|
@ -168,43 +194,64 @@ const sendSignalMessageTask = async ({
|
|||
messageData.quoteAuthor = quoteAuthor;
|
||||
messageData.quoteMessage = quoteMessage;
|
||||
|
||||
logger.debug({
|
||||
quoteAuthor,
|
||||
quoteMessage: quoteMessage.substring(0, 50) + "...",
|
||||
quoteTimestamp,
|
||||
}, 'Including quote in message');
|
||||
logger.debug(
|
||||
{
|
||||
quoteAuthor,
|
||||
quoteMessage: quoteMessage.substring(0, 50) + "...",
|
||||
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",
|
||||
);
|
||||
}
|
||||
|
||||
const response = await messagesClient.v2SendPost({
|
||||
data: messageData,
|
||||
});
|
||||
|
||||
logger.debug({
|
||||
to: finalTo,
|
||||
groupCreated,
|
||||
response: response?.timestamp || "no timestamp",
|
||||
}, 'Message sent successfully');
|
||||
logger.debug(
|
||||
{
|
||||
to: finalTo,
|
||||
groupCreated,
|
||||
response: response?.timestamp || "no timestamp",
|
||||
},
|
||||
"Message sent successfully",
|
||||
);
|
||||
} 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,
|
||||
logger.error(
|
||||
{
|
||||
status: error.response.status,
|
||||
statusText: error.response.statusText,
|
||||
body: errorBody,
|
||||
sentTo: finalTo,
|
||||
messageDetails: {
|
||||
fromNumber: number,
|
||||
toRecipients: [finalTo],
|
||||
hasQuote: !!quoteMessage,
|
||||
},
|
||||
},
|
||||
}, 'Signal API error');
|
||||
"Signal API error",
|
||||
);
|
||||
} catch (e) {
|
||||
logger.error('Could not parse error response');
|
||||
logger.error("Could not parse error response");
|
||||
}
|
||||
}
|
||||
logger.error({ error }, 'Full error details');
|
||||
logger.error({ error }, "Full error details");
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,18 +1,24 @@
|
|||
import { db } from "@link-stack/bridge-common";
|
||||
import { createLogger } from "@link-stack/logger";
|
||||
|
||||
const logger = createLogger('bridge-worker-send-whatsapp-message');
|
||||
const logger = createLogger("bridge-worker-send-whatsapp-message");
|
||||
|
||||
interface SendWhatsappMessageTaskOptions {
|
||||
token: string;
|
||||
to: string;
|
||||
message: any;
|
||||
attachments?: Array<{
|
||||
data: string;
|
||||
filename: string;
|
||||
mime_type: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
const sendWhatsappMessageTask = async ({
|
||||
message,
|
||||
to,
|
||||
token,
|
||||
attachments,
|
||||
}: SendWhatsappMessageTaskOptions): Promise<void> => {
|
||||
const bot = await db
|
||||
.selectFrom("WhatsappBot")
|
||||
|
|
@ -21,13 +27,38 @@ const sendWhatsappMessageTask = async ({
|
|||
.executeTakeFirstOrThrow();
|
||||
|
||||
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${bot.id}/send`;
|
||||
const params = { message, phoneNumber: to };
|
||||
const params: any = { message, phoneNumber: to };
|
||||
|
||||
if (attachments && attachments.length > 0) {
|
||||
params.attachments = attachments;
|
||||
logger.debug(
|
||||
{
|
||||
attachmentCount: attachments.length,
|
||||
attachmentNames: attachments.map((att) => att.filename),
|
||||
},
|
||||
"Sending WhatsApp message with attachments",
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const errorText = await result.text();
|
||||
logger.error(
|
||||
{
|
||||
status: result.status,
|
||||
errorText,
|
||||
url,
|
||||
},
|
||||
"WhatsApp send failed",
|
||||
);
|
||||
throw new Error(`Failed to send message: ${result.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error({ error });
|
||||
throw new Error("Failed to send message");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue