shellphone.app/app/messages/api/queue/notify-incoming-message.ts

65 lines
2.0 KiB
TypeScript
Raw Normal View History

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));
2021-08-27 18:05:44 +00:00
} catch (error: any) {
2021-08-01 16:28:47 +00:00
logger.error(error);
if (error instanceof WebPushError) {
// 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;