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

@ -4,11 +4,13 @@ import { Transition } from "@headlessui/react";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import useNotifications, { notificationDataAtom } from "~/features/core/hooks/use-notifications"; import useNotifications, { notificationDataAtom } from "~/features/core/hooks/use-notifications";
import useCall from "~/features/phone-calls/hooks/use-call";
export default function Notification() { export default function Notification() {
useNotifications(); useNotifications();
const navigate = useNavigate(); const navigate = useNavigate();
const [notificationData] = useAtom(notificationDataAtom); const [notificationData] = useAtom(notificationDataAtom);
const [call, setCall] = useCall();
const [show, setShow] = useState(notificationData !== null); const [show, setShow] = useState(notificationData !== null);
const close = () => setShow(false); const close = () => setShow(false);
const actions = buildActions(); const actions = buildActions();
@ -78,7 +80,7 @@ export default function Notification() {
message: [ message: [
{ {
title: "Reply", title: "Reply",
onClick: () => { onClick() {
navigate(`/messages/${encodeURIComponent(notificationData.data.recipient)}`); navigate(`/messages/${encodeURIComponent(notificationData.data.recipient)}`);
close(); close();
}, },
@ -86,8 +88,21 @@ export default function Notification() {
{ title: "Close", onClick: close }, { title: "Close", onClick: close },
], ],
call: [ call: [
{ title: "Answer", onClick: close }, {
{ title: "Decline", onClick: close }, title: "Answer",
onClick() {
navigate(`/incoming-call/${encodeURIComponent(notificationData.data.recipient)}`);
close();
},
},
{
title: "Decline",
onClick() {
call?.reject();
setCall(null);
close();
},
},
], ],
}[notificationData.data.type]; }[notificationData.data.type];
} }

View File

@ -78,7 +78,7 @@ export default function useNotifications() {
function urlBase64ToUint8Array(base64String: string) { function urlBase64ToUint8Array(base64String: string) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4); const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/"); const base64 = (base64String + padding).replaceAll("-", "+").replaceAll("_", "/");
const rawData = window.atob(base64); const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length); const outputArray = new Uint8Array(rawData.length);

View File

@ -19,7 +19,7 @@ export default function useNotifications() {
channel.removeEventListener("message", eventHandler); channel.removeEventListener("message", eventHandler);
channel.close(); channel.close();
}; };
}, []); }, [setNotificationData]);
useEffect(() => { useEffect(() => {
if (!notificationData) { if (!notificationData) {
@ -28,7 +28,7 @@ export default function useNotifications() {
const timeout = setTimeout(() => setNotificationData(null), 5000); const timeout = setTimeout(() => setNotificationData(null), 5000);
return () => clearTimeout(timeout); return () => clearTimeout(timeout);
}, [notificationData]); }, [notificationData, setNotificationData]);
} }
export const notificationDataAtom = atom<NotificationPayload | null>(null); export const notificationDataAtom = atom<NotificationPayload | null>(null);

View File

@ -0,0 +1,60 @@
import { useCallback, useEffect } from "react";
import type { Call } from "@twilio/voice-sdk";
import { atom, useAtom } from "jotai";
export default function useCall() {
const [call, setCall] = useAtom(callAtom);
const endCall = useCallback(
function endCallFn() {
call?.removeListener("cancel", endCall);
call?.removeListener("disconnect", endCall);
call?.disconnect();
setCall(null);
},
[call, setCall],
);
const onError = useCallback(
function onErrorFn(error: any) {
call?.removeListener("cancel", endCall);
call?.removeListener("disconnect", endCall);
call?.disconnect();
setCall(null);
throw error; // TODO: might not get caught by error boundary
},
[call, setCall, endCall],
);
const eventHandlers = [
["error", onError],
["cancel", endCall],
["disconnect", endCall],
] as const;
for (const [eventName, handler] of eventHandlers) {
// register call event handlers
// one event at a time to only update the handlers that changed
// without resetting the other handlers
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
if (!call) {
return;
}
// if we already have this event handler registered, no need to re-register it
const listeners = call.listeners(eventName);
if (listeners.length > 0 && listeners.every((fn) => fn.toString() === handler.toString())) {
return;
}
call.on(eventName, handler);
return () => {
call.removeListener(eventName, handler);
};
}, [call, setCall, eventName, handler]);
}
return [call, setCall] as const;
}
const callAtom = atom<Call | null>(null);

