shellphone.app/app/features/phone-calls/hooks/use-device.ts

157 lines
4.1 KiB
TypeScript
Raw Normal View History

2022-06-14 23:28:32 +00:00
import { useCallback, useEffect } from "react";
2022-05-24 21:13:08 +00:00
import { useFetcher } from "@remix-run/react";
2022-06-11 17:29:58 +00:00
import { type TwilioError, Call, Device } from "@twilio/voice-sdk";
import { useAtom, atom } from "jotai";
2022-05-24 21:13:08 +00:00
import type { TwilioTokenLoaderData } from "~/features/phone-calls/loaders/twilio-token";
2022-06-14 23:28:32 +00:00
import type { NotificationPayload } from "~/utils/web-push.server";
import useCall from "./use-call";
2022-05-24 21:13:08 +00:00
export default function useDevice() {
const jwt = useDeviceToken();
2022-06-11 17:29:58 +00:00
const [device, setDevice] = useAtom(deviceAtom);
2022-06-14 23:28:32 +00:00
const [call, setCall] = useCall();
const [isDeviceReady, setIsDeviceReady] = useAtom(isDeviceReadyAtom);
2022-05-24 21:13:08 +00:00
useEffect(() => {
2022-06-11 17:29:58 +00:00
// init token
2022-05-24 21:13:08 +00:00
jwt.refresh();
2022-06-14 23:28:32 +00:00
// eslint-disable-next-line react-hooks/exhaustive-deps
2022-05-24 21:13:08 +00:00
}, []);
useEffect(() => {
2022-06-11 17:29:58 +00:00
// init device
if (!jwt.token) {
return;
2022-05-24 21:13:08 +00:00
}
2022-06-11 17:29:58 +00:00
if (device && device.state !== Device.State.Unregistered) {
2022-05-24 21:13:08 +00:00
return;
}
const newDevice = new Device(jwt.token, {
codecPreferences: [Call.Codec.Opus, Call.Codec.PCMU],
sounds: {
[Device.SoundName.Disconnect]: undefined, // TODO
},
});
2022-06-11 17:29:58 +00:00
newDevice.register();
2022-06-14 23:28:32 +00:00
(window as any).ddd = newDevice;
2022-05-24 21:13:08 +00:00
setDevice(newDevice);
2022-06-14 23:28:32 +00:00
}, [device, jwt.token, setDevice]);
2022-06-11 17:29:58 +00:00
useEffect(() => {
// refresh token
if (jwt.token && device?.state === Device.State.Registered && device?.token !== jwt.token) {
device.updateToken(jwt.token);
}
}, [device, jwt.token]);
2022-05-24 21:13:08 +00:00
2022-06-14 23:28:32 +00:00
const onTokenWillExpire = useCallback(
function onTokenWillExpire() {
jwt.refresh();
},
[jwt.refresh],
);
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;
}
2022-05-24 21:13:08 +00:00
2022-06-14 23:28:32 +00:00
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;
}
2022-05-24 21:13:08 +00:00
2022-06-14 23:28:32 +00:00
// 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())) {
2022-05-24 21:13:08 +00:00
return;
}
2022-06-14 23:28:32 +00:00
device.on(eventName, handler);
return () => {
device.removeListener(eventName, handler);
};
}, [device, eventName, handler]);
}
2022-05-24 21:13:08 +00:00
return {
device,
isDeviceReady,
};
}
2022-06-11 17:29:58 +00:00
const deviceAtom = atom<Device | null>(null);
2022-06-14 23:28:32 +00:00
const isDeviceReadyAtom = atom(false);
2022-06-11 17:29:58 +00:00
2022-05-24 21:13:08 +00:00
function useDeviceToken() {
const fetcher = useFetcher<TwilioTokenLoaderData>();
2022-06-14 23:28:32 +00:00
const refresh = useCallback(() => fetcher.load("/outgoing-call/twilio-token"), []);
2022-05-24 21:13:08 +00:00
return {
token: fetcher.data,
2022-06-14 23:28:32 +00:00
refresh,
2022-05-24 21:13:08 +00:00
};
}