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("+33476982071")
.fetch();*/
try {
/*try {
await twilio(accountSid, authToken).messages.create({
body: "content",
to: "+213744123789",
@ -31,7 +31,12 @@ export default async function ddd(req: BlitzApiRequest, res: BlitzApiResponse) {
console.log(error.moreInfo);
console.log(error.details);
// 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);
}

View File

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

View File

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

View File

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

View File

@ -37,21 +37,36 @@ export default async function incomingMessageHandler(req: BlitzApiRequest, res:
}
console.log("req.body", req.body);
// TODO: return 200 and process this in the background
try {
const phoneNumber = req.body.To;
const customerPhoneNumber = await db.phoneNumber.findFirst({
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({
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(
customer!.authToken!,
customer.authToken,
twilioSignature,
url,
req.body
);
console.log("isRequestValid", isRequestValid);
if (!isRequestValid) {
const statusCode = 400;
const apiError: ApiError = {
@ -64,15 +79,22 @@ export default async function incomingMessageHandler(req: BlitzApiRequest, res:
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({
data: {
customerId: customer!.id,
to: req.body.To,
from: req.body.From,
status: MessageStatus.Received,
direction: Direction.Inbound,
sentAt: req.body.DateSent,
content: encrypt(req.body.Body, customer!.encryptionKey),
customerId: customer.id,
to: message.to,
from: message.from,
status: translateStatus(message.status),
direction: translateDirection(message.direction),
sentAt: message.dateCreated,
content: encrypt(message.body, customer.encryptionKey),
},
});
} 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 {
switch (direction) {
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">
<ul ref={messagesListRef}>
{conversation.length === 0 ? "empty state" : null}
{conversation.map((message, index) => {
const isOutbound = message.direction === Direction.Outbound;
const nextMessage = conversation![index + 1];

View File

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

View File

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