2022-06-12 21:17:22 +00:00
|
|
|
import { Queue } from "~/utils/queue.server";
|
|
|
|
import db from "~/utils/db.server";
|
|
|
|
import logger from "~/utils/logger.server";
|
|
|
|
import { buildMessageNotificationPayload, notify } from "~/utils/web-push.server";
|
|
|
|
import getTwilioClient from "~/utils/twilio.server";
|
|
|
|
|
|
|
|
type Payload = {
|
|
|
|
messageSid: string;
|
|
|
|
phoneNumberId: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Queue<Payload>("notify incoming message", async ({ data }) => {
|
|
|
|
const { messageSid, phoneNumberId } = data;
|
|
|
|
const phoneNumber = await db.phoneNumber.findUnique({
|
|
|
|
where: { id: phoneNumberId },
|
|
|
|
select: {
|
|
|
|
twilioAccount: {
|
|
|
|
include: {
|
|
|
|
organization: {
|
|
|
|
select: {
|
|
|
|
memberships: {
|
|
|
|
select: { notificationSubscription: true },
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
if (!phoneNumber) {
|
|
|
|
logger.warn(`No phone number found with id=${phoneNumberId}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const subscriptions = phoneNumber.twilioAccount.organization.memberships.flatMap(
|
|
|
|
(membership) => membership.notificationSubscription,
|
|
|
|
);
|
|
|
|
|
|
|
|
const twilioClient = getTwilioClient(phoneNumber.twilioAccount);
|
|
|
|
const message = await twilioClient.messages.get(messageSid).fetch();
|
|
|
|
const payload = buildMessageNotificationPayload(message);
|
|
|
|
|
2022-06-14 23:28:32 +00:00
|
|
|
// TODO: implement WS/SSE to push new messages for users who haven't enabled push notifications
|
2022-06-12 21:17:22 +00:00
|
|
|
await notify(subscriptions, payload);
|
|
|
|
});
|