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,110 @@
import { useEffect, useState } from "react";
import { type TwilioError, Call, Device } from "@twilio/voice-sdk";
import { useFetcher } from "@remix-run/react";
import type { TwilioTokenLoaderData } from "~/features/phone-calls/loaders/twilio-token";
export default function useDevice() {
const jwt = useDeviceToken();
const [device, setDevice] = useState<Device | null>(null);
const [isDeviceReady, setIsDeviceReady] = useState(() => device?.state === Device.State.Registered);
useEffect(() => {
jwt.refresh();
}, []);
useEffect(() => {
if (jwt.token && device?.state === Device.State.Registered && device?.token !== jwt.token) {
device.updateToken(jwt.token);
}
}, [jwt.token, device]);
useEffect(() => {
if (!jwt.token || device?.state === Device.State.Registered) {
return;
}
const newDevice = new Device(jwt.token, {
codecPreferences: [Call.Codec.Opus, Call.Codec.PCMU],
sounds: {
[Device.SoundName.Disconnect]: undefined, // TODO
},
});
newDevice.register(); // TODO throwing an error
setDevice(newDevice);
}, [device?.state, jwt.token, setDevice]);
useEffect(() => {
if (!device) {
return;
}
device.on("registered", onDeviceRegistered);
device.on("unregistered", onDeviceUnregistered);
device.on("error", onDeviceError);
device.on("incoming", onDeviceIncoming);
device.on("tokenWillExpire", onTokenWillExpire);
return () => {
if (typeof device.off !== "function") {
return;
}
device.off("registered", onDeviceRegistered);
device.off("unregistered", onDeviceUnregistered);
device.off("error", onDeviceError);
device.off("incoming", onDeviceIncoming);
device.off("tokenWillExpire", onTokenWillExpire);
};
}, [device]);
return {
device,
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();
}
}
}
function useDeviceToken() {
const fetcher = useFetcher<TwilioTokenLoaderData>();
return {
token: fetcher.data,
refresh: () => fetcher.load("/outgoing-call/twilio-token"),
};
}

View File

@ -0,0 +1,100 @@
import { useCallback, useState } from "react";
import { useNavigate } from "@remix-run/react";
import type { Call } from "@twilio/voice-sdk";
import useDevice from "./use-device";
type Params = {
recipient: string;
onHangUp?: () => void;
};
export default function useMakeCall({ recipient, onHangUp }: Params) {
const navigate = useNavigate();
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null);
const [state, setState] = useState<State>("initial");
const { device, isDeviceReady } = useDevice();
const endCall = useCallback(
function endCall() {
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
outgoingConnection?.disconnect();
setState("call_ending");
setTimeout(() => {
setState("call_ended");
setTimeout(() => navigate("/keypad"), 100);
}, 150);
},
[outgoingConnection, navigate],
);
const makeCall = useCallback(
async function makeCall() {
if (!device || !isDeviceReady) {
console.warn("device is not ready yet, can't make the call");
return;
}
if (state !== "initial") {
return;
}
if (device.isBusy) {
console.error("device is busy, this shouldn't happen");
return;
}
setState("calling");
const params = { To: recipient };
const outgoingConnection = await device.connect({ params });
setOutgoingConnection(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.on("cancel", endCall);
outgoingConnection.on("disconnect", endCall);
},
[device, isDeviceReady, recipient, state],
);
const sendDigits = useCallback(
function sendDigits(digits: string) {
return outgoingConnection?.sendDigits(digits);
},
[outgoingConnection],
);
const hangUp = useCallback(
function hangUp() {
setState("call_ending");
outgoingConnection?.disconnect();
device?.disconnectAll();
device?.destroy();
onHangUp?.();
navigate("/keypad");
// TODO: outgoingConnection.off is not a function
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
},
[device, endCall, onHangUp, outgoingConnection, navigate],
);
return {
makeCall,
sendDigits,
hangUp,
state,
};
}
type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended";

View File

@ -0,0 +1,63 @@
import { type LoaderFunction } from "@remix-run/node";
import Twilio from "twilio";
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
import { encrypt } from "~/utils/encryption";
import db from "~/utils/db.server";
import { commitSession } from "~/utils/session.server";
import getTwilioClient from "~/utils/twilio.server";
export type TwilioTokenLoaderData = string;
const loader: LoaderFunction = async ({ request }) => {
const { user, organization, twilioAccount } = await requireLoggedIn(request);
if (!twilioAccount || !twilioAccount.twimlAppSid) {
throw new Error("unreachable");
}
const twilioClient = getTwilioClient(twilioAccount);
let shouldRefreshSession = false;
let { apiKeySid, apiKeySecret } = twilioAccount;
if (apiKeySid && apiKeySecret) {
try {
await twilioClient.keys.get(apiKeySid).fetch();
} catch (error: any) {
if (error.code !== 20404) {
throw error;
}
apiKeySid = null;
apiKeySecret = null;
}
}
if (!apiKeySid || !apiKeySecret) {
shouldRefreshSession = true;
const apiKey = await twilioClient.newKeys.create({ friendlyName: "Shellphone" });
apiKeySid = apiKey.sid;
apiKeySecret = apiKey.secret;
await db.twilioAccount.update({
where: { subAccountSid: twilioAccount.subAccountSid },
data: { apiKeySid: apiKey.sid, apiKeySecret: encrypt(apiKey.secret) },
});
}
const accessToken = new Twilio.jwt.AccessToken(twilioAccount.subAccountSid, apiKeySid, apiKeySecret, {
identity: `${organization.id}__${user.id}`,
ttl: 3600,
});
const grant = new Twilio.jwt.AccessToken.VoiceGrant({
outgoingApplicationSid: twilioAccount.twimlAppSid,
incomingAllow: true,
});
accessToken.addGrant(grant);
const headers = new Headers({ "Content-Type": "text/plain" });
if (shouldRefreshSession) {
const { session } = await refreshSessionData(request);
headers.set("Set-Cookie", await commitSession(session));
}
return new Response(accessToken.toJwt(), { headers });
};
export default loader;