2021-08-01 16:28:47 +00:00
|
|
|
import { getConfig } from "blitz";
|
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
|
|
|
|
import twilio from "twilio";
|
|
|
|
import webpush, { PushSubscription, WebPushError } from "web-push";
|
|
|
|
|
|
|
|
import db from "../../../../db";
|
|
|
|
import appLogger from "../../../../integrations/logger";
|
|
|
|
|
|
|
|
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
|
|
|
|
const logger = appLogger.child({ queue: "notify-incoming-message" });
|
|
|
|
|
|
|
|
type Payload = {
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId: string;
|
|
|
|
phoneNumberId: string;
|
2021-08-01 16:28:47 +00:00
|
|
|
messageSid: MessageInstance["sid"];
|
|
|
|
};
|
|
|
|
|
|
|
|
const notifyIncomingMessageQueue = Queue<Payload>(
|
|
|
|
"api/queue/notify-incoming-message",
|
2021-08-05 17:07:15 +00:00
|
|
|
async ({ messageSid, organizationId, phoneNumberId }) => {
|
2021-08-01 16:28:47 +00:00
|
|
|
webpush.setVapidDetails(
|
|
|
|
"mailto:mokht@rmi.al",
|
|
|
|
publicRuntimeConfig.webPush.publicKey,
|
|
|
|
serverRuntimeConfig.webPush.privateKey,
|
|
|
|
);
|
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const organization = await db.organization.findFirst({
|
|
|
|
where: { id: organizationId },
|
|
|
|
});
|
|
|
|
if (!organization || !organization.twilioAccountSid || !organization.twilioAuthToken) {
|
2021-08-01 16:28:47 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const message = await twilio(organization.twilioAccountSid, organization.twilioAuthToken)
|
|
|
|
.messages.get(messageSid)
|
|
|
|
.fetch();
|
2021-08-01 16:28:47 +00:00
|
|
|
const notification = { message: `${message.from} - ${message.body}` };
|
2021-08-05 17:07:15 +00:00
|
|
|
const subscriptions = await db.notificationSubscription.findMany({ where: { organizationId, phoneNumberId } });
|
2021-08-01 16:28:47 +00:00
|
|
|
await Promise.all(
|
|
|
|
subscriptions.map(async (subscription) => {
|
|
|
|
const webPushSubscription: PushSubscription = {
|
|
|
|
endpoint: subscription.endpoint,
|
|
|
|
keys: {
|
|
|
|
p256dh: subscription.keys_p256dh,
|
|
|
|
auth: subscription.keys_auth,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
|
|
|
await webpush.sendNotification(webPushSubscription, JSON.stringify(notification));
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
|
|
|
if (error instanceof WebPushError) {
|
2021-08-02 13:43:27 +00:00
|
|
|
// subscription most likely expired or has been revoked
|
2021-08-01 16:28:47 +00:00
|
|
|
await db.notificationSubscription.delete({ where: { id: subscription.id } });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
export default notifyIncomingMessageQueue;
|