shellphone.app/app/phone-calls/hooks/use-make-call.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-08-31 22:42:15 +00:00
import { useState } from "react";
import { useRouter, Routes } from "blitz";
import { Call } from "@twilio/voice-sdk";
2021-08-13 04:43:57 +00:00
2021-08-31 22:42:15 +00:00
import useDevice from "./use-device";
2021-08-13 04:43:57 +00:00
2021-08-13 15:52:38 +00:00
type Params = {
recipient: string;
onHangUp?: () => void;
};
export default function useMakeCall({ recipient, onHangUp }: Params) {
2021-08-13 04:43:57 +00:00
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null);
const [state, setState] = useState<State>("initial");
const { device, isDeviceReady } = useDevice();
2021-08-31 22:42:15 +00:00
const router = useRouter();
2021-08-13 04:43:57 +00:00
return {
makeCall,
sendDigits,
hangUp,
state,
};
async function makeCall() {
if (!device || !isDeviceReady) {
console.error("device is not ready yet, can't make the call");
2021-08-13 04:43:57 +00:00
return;
}
2021-08-31 22:42:15 +00:00
if (state !== "initial") {
2021-08-13 04:43:57 +00:00
return;
}
setState("calling");
const params = { To: recipient };
const outgoingConnection = await device.connect({ params });
setOutgoingConnection(outgoingConnection);
// @ts-ignore
window.ddd = outgoingConnection;
2021-09-03 16:19:32 +00:00
outgoingConnection.on("error", (error) => {
outgoingConnection.off("cancel", endCall);
outgoingConnection.off("disconnect", endCall);
setState(() => {
// hack to trigger the error boundary
throw error;
});
});
2021-08-31 23:12:47 +00:00
outgoingConnection.once("accept", (call: Call) => setState("call_in_progress"));
2021-08-31 22:42:15 +00:00
outgoingConnection.on("cancel", endCall);
outgoingConnection.on("disconnect", endCall);
2021-08-13 04:43:57 +00:00
}
2021-08-31 22:42:15 +00:00
function endCall() {
2021-09-03 16:19:32 +00:00
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
outgoingConnection?.disconnect();
2021-08-31 22:42:15 +00:00
setState("call_ending");
setTimeout(() => {
setState("call_ended");
setTimeout(() => router.replace(Routes.KeypadPage()), 100);
}, 150);
}
2021-08-13 04:43:57 +00:00
function sendDigits(digits: string) {
return outgoingConnection?.sendDigits(digits);
}
function hangUp() {
setState("call_ending");
2021-08-31 22:42:15 +00:00
outgoingConnection?.disconnect();
2021-08-13 15:52:38 +00:00
device?.disconnectAll();
onHangUp?.();
2021-08-31 22:42:15 +00:00
router.replace(Routes.KeypadPage());
outgoingConnection?.off("cancel", endCall);
outgoingConnection?.off("disconnect", endCall);
2021-08-13 04:43:57 +00:00
}
}
type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended";