2021-08-01 10:54:51 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
|
|
|
|
|
2021-08-30 12:53:21 +00:00
|
|
|
import db from "../../../../db";
|
2021-08-01 10:54:51 +00:00
|
|
|
import { encrypt } from "../../../../db/_encryption";
|
2021-08-05 17:07:15 +00:00
|
|
|
import notifyIncomingMessageQueue from "./notify-incoming-message";
|
2021-08-30 12:53:21 +00:00
|
|
|
import getTwilioClient, { translateMessageDirection, translateMessageStatus } from "../../../../integrations/twilio";
|
2021-08-01 10:54:51 +00:00
|
|
|
|
|
|
|
type Payload = {
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId: string;
|
|
|
|
phoneNumberId: string;
|
2021-08-01 10:54:51 +00:00
|
|
|
messageSid: MessageInstance["sid"];
|
|
|
|
};
|
|
|
|
|
|
|
|
const insertIncomingMessageQueue = Queue<Payload>(
|
|
|
|
"api/queue/insert-incoming-message",
|
2021-08-05 17:07:15 +00:00
|
|
|
async ({ messageSid, organizationId, phoneNumberId }) => {
|
|
|
|
const organization = await db.organization.findFirst({
|
|
|
|
where: { id: organizationId },
|
|
|
|
});
|
2021-08-08 04:28:19 +00:00
|
|
|
if (!organization) {
|
2021-08-01 10:54:51 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-08-08 04:28:19 +00:00
|
|
|
const twilioClient = getTwilioClient(organization);
|
|
|
|
const message = await twilioClient.messages.get(messageSid).fetch();
|
2021-08-01 10:54:51 +00:00
|
|
|
await db.message.create({
|
|
|
|
data: {
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId,
|
|
|
|
phoneNumberId,
|
|
|
|
id: messageSid,
|
2021-08-01 10:54:51 +00:00
|
|
|
to: message.to,
|
|
|
|
from: message.from,
|
2021-08-30 12:53:21 +00:00
|
|
|
status: translateMessageStatus(message.status),
|
|
|
|
direction: translateMessageDirection(message.direction),
|
2021-08-01 10:54:51 +00:00
|
|
|
sentAt: message.dateCreated,
|
2021-08-05 17:07:15 +00:00
|
|
|
content: encrypt(message.body, organization.encryptionKey),
|
2021-08-01 10:54:51 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
await notifyIncomingMessageQueue.enqueue(
|
|
|
|
{
|
|
|
|
messageSid,
|
|
|
|
organizationId,
|
|
|
|
phoneNumberId,
|
2021-08-01 10:54:51 +00:00
|
|
|
},
|
2021-08-05 17:07:15 +00:00
|
|
|
{ id: `notify-${messageSid}-${organizationId}-${phoneNumberId}` },
|
|
|
|
);
|
2021-08-01 12:04:04 +00:00
|
|
|
},
|
2021-08-01 10:54:51 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
export default insertIncomingMessageQueue;
|