handle incoming sms

This commit is contained in:
m5r 2021-08-01 18:36:32 +08:00
parent 56e8880715
commit 6cbc7468fb
8 changed files with 87 additions and 17 deletions

View File

@ -20,7 +20,7 @@ export default async function ddd(req: BlitzApiRequest, res: BlitzApiResponse) {
// .phoneNumbers("+33613370787") // .phoneNumbers("+33613370787")
.phoneNumbers("+33476982071") .phoneNumbers("+33476982071")
.fetch();*/ .fetch();*/
try { /*try {
await twilio(accountSid, authToken).messages.create({ await twilio(accountSid, authToken).messages.create({
body: "content", body: "content",
to: "+213744123789", to: "+213744123789",
@ -31,7 +31,12 @@ export default async function ddd(req: BlitzApiRequest, res: BlitzApiResponse) {
console.log(error.moreInfo); console.log(error.moreInfo);
console.log(error.details); console.log(error.details);
// console.log(JSON.stringify(Object.keys(error))); // console.log(JSON.stringify(Object.keys(error)));
} }*/
const ddd = await twilio(accountSid, authToken).messages.create({
body: "content",
to: "+33757592025",
from: "+33757592722",
});
res.status(200).send(ddd); res.status(200).send(ddd);
} }

View File

@ -21,7 +21,7 @@ const fetchMessagesQueue = Queue<Payload>("api/queue/fetch-messages", async ({ c
}), }),
]); ]);
const messages = [...messagesSent, ...messagesReceived].sort( const messages = [...messagesSent, ...messagesReceived].sort(
(a, b) => a.dateSent.getTime() - b.dateSent.getTime() (a, b) => a.dateCreated.getTime() - b.dateCreated.getTime()
); );
await insertMessagesQueue.enqueue( await insertMessagesQueue.enqueue(

View File

@ -24,7 +24,7 @@ const insertMessagesQueue = Queue<Payload>(
status: translateStatus(message.status), status: translateStatus(message.status),
direction: translateDirection(message.direction), direction: translateDirection(message.direction),
twilioSid: message.sid, twilioSid: message.sid,
sentAt: new Date(message.dateSent), sentAt: new Date(message.dateCreated),
})) }))
.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime()); .sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());

View File

