shellphone.app/app/settings/api/queue/set-twilio-webhooks.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
import type twilio from "twilio";
2021-08-08 04:26:15 +00:00
import type { ApplicationInstance } from "twilio/lib/rest/api/v2010/account/application";
2021-07-31 14:33:18 +00:00
2021-10-15 23:25:13 +00:00
import db from "db";
import getTwilioClient, { getTwiMLName, smsUrl, voiceUrl } from "integrations/twilio";
2021-07-31 14:33:18 +00:00
type Payload = {
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
};
2021-07-31 14:33:18 +00:00
2021-08-05 17:07:15 +00:00
const setTwilioWebhooks = Queue<Payload>("api/queue/set-twilio-webhooks", async ({ organizationId, phoneNumberId }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
2021-08-05 17:07:15 +00:00
const organization = phoneNumber.organization;
const twilioClient = getTwilioClient(organization);
const twimlApp = await getTwimlApplication(twilioClient, organization.twimlAppSid);
2021-08-01 14:03:49 +00:00
const twimlAppSid = twimlApp.sid;
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
await Promise.all([
2021-08-05 17:07:15 +00:00
db.organization.update({
where: { id: organizationId },
data: { twimlAppSid },
2021-08-08 04:26:15 +00:00
}),
twilioClient.incomingPhoneNumbers.get(phoneNumber.id).update({
2021-08-08 04:26:15 +00:00
smsApplicationSid: twimlAppSid,
voiceApplicationSid: twimlAppSid,
2021-08-01 14:03:49 +00:00
}),
]);
});
2021-07-31 14:33:18 +00:00
2021-08-08 04:26:15 +00:00
async function getTwimlApplication(
twilioClient: twilio.Twilio,
organizationTwimlAppSid: string | null,
): Promise<ApplicationInstance> {
try {
if (organizationTwimlAppSid) {
return await updateTwimlApplication(twilioClient, organizationTwimlAppSid);
2021-08-08 04:26:15 +00:00
}
} catch {
// twiml app with sid `organizationTwimlAppSid` probably doesn't exist anymore
}
const twimlApps = await twilioClient.applications.list();
const twimlApp = twimlApps.find((app) => app.friendlyName.startsWith("Shellphone"));
2021-08-08 04:26:15 +00:00
if (twimlApp) {
return updateTwimlApplication(twilioClient, twimlApp.sid);
}
return twilioClient.applications.create({
friendlyName: getTwiMLName(),
smsUrl,
2021-08-08 04:26:15 +00:00
smsMethod: "POST",
voiceUrl,
2021-08-08 04:26:15 +00:00
voiceMethod: "POST",
});
}
async function updateTwimlApplication(twilioClient: twilio.Twilio, twimlAppSid: string) {
await twilioClient.applications.get(twimlAppSid).update({
friendlyName: getTwiMLName(),
smsUrl,
2021-08-08 04:26:15 +00:00
smsMethod: "POST",
voiceUrl,
2021-08-08 04:26:15 +00:00
voiceMethod: "POST",
});
return twilioClient.applications.get(twimlAppSid).fetch();
}
export default setTwilioWebhooks;