View File

@ -1,18 +1,22 @@
import { useEffect, useState } from "react"; import { useCallback, useEffect } from "react";
import { useFetcher } from "@remix-run/react"; import { useFetcher } from "@remix-run/react";
import { type TwilioError, Call, Device } from "@twilio/voice-sdk"; import { type TwilioError, Call, Device } from "@twilio/voice-sdk";
import { useAtom, atom } from "jotai"; import { useAtom, atom } from "jotai";
import type { TwilioTokenLoaderData } from "~/features/phone-calls/loaders/twilio-token"; import type { TwilioTokenLoaderData } from "~/features/phone-calls/loaders/twilio-token";
import type { NotificationPayload } from "~/utils/web-push.server";
import useCall from "./use-call";
export default function useDevice() { export default function useDevice() {
const jwt = useDeviceToken(); const jwt = useDeviceToken();
const [device, setDevice] = useAtom(deviceAtom); const [device, setDevice] = useAtom(deviceAtom);
const [isDeviceReady, setIsDeviceReady] = useState(device?.state === Device.State.Registered); const [call, setCall] = useCall();
const [isDeviceReady, setIsDeviceReady] = useAtom(isDeviceReadyAtom);
useEffect(() => { useEffect(() => {
// init token // init token
jwt.refresh(); jwt.refresh();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => { useEffect(() => {
@ -31,8 +35,9 @@ export default function useDevice() {
}, },
}); });
newDevice.register(); newDevice.register();
(window as any).ddd = newDevice;
setDevice(newDevice); setDevice(newDevice);
}, [device, jwt.token]); }, [device, jwt.token, setDevice]);
useEffect(() => { useEffect(() => {
// refresh token // refresh token
@ -41,79 +46,111 @@ export default function useDevice() {
} }
}, [device, jwt.token]); }, [device, jwt.token]);
useEffect(() => { const onTokenWillExpire = useCallback(
if (!device) { function onTokenWillExpire() {
return; jwt.refresh();
} },
[jwt.refresh],
);
device.on("registered", onDeviceRegistered); const onDeviceRegistered = useCallback(
device.on("unregistered", onDeviceUnregistered); function onDeviceRegistered() {
device.on("error", onDeviceError); setIsDeviceReady(true);
device.on("incoming", onDeviceIncoming); },
device.on("tokenWillExpire", onTokenWillExpire); [setIsDeviceReady],
);
return () => { const onDeviceUnregistered = useCallback(
if (typeof device.off !== "function") { function onDeviceUnregistered() {
setIsDeviceReady(false);
},
[setIsDeviceReady],
);
const onDeviceError = useCallback(function onDeviceError(error: TwilioError.TwilioError, call?: Call) {
console.log("error", error);
// we might have to change this if we instantiate the device on every page to receive calls
// setDevice(() => {
// hack to trigger the error boundary
throw error;
// });
}, []);
const onDeviceIncoming = useCallback(
function onDeviceIncoming(incomingCall: Call) {
if (call) {
incomingCall.reject();
return; return;
} }
device.off("registered", onDeviceRegistered); setCall(incomingCall);
device.off("unregistered", onDeviceUnregistered); console.log("incomingCall.parameters", incomingCall.parameters);
device.off("error", onDeviceError); // TODO prevent making a new call when there is a pending incoming call
device.off("incoming", onDeviceIncoming); const channel = new BroadcastChannel("notifications");
device.off("tokenWillExpire", onTokenWillExpire); const recipient = incomingCall.parameters.From;
}; const message: NotificationPayload = {
}, [device]); title: recipient, // TODO:
body: "",
actions: [
{
action: "answer",
title: "Answer",
},
{
action: "decline",
title: "Decline",
},
],
data: { recipient, type: "call" },
};
channel.postMessage(JSON.stringify(message));
},
[call, setCall],
);
const eventHandlers = [
["registered", onDeviceRegistered],
["unregistered", onDeviceUnregistered],
["error", onDeviceError],
["incoming", onDeviceIncoming],
["tokenWillExpire", onTokenWillExpire],
] as const;
for (const [eventName, handler] of eventHandlers) {
// register device event handlers
// one event at a time to only update the handlers that changed
// without resetting the other handlers
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
if (!device) {
return;
}
// if we already have this event handler registered, no need to re-register it
const listeners = device.listeners(eventName);
if (listeners.length > 0 && listeners.every((fn) => fn.toString() === handler.toString())) {
return;
}
device.on(eventName, handler);
return () => {
device.removeListener(eventName, handler);
};
}, [device, eventName, handler]);
}
return { return {
device, device,
isDeviceReady, isDeviceReady,
}; };
function onTokenWillExpire() {
jwt.refresh();
}
function onDeviceRegistered() {
setIsDeviceReady(true);
}
function onDeviceUnregistered() {
setIsDeviceReady(false);
}
function onDeviceError(error: TwilioError.TwilioError, call?: Call) {
console.log("error", error);
// we might have to change this if we instantiate the device on every page to receive calls
setDevice(() => {
// hack to trigger the error boundary
throw error;
});
}
function onDeviceIncoming(call: Call) {
// TODO show alert to accept/reject the incoming call /!\ it should persist between screens /!\ prevent making a new call when there is a pending incoming call
console.log("call", call);
console.log("Incoming connection from " + call.parameters.From);
let archEnemyPhoneNumber = "+12093373517";
if (call.parameters.From === archEnemyPhoneNumber) {
call.reject();
console.log("It's your nemesis. Rejected call.");
} else {
// accept the incoming connection and start two-way audio
call.accept();
}
}
} }
const deviceAtom = atom<Device | null>(null); const deviceAtom = atom<Device | null>(null);
const isDeviceReadyAtom = atom(false);
function useDeviceToken() { function useDeviceToken() {
const fetcher = useFetcher<TwilioTokenLoaderData>(); const fetcher = useFetcher<TwilioTokenLoaderData>();
const refresh = useCallback(() => fetcher.load("/outgoing-call/twilio-token"), []);
return { return {
token: fetcher.data, token: fetcher.data,
refresh: () => fetcher.load("/outgoing-call/twilio-token"), refresh,
}; };
} }

