memoize hook functions and wrap up outgoing calls

This commit is contained in:
m5r 2021-09-05 00:29:25 +08:00
parent d5185fa183
commit 3433a90258
4 changed files with 106 additions and 85 deletions

View File

@ -1,16 +1,16 @@
import { useCallback, useEffect, useMemo } from "react"; import { useCallback, useEffect, useState } from "react";
import { useMutation } from "blitz"; import { useMutation } from "blitz";
import type { TwilioError } from "@twilio/voice-sdk"; import type { TwilioError } from "@twilio/voice-sdk";
import { Call, Device } from "@twilio/voice-sdk"; import { Call, Device } from "@twilio/voice-sdk";
import { atom, useAtom } from "jotai";
import getToken, { ttl } from "../mutations/get-token"; import getToken from "../mutations/get-token";
import appLogger from "../../../integrations/logger"; import appLogger from "../../../integrations/logger";
const logger = appLogger.child({ module: "use-device" }); const logger = appLogger.child({ module: "use-device" });
export default function useDevice() { export default function useDevice() {
const [device, setDevice] = useAtom(deviceAtom); const [device, setDevice] = useState<Device | null>(null);
const [isDeviceReady, setIsDeviceReady] = useState(() => device?.state === Device.State.Registered);
const [getTokenMutation] = useMutation(getToken); const [getTokenMutation] = useMutation(getToken);
const refreshToken = useCallback(async () => { const refreshToken = useCallback(async () => {
if (!device) { if (!device) {
@ -21,16 +21,13 @@ export default function useDevice() {
const token = await getTokenMutation(); const token = await getTokenMutation();
device.updateToken(token); device.updateToken(token);
}, [device, getTokenMutation]); }, [device, getTokenMutation]);
const isDeviceReady = useMemo(() => device?.state === Device.State.Registered, [device]);
useEffect(() => { useEffect(() => {
if (!isDeviceReady) { const intervalId = setInterval(() => {
return; return refreshToken();
} }, (3600 - 30) * 1000);
const intervalId = setInterval(refreshToken, (ttl - 30) * 1000);
return () => clearInterval(intervalId); return () => clearInterval(intervalId);
}, [isDeviceReady, refreshToken]); }, [refreshToken]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
@ -51,31 +48,39 @@ export default function useDevice() {
return; return;
} }
console.log("ok"); device.on("registered", onDeviceRegistered);
// @ts-ignore device.on("unregistered", onDeviceUnregistered);
window.device = device;
device.on("error", onDeviceError); device.on("error", onDeviceError);
device.on("incoming", onDeviceIncoming); device.on("incoming", onDeviceIncoming);
return () => { return () => {
device.off("registered", onDeviceRegistered);
device.off("unregistered", onDeviceUnregistered);
device.off("error", onDeviceError); device.off("error", onDeviceError);
device.off("incoming", onDeviceIncoming); device.off("incoming", onDeviceIncoming);
}; };
}, [device]); }, [device]);
// @ts-ignore
window.refreshToken = refreshToken;
return { return {
device, device,
isDeviceReady, isDeviceReady,
refreshToken, refreshToken,
}; };
function onDeviceRegistered() {
setIsDeviceReady(true);
}
function onDeviceUnregistered() {
setIsDeviceReady(false);
}
function onDeviceError(error: TwilioError.TwilioError, call?: Call) { function onDeviceError(error: TwilioError.TwilioError, call?: Call) {
// TODO gracefully handle errors: possibly hang up the call, redirect to keypad // we might have to change this if we instantiate the device on every page to receive calls
console.error("device error", JSON.parse(JSON.stringify(error))); setDevice(() => {
alert(error.code); // hack to trigger the error boundary
throw error;
});
} }
function onDeviceIncoming(call: Call) { function onDeviceIncoming(call: Call) {
@ -94,8 +99,6 @@ export default function useDevice() {
} }
} }
const deviceAtom = atom<Device | null>(null);
let e = { let e = {
message: message:
"ConnectionError (53000): Raised whenever a signaling connection error occurs that is not covered by a more specific error code.", "ConnectionError (53000): Raised whenever a signaling connection error occurs that is not covered by a more specific error code.",

View File

@ -1,9 +1,13 @@
import { useState } from "react"; import { useCallback, useState } from "react";
import { useRouter, Routes } from "blitz"; import { useRouter, Routes } from "blitz";
import { Call } from "@twilio/voice-sdk"; import { Call } from "@twilio/voice-sdk";
import useDevice from "./use-device"; import useDevice from "./use-device";
import appLogger from "../../../integrations/logger";
const logger = appLogger.child({ module: "use-make-call" });
type Params = { type Params = {
recipient: string; recipient: string;
onHangUp?: () => void; onHangUp?: () => void;
@ -15,69 +19,85 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
const { device, isDeviceReady } = useDevice(); const { device, isDeviceReady } = useDevice();
const router = useRouter(); const router = useRouter();
const endCall = useCallback(
function endCall() {
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
outgoingConnection?.disconnect();
setState("call_ending");
setTimeout(() => {
setState("call_ended");
setTimeout(() => router.replace(Routes.KeypadPage()), 100);
}, 150);
},
[outgoingConnection, router],
);
const makeCall = useCallback(
async function makeCall() {
if (!device || !isDeviceReady) {
logger.warn("device is not ready yet, can't make the call");
return;
}
if (state !== "initial") {
return;
}
if (device.isBusy) {
logger.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?.();
router.replace(Routes.KeypadPage());
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
},
[device, endCall, onHangUp, outgoingConnection, router],
);
return { return {
makeCall, makeCall,
sendDigits, sendDigits,
hangUp, hangUp,
state, state,
}; };
async function makeCall() {
if (!device || !isDeviceReady) {
console.error("device is not ready yet, can't make the call");
return;
}
if (state !== "initial") {
return;
}
setState("calling");
const params = { To: recipient };
const outgoingConnection = await device.connect({ params });
setOutgoingConnection(outgoingConnection);
// @ts-ignore
window.ddd = 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);
}
function endCall() {
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
outgoingConnection?.disconnect();
setState("call_ending");
setTimeout(() => {
setState("call_ended");
setTimeout(() => router.replace(Routes.KeypadPage()), 100);
}, 150);
}
function sendDigits(digits: string) {
return outgoingConnection?.sendDigits(digits);
}
function hangUp() {
setState("call_ending");
outgoingConnection?.disconnect();
device?.disconnectAll();
onHangUp?.();
router.replace(Routes.KeypadPage());
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
}
} }
type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended"; type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended";

View File

@ -4,8 +4,6 @@ import Twilio from "twilio";
import db from "db"; import db from "db";
import getCurrentPhoneNumber from "../../phone-numbers/queries/get-current-phone-number"; import getCurrentPhoneNumber from "../../phone-numbers/queries/get-current-phone-number";
export const ttl = 3600;
export default resolver.pipe(resolver.authorize(), async (_ = null, context) => { export default resolver.pipe(resolver.authorize(), async (_ = null, context) => {
const phoneNumber = await getCurrentPhoneNumber({}, context); const phoneNumber = await getCurrentPhoneNumber({}, context);
if (!phoneNumber) { if (!phoneNumber) {
@ -30,7 +28,7 @@ export default resolver.pipe(resolver.authorize(), async (_ = null, context) =>
organization.twilioAccountSid, organization.twilioAccountSid,
organization.twilioApiKey, organization.twilioApiKey,
organization.twilioApiSecret, organization.twilioApiSecret,
{ identity: `${context.session.orgId}__${context.session.userId}` }, { identity: `${context.session.orgId}__${context.session.userId}`, ttl: 3600 },
); );
const grant = new Twilio.jwt.AccessToken.VoiceGrant({ const grant = new Twilio.jwt.AccessToken.VoiceGrant({
outgoingApplicationSid: organization.twimlAppSid, outgoingApplicationSid: organization.twimlAppSid,

View File

@ -16,10 +16,10 @@ const OutgoingCall: BlitzPage = () => {
useRequireOnboarding(); useRequireOnboarding();
const [phoneNumber, setPhoneNumber] = useAtom(phoneNumberAtom); const [phoneNumber, setPhoneNumber] = useAtom(phoneNumberAtom);
const router = useRouter(); const router = useRouter();
const { isDeviceReady } = useDevice();
const recipient = decodeURIComponent(router.params.recipient); const recipient = decodeURIComponent(router.params.recipient);
const onHangUp = useCallback(() => setPhoneNumber(""), [setPhoneNumber]); const onHangUp = useCallback(() => setPhoneNumber(""), [setPhoneNumber]);
const call = useMakeCall({ recipient, onHangUp }); const call = useMakeCall({ recipient, onHangUp });
const { isDeviceReady } = useDevice();
const pressDigit = useAtom(pressDigitAtom)[1]; const pressDigit = useAtom(pressDigitAtom)[1];
const onDigitPressProps = useCallback( const onDigitPressProps = useCallback(
(digit: string) => ({ (digit: string) => ({
@ -36,7 +36,7 @@ const OutgoingCall: BlitzPage = () => {
if (isDeviceReady) { if (isDeviceReady) {
call.makeCall(); call.makeCall();
} }
}, [isDeviceReady]); }, [call, isDeviceReady]);
return ( return (
<div className="w-96 h-full flex flex-col justify-around py-5 mx-auto text-center text-black bg-white"> <div className="w-96 h-full flex flex-col justify-around py-5 mx-auto text-center text-black bg-white">