@ -1,6 +1,14 @@
import type { ErrorInfo, FunctionComponent } from "react"; import type { ErrorInfo, FunctionComponent } from "react";
import { Component } from "react"; import { Component } from "react";
import { Head, withRouter } from "blitz"; import {
Head,
withRouter,
AuthenticationError,
AuthorizationError,
CSRFTokenMismatchError,
NotFoundError,
RedirectError,
} from "blitz";
import type { WithRouterProps } from "next/dist/client/with-router"; import type { WithRouterProps } from "next/dist/client/with-router";
import appLogger from "../../../../integrations/logger"; import appLogger from "../../../../integrations/logger";
@ -52,6 +60,14 @@ type ErrorBoundaryState =
errorMessage: string; errorMessage: string;
}; };
const blitzErrorNames = [
RedirectError.name,
AuthenticationError.name,
AuthorizationError.name,
CSRFTokenMismatchError.name,
NotFoundError.name,
];
const ErrorBoundary = withRouter( const ErrorBoundary = withRouter(
class ErrorBoundary extends Component<WithRouterProps, ErrorBoundaryState> { class ErrorBoundary extends Component<WithRouterProps, ErrorBoundaryState> {
public readonly state = { public readonly state = {
@ -67,6 +83,10 @@ const ErrorBoundary = withRouter(
public componentDidCatch(error: Error, errorInfo: ErrorInfo) { public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
logger.error(error, errorInfo.componentStack); logger.error(error, errorInfo.componentStack);
if (blitzErrorNames.includes(error.name)) {
// let Blitz ErrorBoundary handle this one
throw error;
}
} }
public render() { public render() {

View File

@ -37,21 +37,36 @@ export default async function incomingMessageHandler(req: BlitzApiRequest, res:
} }
console.log("req.body", req.body); console.log("req.body", req.body);
// TODO: return 200 and process this in the background
try { try {
const phoneNumber = req.body.To; const phoneNumber = req.body.To;
const customerPhoneNumber = await db.phoneNumber.findFirst({ const customerPhoneNumber = await db.phoneNumber.findFirst({
where: { phoneNumber }, where: { phoneNumber },
}); });
console.log("customerPhoneNumber", customerPhoneNumber);
if (!customerPhoneNumber) {
// phone number is not registered by any customer
res.status(200).end();
return;
}
const customer = await db.customer.findFirst({ const customer = await db.customer.findFirst({
where: { id: customerPhoneNumber!.customerId }, where: { id: customerPhoneNumber.customerId },
}); });
const url = "https://phone.mokhtar.dev/api/webhook/incoming-message"; console.log("customer", customer);
if (!customer || !customer.authToken) {
res.status(200).end();
return;
}
const url = "https://4cbc3f38c23a.ngrok.io/api/webhook/incoming-message";
const isRequestValid = twilio.validateRequest( const isRequestValid = twilio.validateRequest(
customer!.authToken!, customer.authToken,
twilioSignature, twilioSignature,
url, url,
req.body req.body
); );
console.log("isRequestValid", isRequestValid);
if (!isRequestValid) { if (!isRequestValid) {
const statusCode = 400; const statusCode = 400;
const apiError: ApiError = { const apiError: ApiError = {
@ -64,15 +79,22 @@ export default async function incomingMessageHandler(req: BlitzApiRequest, res:
return; return;
} }
// TODO: send notification
const body: Body = req.body;
const messageSid = body.MessageSid;
const message = await twilio(customer.accountSid!, customer.authToken)
.messages.get(messageSid)
.fetch();
await db.message.create({ await db.message.create({
data: { data: {
customerId: customer!.id, customerId: customer.id,
to: req.body.To, to: message.to,
from: req.body.From, from: message.from,
status: MessageStatus.Received, status: translateStatus(message.status),
direction: Direction.Inbound, direction: translateDirection(message.direction),
sentAt: req.body.DateSent, sentAt: message.dateCreated,
content: encrypt(req.body.Body, customer!.encryptionKey), content: encrypt(message.body, customer.encryptionKey),
}, },
}); });
} catch (error) { } catch (error) {
@ -87,6 +109,28 @@ export default async function incomingMessageHandler(req: BlitzApiRequest, res:
} }
} }
type Body = {
ToCountry: string;
ToState: string;
SmsMessageSid: string;
NumMedia: string;
ToCity: string;
FromZip: string;
SmsSid: string;
FromState: string;
SmsStatus: string;
FromCity: string;
Body: string;
FromCountry: string;
To: string;
ToZip: string;
NumSegments: string;
MessageSid: string;
AccountSid: string;
From: string;
ApiVersion: string;
};
function translateDirection(direction: MessageInstance["direction"]): Direction { function translateDirection(direction: MessageInstance["direction"]): Direction {
switch (direction) { switch (direction) {
case "inbound": case "inbound":

View File

@ -20,6 +20,7 @@ export default function Conversation() {
<> <>
<div className="flex flex-col space-y-6 p-6 pt-12 pb-16"> <div className="flex flex-col space-y-6 p-6 pt-12 pb-16">
<ul ref={messagesListRef}> <ul ref={messagesListRef}>
{conversation.length === 0 ? "empty state" : null}
{conversation.map((message, index) => { {conversation.map((message, index) => {
const isOutbound = message.direction === Direction.Outbound; const isOutbound = message.direction === Direction.Outbound;
const nextMessage = conversation![index + 1]; const nextMessage = conversation![index + 1];

View File

@ -9,7 +9,7 @@ export default function useConversation(recipient: string) {
{ {
select(conversations) { select(conversations) {
if (!conversations[recipient]) { if (!conversations[recipient]) {
throw new Error("Conversation not found"); return [];
} }
return conversations[recipient]!; return conversations[recipient]!;

View File

@ -29,6 +29,6 @@ const Messages: BlitzPage = () => {
Messages.getLayout = (page) => <Layout title="Messages">{page}</Layout>; Messages.getLayout = (page) => <Layout title="Messages">{page}</Layout>;
Messages.authenticate = { redirectTo: Routes.SignIn() }; Messages.authenticate = { redirectTo: Routes.SignIn().pathname };
export default Messages; export default Messages;