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

88 lines
2.1 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;
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,
2024-06-05 15:12:48 +02:00
}: ReceiveSignalMessageTaskOptions): Promise<void> => {
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;
// Check if auto-group creation is enabled and this is NOT already a group message
const enableAutoGroups = process.env.BRIDGE_SIGNAL_AUTO_GROUPS === "true";
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) {
finalTo = createGroupResponse.id;
console.log(
`Created new Signal group ${finalTo} for conversation with ${from}`,
);
}
} catch (error) {
console.error("Error creating Signal group:", error);
// Continue with original 'to' if group creation fails
}
}
2024-06-05 15:12:48 +02:00
const payload = {
2025-06-10 14:02:21 +02:00
to: finalTo,
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,
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;