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

@ -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 { type TwilioError, Call, Device } from "@twilio/voice-sdk";
import { useAtom, atom } from "jotai";
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() {
const jwt = useDeviceToken();
const [device, setDevice] = useAtom(deviceAtom);
const [isDeviceReady, setIsDeviceReady] = useState(device?.state === Device.State.Registered);
const [call, setCall] = useCall();
const [isDeviceReady, setIsDeviceReady] = useAtom(isDeviceReadyAtom);
useEffect(() => {
// init token
jwt.refresh();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
@ -31,8 +35,9 @@ export default function useDevice() {
},
});
newDevice.register();
(window as any).ddd = newDevice;
setDevice(newDevice);
}, [device, jwt.token]);
}, [device, jwt.token, setDevice]);
useEffect(() => {
// refresh token
@ -41,79 +46,111 @@ export default function useDevice() {
}
}, [device, jwt.token]);
useEffect(() => {
if (!device) {
return;
}
const onTokenWillExpire = useCallback(
function onTokenWillExpire() {
jwt.refresh();
},
[jwt.refresh],
);
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") {
const onDeviceRegistered = useCallback(
function onDeviceRegistered() {
setIsDeviceReady(true);
},
[setIsDeviceReady],
);
const onDeviceUnregistered = useCallback(
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;
}
device.off("registered", onDeviceRegistered);
device.off("unregistered", onDeviceUnregistered);
device.off("error", onDeviceError);
device.off("incoming", onDeviceIncoming);
device.off("tokenWillExpire", onTokenWillExpire);
};
}, [device]);
setCall(incomingCall);
console.log("incomingCall.parameters", incomingCall.parameters);
// TODO prevent making a new call when there is a pending incoming call
const channel = new BroadcastChannel("notifications");
const recipient = incomingCall.parameters.From;
const message: NotificationPayload = {
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 {
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();
}
}
}
const deviceAtom = atom<Device | null>(null);
const isDeviceReadyAtom = atom(false);
function useDeviceToken() {
const fetcher = useFetcher<TwilioTokenLoaderData>();
const refresh = useCallback(() => fetcher.load("/outgoing-call/twilio-token"), []);
return {
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 useDevice from "./use-device";
import useCall from "./use-call";
type Params = {
recipient: string;
@ -11,28 +12,23 @@ type Params = {
export default function useMakeCall({ recipient, onHangUp }: Params) {
const navigate = useNavigate();
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null);
const [call, setCall] = useCall();
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],
[navigate],
);
const makeCall = useCallback(
async function makeCall() {
console.log({ device, isDeviceReady });
if (!device || !isDeviceReady) {
console.warn("device is not ready yet, can't make the call");
return;
@ -42,7 +38,7 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
return;
}
if (device.isBusy) {
if (device.isBusy || Boolean(call)) {
console.error("device is busy, this shouldn't happen");
return;
}
@ -51,43 +47,30 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
const params = { To: recipient };
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.on("cancel", endCall);
outgoingConnection.on("disconnect", endCall);
outgoingConnection.once("cancel", endCall);
outgoingConnection.once("disconnect", endCall);
},
[device, isDeviceReady, recipient, state],
[call, device, endCall, isDeviceReady, recipient, setCall, state],
);
const sendDigits = useCallback(
function sendDigits(digits: string) {
return outgoingConnection?.sendDigits(digits);
return call?.sendDigits(digits);
},
[outgoingConnection],
[call],
);
const hangUp = useCallback(
function hangUp() {
setState("call_ending");
outgoingConnection?.disconnect();
device?.disconnectAll();
device?.destroy();
call?.disconnect();
onHangUp?.();
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 {

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";