make a phone call ~ not really working

This commit is contained in:
m5r
2022-05-24 23:13:08 +02:00
parent c9c1784dd7
commit 8ad21ae9e1
15 changed files with 794 additions and 136 deletions

View File

@ -0,0 +1,80 @@
import { useCallback } from "react";
import type { MetaFunction } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { IoCall } from "react-icons/io5";
import { getSeoMeta } from "~/utils/seo";
import { usePhoneNumber, usePressDigit } from "~/features/keypad/hooks/atoms";
import useDevice from "~/features/phone-calls/hooks/use-device";
import useMakeCall from "~/features/phone-calls/hooks/use-make-call";
import Keypad from "~/features/keypad/components/keypad";
export const meta: MetaFunction = ({ params }) => {
const recipient = decodeURIComponent(params.recipient ?? "");
return {
...getSeoMeta({
title: `Calling ${recipient}`,
}),
};
};
export default function OutgoingCallPage() {
const params = useParams<{ recipient: string }>();
const recipient = decodeURIComponent(params.recipient ?? "");
const [phoneNumber, setPhoneNumber] = usePhoneNumber();
const onHangUp = useCallback(() => setPhoneNumber(""), [setPhoneNumber]);
const call = useMakeCall({ recipient, onHangUp });
const { isDeviceReady } = useDevice();
const pressDigit = usePressDigit();
const onDigitPressProps = useCallback(
(digit: string) => ({
onPress() {
pressDigit(digit);
call.sendDigits(digit);
},
}),
[call, pressDigit],
);
return (
<div className="w-96 h-full flex flex-col justify-around py-5 mx-auto text-center text-black bg-white">
<div className="h-16 text-3xl text-gray-700">
<span>{recipient}</span>
</div>
<div className="mb-4 text-gray-600">
<div className="h-8 text-2xl">{phoneNumber}</div>
<div className="h-8 text-lg">{translateState(call.state)}</div>
</div>
<Keypad onDigitPressProps={onDigitPressProps} onZeroPressProps={onDigitPressProps("0")}>
<button
onClick={call.hangUp}
className="cursor-pointer select-none col-start-2 h-12 w-12 flex justify-center items-center mx-auto bg-red-800 rounded-full"
>
<IoCall className="w-6 h-6 text-white" />
</button>
</Keypad>
</div>
);
function translateState(state: typeof call.state) {
switch (state) {
case "initial":
case "ready":
return "Connecting...";
case "calling":
return "Calling...";
case "call_in_progress":
return "In call"; // TODO display time elapsed
case "call_ending":
return "Call ending...";
case "call_ended":
return "Call ended";
}
}
}
export const handle = { hideFooter: true };

View File

@ -0,0 +1,3 @@
import twilioTokenLoader from "~/features/phone-calls/loaders/twilio-token";
export const loader = twilioTokenLoader;

View File

@ -1,10 +1,8 @@
import { type LoaderFunction, redirect } from "@remix-run/node";
import twilio from "twilio";
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
import { commitSession } from "~/utils/session.server";
import db from "~/utils/db.server";
import serverConfig from "~/config/config.server";
import getTwilioClient from "~/utils/twilio.server";
import fetchPhoneCallsQueue from "~/queues/fetch-phone-calls.server";
import fetchMessagesQueue from "~/queues/fetch-messages.server";
@ -18,29 +16,27 @@ export const loader: LoaderFunction = async ({ request }) => {
throw new Error("unreachable");
}
let twilioClient = twilio(twilioSubAccountSid, serverConfig.twilio.authToken);
let twilioClient = getTwilioClient({ accountSid: twilioSubAccountSid, subAccountSid: twilioSubAccountSid });
const twilioSubAccount = await twilioClient.api.accounts(twilioSubAccountSid).fetch();
const twilioMainAccountSid = twilioSubAccount.ownerAccountSid;
const twilioMainAccount = await twilioClient.api.accounts(twilioMainAccountSid).fetch();
console.log("twilioSubAccount", twilioSubAccount);
console.log("twilioAccount", twilioMainAccount);
const data = {
subAccountSid: twilioSubAccount.sid,
subAccountAuthToken: encrypt(twilioSubAccount.authToken),
accountSid: twilioMainAccount.sid,
};
const twilioAccount = await db.twilioAccount.upsert({
where: { organizationId: organization.id },
create: {
organization: {
connect: { id: organization.id },
},
subAccountSid: twilioSubAccount.sid,
subAccountAuthToken: encrypt(twilioSubAccount.authToken),
accountSid: twilioMainAccount.sid,
accountAuthToken: encrypt(twilioMainAccount.authToken),
},
update: {
subAccountSid: twilioSubAccount.sid,
subAccountAuthToken: encrypt(twilioSubAccount.authToken),
accountSid: twilioMainAccount.sid,
accountAuthToken: encrypt(twilioMainAccount.authToken),
...data,
},
update: data,
});
twilioClient = getTwilioClient(twilioAccount);