View File

@ -3,6 +3,7 @@ import { useNavigate } from "@remix-run/react";
import type { Call } from "@twilio/voice-sdk"; import type { Call } from "@twilio/voice-sdk";
import useDevice from "./use-device"; import useDevice from "./use-device";
import useCall from "./use-call";
type Params = { type Params = {
recipient: string; recipient: string;
@ -11,28 +12,23 @@ type Params = {
export default function useMakeCall({ recipient, onHangUp }: Params) { export default function useMakeCall({ recipient, onHangUp }: Params) {
const navigate = useNavigate(); const navigate = useNavigate();
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null); const [call, setCall] = useCall();
const [state, setState] = useState<State>("initial"); const [state, setState] = useState<State>("initial");
const { device, isDeviceReady } = useDevice(); const { device, isDeviceReady } = useDevice();
const endCall = useCallback( const endCall = useCallback(
function endCall() { function endCall() {
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
outgoingConnection?.disconnect();
setState("call_ending"); setState("call_ending");
setTimeout(() => { setTimeout(() => {
setState("call_ended"); setState("call_ended");
setTimeout(() => navigate("/keypad"), 100); setTimeout(() => navigate("/keypad"), 100);
}, 150); }, 150);
}, },
[outgoingConnection, navigate], [navigate],
); );
const makeCall = useCallback( const makeCall = useCallback(
async function makeCall() { async function makeCall() {
console.log({ device, isDeviceReady });
if (!device || !isDeviceReady) { if (!device || !isDeviceReady) {
console.warn("device is not ready yet, can't make the call"); console.warn("device is not ready yet, can't make the call");
return; return;
@ -42,7 +38,7 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
return; return;
} }
if (device.isBusy) { if (device.isBusy || Boolean(call)) {
console.error("device is busy, this shouldn't happen"); console.error("device is busy, this shouldn't happen");
return; return;
} }
@ -51,43 +47,30 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
const params = { To: recipient }; const params = { To: recipient };
const outgoingConnection = await device.connect({ params }); const outgoingConnection = await device.connect({ params });
setOutgoingConnection(outgoingConnection); setCall(outgoingConnection);
outgoingConnection.on("error", (error) => {
outgoingConnection.off("cancel", endCall);
outgoingConnection.off("disconnect", endCall);
setState(() => {
// hack to trigger the error boundary
throw error;
});
});
outgoingConnection.once("accept", (call: Call) => setState("call_in_progress")); outgoingConnection.once("accept", (call: Call) => setState("call_in_progress"));
outgoingConnection.on("cancel", endCall); outgoingConnection.once("cancel", endCall);
outgoingConnection.on("disconnect", endCall); outgoingConnection.once("disconnect", endCall);
}, },
[device, isDeviceReady, recipient, state], [call, device, endCall, isDeviceReady, recipient, setCall, state],
); );
const sendDigits = useCallback( const sendDigits = useCallback(
function sendDigits(digits: string) { function sendDigits(digits: string) {
return outgoingConnection?.sendDigits(digits); return call?.sendDigits(digits);
}, },
[outgoingConnection], [call],
); );
const hangUp = useCallback( const hangUp = useCallback(
function hangUp() { function hangUp() {
setState("call_ending"); setState("call_ending");
outgoingConnection?.disconnect(); call?.disconnect();
device?.disconnectAll();
device?.destroy();
onHangUp?.(); onHangUp?.();
navigate("/keypad"); navigate("/keypad");
// TODO: outgoingConnection.off is not a function
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
}, },
[device, endCall, onHangUp, outgoingConnection, navigate], [call, onHangUp, navigate],
); );
return { return {

View File

@ -0,0 +1,78 @@
import { useCallback, useState } from "react";
import { useNavigate } from "@remix-run/react";
import useDevice from "./use-device";
import useCall from "./use-call";
type Params = {
onHangUp?: () => void;
};
export default function useMakeCall({ onHangUp }: Params) {
const navigate = useNavigate();
const [call] = useCall();
const [state, setState] = useState<State>("initial");
const { device, isDeviceReady } = useDevice();
const endCall = useCallback(
function endCall() {
setState("call_ending");
setTimeout(() => {
setState("call_ended");
setTimeout(() => navigate("/keypad"), 100);
}, 150);
},
[navigate],
);
const acceptCall = useCallback(
async function acceptCall() {
if (!device || !isDeviceReady) {
console.warn("device is not ready yet, can't make the call");
return;
}
if (state !== "initial") {
return;
}
if (device.isBusy || !call) {
console.error("device is busy, this shouldn't happen");
return;
}
call.accept();
setState("call_in_progress");
call.once("cancel", endCall);
call.once("disconnect", endCall);
},
[call, device, endCall, isDeviceReady, state],
);
const sendDigits = useCallback(
function sendDigits(digits: string) {
return call?.sendDigits(digits);
},
[call],
);
const hangUp = useCallback(
function hangUp() {
setState("call_ending");
call?.disconnect();
onHangUp?.();
navigate("/keypad");
},
[call, onHangUp, navigate],
);
return {
acceptCall,
sendDigits,
hangUp,
state,
};
}
type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended";

View File

@ -39,5 +39,6 @@ export default Queue<Payload>("notify incoming message", async ({ data }) => {
const message = await twilioClient.messages.get(messageSid).fetch(); const message = await twilioClient.messages.get(messageSid).fetch();
const payload = buildMessageNotificationPayload(message); const payload = buildMessageNotificationPayload(message);
// TODO: implement WS/SSE to push new messages for users who haven't enabled push notifications
await notify(subscriptions, payload); await notify(subscriptions, payload);
}); });

View File

@ -7,6 +7,7 @@ import Footer from "~/features/core/components/footer";
import ServiceWorkerUpdateNotifier from "~/features/core/components/service-worker-update-notifier"; import ServiceWorkerUpdateNotifier from "~/features/core/components/service-worker-update-notifier";
import Notification from "~/features/core/components/notification"; import Notification from "~/features/core/components/notification";
import useServiceWorkerRevalidate from "~/features/core/hooks/use-service-worker-revalidate"; 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 footerStyles from "~/features/core/components/footer.css";
import appStyles from "~/styles/app.css"; import appStyles from "~/styles/app.css";
@ -32,6 +33,7 @@ export const loader: LoaderFunction = async ({ request }) => {
}; };
export default function __App() { export default function __App() {
useDevice();
useServiceWorkerRevalidate(); useServiceWorkerRevalidate();
const matches = useMatches(); const matches = useMatches();
const hideFooter = matches.some((match) => match.handle?.hideFooter === true); 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 { voiceUrl, translateCallStatus } from "~/utils/twilio.server";
import { decrypt } from "~/utils/encryption"; import { decrypt } from "~/utils/encryption";
import { validate } from "~/utils/validation.server"; import { validate } from "~/utils/validation.server";
import { notify } from "~/utils/web-push.server";
export const action: ActionFunction = async ({ request }) => { export const action: ActionFunction = async ({ request }) => {
const twilioSignature = request.headers.get("X-Twilio-Signature") || request.headers.get("x-twilio-signature"); 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 formData = Object.fromEntries(await request.formData());
const isOutgoingCall = formData.Caller?.toString().startsWith("client:"); const isOutgoingCall = formData.Caller?.toString().startsWith("client:");
console.log("isOutgoingCall", isOutgoingCall);
if (isOutgoingCall) { if (isOutgoingCall) {
const validation = validate(validations.outgoing, formData); return handleOutgoingCall(formData, twilioSignature);
if (validation.errors) { }
logger.error(validation.errors);
return badRequest("");
}
const body = validation.data; return handleIncomingCall(formData, twilioSignature);
const recipient = body.To; };
const accountSid = body.From.slice("client:".length).split("__")[0];
try { async function handleIncomingCall(formData: unknown, twilioSignature: string) {
const twilioAccount = await db.twilioAccount.findUnique({ where: { accountSid } }); console.log("formData", formData);
if (!twilioAccount) { const validation = validate(validations.incoming, formData);
// this shouldn't be happening if (validation.errors) {
return new Response(null, { status: 402 }); logger.error(validation.errors);
} return badRequest("");
}
const phoneNumber = await db.phoneNumber.findUnique({ const body = validation.data;
where: { twilioAccountSid_isCurrent: { twilioAccountSid: twilioAccount.accountSid, isCurrent: true } }, const phoneNumber = await db.phoneNumber.findFirst({
where: {
number: body.To,
twilioAccountSid: body.AccountSid,
},
include: {
twilioAccount: {
include: { include: {
twilioAccount: { organization: {
include: { select: {
organization: { subscriptions: {
select: { where: {
subscriptions: { OR: [
where: { { status: { not: SubscriptionStatus.deleted } },
OR: [ {
{ status: { not: SubscriptionStatus.deleted } }, status: SubscriptionStatus.deleted,
{ cancellationEffectiveDate: { gt: new Date() },
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 if (!phoneNumber) {
// the organization is on the free plan // this shouldn't be happening
console.log("no active subscription"); // TODO: uncomment the line below return new Response(null, { status: 402 });
// 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.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([ const CallStatus = z.union([
z.literal("busy"), z.literal("busy"),
@ -140,6 +232,7 @@ const validations = {
ApplicationSid: z.string(), ApplicationSid: z.string(),
CallSid: z.string(), CallSid: z.string(),
CallStatus, CallStatus,
CallToken: z.string(),
Called: z.string(), Called: z.string(),
CalledCity: z.string(), CalledCity: z.string(),
CalledCountry: z.string(), CalledCountry: z.string(),