letsgooooo receiving calls

This commit is contained in:
m5r
2022-06-15 01:28:32 +02:00
parent d452422355
commit a46a4a3861
11 changed files with 527 additions and 172 deletions

View File

@ -7,6 +7,7 @@ import Footer from "~/features/core/components/footer";
import ServiceWorkerUpdateNotifier from "~/features/core/components/service-worker-update-notifier";
import Notification from "~/features/core/components/notification";
import useServiceWorkerRevalidate from "~/features/core/hooks/use-service-worker-revalidate";
import useDevice from "~/features/phone-calls/hooks/use-device";
import footerStyles from "~/features/core/components/footer.css";
import appStyles from "~/styles/app.css";
@ -32,6 +33,7 @@ export const loader: LoaderFunction = async ({ request }) => {
};
export default function __App() {
useDevice();
useServiceWorkerRevalidate();
const matches = useMatches();
const hideFooter = matches.some((match) => match.handle?.hideFooter === true);

View File

@ -0,0 +1,86 @@
import { useCallback, useEffect } 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 useReceiveCall from "~/features/phone-calls/hooks/use-receive-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 IncomingCallPage() {
const params = useParams<{ recipient: string }>();
const recipient = decodeURIComponent(params.recipient ?? "");
const [phoneNumber, setPhoneNumber] = usePhoneNumber();
const onHangUp = useCallback(() => setPhoneNumber(""), [setPhoneNumber]);
const call = useReceiveCall({ onHangUp });
const { isDeviceReady } = useDevice();
const pressDigit = usePressDigit();
const onDigitPressProps = useCallback(
(digit: string) => ({
onPress() {
pressDigit(digit);
call.sendDigits(digit);
},
}),
[call, pressDigit],
);
useEffect(() => {
if (isDeviceReady) {
call.acceptCall();
}
}, [call, isDeviceReady]);
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

@ -9,6 +9,7 @@ import twilio from "twilio";
import { voiceUrl, translateCallStatus } from "~/utils/twilio.server";
import { decrypt } from "~/utils/encryption";
import { validate } from "~/utils/validation.server";
import { notify } from "~/utils/web-push.server";
export const action: ActionFunction = async ({ request }) => {
const twilioSignature = request.headers.get("X-Twilio-Signature") || request.headers.get("x-twilio-signature");
@ -18,96 +19,187 @@ export const action: ActionFunction = async ({ request }) => {
const formData = Object.fromEntries(await request.formData());
const isOutgoingCall = formData.Caller?.toString().startsWith("client:");
console.log("isOutgoingCall", isOutgoingCall);
if (isOutgoingCall) {
const validation = validate(validations.outgoing, formData);
if (validation.errors) {
logger.error(validation.errors);
return badRequest("");
}
return handleOutgoingCall(formData, twilioSignature);
}
const body = validation.data;
const recipient = body.To;
const accountSid = body.From.slice("client:".length).split("__")[0];
return handleIncomingCall(formData, twilioSignature);
};
try {
const twilioAccount = await db.twilioAccount.findUnique({ where: { accountSid } });
if (!twilioAccount) {
// this shouldn't be happening
return new Response(null, { status: 402 });
}
async function handleIncomingCall(formData: unknown, twilioSignature: string) {
console.log("formData", formData);
const validation = validate(validations.incoming, formData);
if (validation.errors) {
logger.error(validation.errors);
return badRequest("");
}
const phoneNumber = await db.phoneNumber.findUnique({
where: { twilioAccountSid_isCurrent: { twilioAccountSid: twilioAccount.accountSid, isCurrent: true } },
const body = validation.data;
const phoneNumber = await db.phoneNumber.findFirst({
where: {
number: body.To,
twilioAccountSid: body.AccountSid,
},
include: {
twilioAccount: {
include: {
twilioAccount: {
include: {
organization: {
select: {
subscriptions: {
where: {
OR: [
{ status: { not: SubscriptionStatus.deleted } },
{
status: SubscriptionStatus.deleted,
cancellationEffectiveDate: { gt: new Date() },
},
],
organization: {
select: {
subscriptions: {
where: {
OR: [
{ status: { not: SubscriptionStatus.deleted } },
{
status: SubscriptionStatus.deleted,
cancellationEffectiveDate: { gt: new Date() },
},
orderBy: { lastEventTime: Prisma.SortOrder.desc },
},
],
},
orderBy: { lastEventTime: Prisma.SortOrder.desc },
},
memberships: {
select: { user: true },
},
},
},
},
});
if (phoneNumber?.twilioAccount.organization.subscriptions.length === 0) {
// decline the outgoing call because
// the organization is on the free plan
console.log("no active subscription"); // TODO: uncomment the line below
// return new Response(null, { status: 402 });
}
const encryptedAuthToken = phoneNumber?.twilioAccount.authToken;
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);
}
},
},
});
if (!phoneNumber) {
// this shouldn't be happening
return new Response(null, { status: 402 });
}
};
if (phoneNumber.twilioAccount.organization.subscriptions.length === 0) {
// decline the outgoing call because
// the organization is on the free plan
console.log("no active subscription"); // TODO: uncomment the line below
// return new Response(null, { status: 402 });
}
const encryptedAuthToken = phoneNumber.twilioAccount.authToken;
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.From,
from: body.From,
to: body.To,
status: translateCallStatus(body.CallStatus),
direction: Direction.Outbound,
duration: "0",
phoneNumberId: phoneNumber.id,
},
});
// await notify(); TODO
const user = phoneNumber.twilioAccount.organization.memberships[0].user!;
const identity = `${phoneNumber.twilioAccount.accountSid}__${user.id}`;
const voiceResponse = new twilio.twiml.VoiceResponse();
const dial = voiceResponse.dial({ answerOnBridge: true });
dial.client(identity);
console.log("twiml voiceResponse", voiceResponse.toString());
return new Response(voiceResponse.toString(), { headers: { "Content-Type": "text/xml" } });
}
async function handleOutgoingCall(formData: unknown, twilioSignature: string) {
const validation = validate(validations.outgoing, formData);
if (validation.errors) {
logger.error(validation.errors);
return badRequest("");
}
const body = validation.data;
const recipient = body.To;
const accountSid = body.From.slice("client:".length).split("__")[0];
try {
const twilioAccount = await db.twilioAccount.findUnique({
where: { accountSid },
include: {
organization: {
select: {
subscriptions: {
where: {
OR: [
{ status: { not: SubscriptionStatus.deleted } },
{
status: SubscriptionStatus.deleted,
cancellationEffectiveDate: { gt: new Date() },
},
],
},
orderBy: { lastEventTime: Prisma.SortOrder.desc },
},
},
},
},
});
if (!twilioAccount) {
// this shouldn't be happening
return new Response(null, { status: 402 });
}
const phoneNumber = await db.phoneNumber.findUnique({
where: { twilioAccountSid_isCurrent: { twilioAccountSid: twilioAccount.accountSid, isCurrent: true } },
});
if (!phoneNumber) {
// this shouldn't be happening
return new Response(null, { status: 402 });
}
if (twilioAccount.organization.subscriptions.length === 0) {
// decline the outgoing call because
// the organization is on the free plan
console.log("no active subscription"); // TODO: uncomment the line below
// return new Response(null, { status: 402 });
}
const encryptedAuthToken = twilioAccount.authToken;
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);
}
}
const CallStatus = z.union([
z.literal("busy"),
@ -140,6 +232,7 @@ const validations = {
ApplicationSid: z.string(),
CallSid: z.string(),
CallStatus,
CallToken: z.string(),
Called: z.string(),
CalledCity: z.string(),
CalledCountry: z.string(),