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

78 lines
1.8 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");
2021-08-31 22:42:15 +00:00
const device = useDevice();
const router = useRouter();
2021-08-13 04:43:57 +00:00
return {
makeCall,
sendDigits,
hangUp,
state,
};
async function makeCall() {
if (!device) {
console.error("no device initialized, can't make the call");
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;
// TODO: setState("call_in_progress");
// TODO: remove event listeners
2021-08-31 22:42:15 +00:00
outgoingConnection.on("cancel", endCall);
outgoingConnection.on("disconnect", endCall);
2021-08-13 04:43:57 +00:00
outgoingConnection.on("error", (error) => {
console.error("call error", error);
alert(error);
});
}
2021-08-31 22:42:15 +00:00
function endCall() {
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";