136
app/routes/webhooks/call.ts Normal file
View File

@ -0,0 +1,136 @@
import { type ActionFunction } from "@remix-run/node";
import { type CallInstance } from "twilio/lib/rest/api/v2010/account/call";
import { badRequest, serverError } from "remix-utils";
import { Direction, Prisma, SubscriptionStatus } from "@prisma/client";
import logger from "~/utils/logger.server";
import db from "~/utils/db.server";
import twilio from "twilio";
import { voiceUrl, translateCallStatus } from "~/utils/twilio.server";
import { decrypt } from "~/utils/encryption";
export const action: ActionFunction = async ({ request }) => {
const twilioSignature = request.headers.get("X-Twilio-Signature") || request.headers.get("x-twilio-signature");
if (!twilioSignature || Array.isArray(twilioSignature)) {
return badRequest("Invalid header X-Twilio-Signature");
}
const body: Body = await request.json();
const isOutgoingCall = body.From.startsWith("client:");
if (isOutgoingCall) {
const recipient = body.To;
const organizationId = body.From.slice("client:".length).split("__")[0];
try {
const phoneNumber = await db.phoneNumber.findUnique({
where: { organizationId_isCurrent: { organizationId, isCurrent: true } },
include: {
organization: {
include: {
subscriptions: {
where: {
OR: [
{ status: { not: SubscriptionStatus.deleted } },
{
status: SubscriptionStatus.deleted,
cancellationEffectiveDate: { gt: new Date() },
},
],
},
orderBy: { lastEventTime: Prisma.SortOrder.desc },
},
twilioAccount: true,
},
},
},
});
if (phoneNumber?.organization.subscriptions.length === 0) {
// decline the outgoing call because
// the organization is on the free plan
return new Response(null, { status: 402 });
}
const encryptedAuthToken = phoneNumber?.organization.twilioAccount?.subAccountAuthToken;
const authToken = encryptedAuthToken ? decrypt(encryptedAuthToken) : "";
if (
!phoneNumber ||
!encryptedAuthToken ||
!twilio.validateRequest(authToken, twilioSignature, voiceUrl, body)
) {
return badRequest("Invalid webhook");
}
await db.phoneCall.create({
data: {
id: body.CallSid,
recipient: body.To,
from: phoneNumber.number,
to: body.To,
status: translateCallStatus(body.CallStatus),
direction: Direction.Outbound,
duration: "0",
phoneNumberId: phoneNumber.id,
},
});
const voiceResponse = new twilio.twiml.VoiceResponse();
const dial = voiceResponse.dial({
answerOnBridge: true,
callerId: phoneNumber!.number,
});
dial.number(recipient);
console.log("twiml voiceResponse", voiceResponse.toString());
return new Response(voiceResponse.toString(), { headers: { "Content-Type": "text/xml" } });
} catch (error: any) {
logger.error(error);
return serverError(error.message);
}
}
};
type OutgoingCallBody = {
AccountSid: string;
ApiVersion: string;
ApplicationSid: string;
CallSid: string;
CallStatus: CallInstance["status"];
Called: string;
Caller: string;
Direction: `outbound${string}`;
From: string;
To: string;
};
type IncomingCallBody = {
AccountSid: string;
ApiVersion: string;
ApplicationSid: string;
CallSid: string;
CallStatus: CallInstance["status"];
Called: string;
CalledCity: string;
CalledCountry: string;
CalledState: string;
CalledZip: string;
Caller: string;
CallerCity: string;
CallerCountry: string;
CallerState: string;
CallerZip: string;
Direction: "inbound";
From: string;
FromCity: string;
FromCountry: string;
FromState: string;
FromZip: string;
To: string;
ToCity: string;
ToCountry: string;
ToState: string;
ToZip: string;
};
type Body = OutgoingCallBody | IncomingCallBody;

View File

@ -57,7 +57,7 @@ export const action: ActionFunction = async ({ request }) => {
// if multiple organizations have the same number
// find the organization currently using that phone number
// maybe we shouldn't let that happen by restricting a phone number to one org?
const encryptedAuthToken = phoneNumber.organization.twilioAccount?.accountAuthToken;
const encryptedAuthToken = phoneNumber.organization.twilioAccount?.subAccountAuthToken;
const authToken = encryptedAuthToken ? decrypt(encryptedAuthToken) : "";
return twilio.validateRequest(authToken, twilioSignature, smsUrl, body);
});