make a phone call ~ not really working
This commit is contained in:
@ -1,45 +1,51 @@
|
||||
import { type FunctionComponent, type PropsWithChildren, useRef } from "react";
|
||||
import { usePress } from "@react-aria/interactions";
|
||||
import { type PressHookProps, usePress } from "@react-aria/interactions";
|
||||
|
||||
import { useLongPressDigit, usePressDigit } from "~/features/keypad/hooks/atoms";
|
||||
|
||||
const Keypad: FunctionComponent<PropsWithChildren<{}>> = ({ children }) => {
|
||||
type Props = {
|
||||
onDigitPressProps?: (digit: string) => PressHookProps;
|
||||
onZeroPressProps?: PressHookProps;
|
||||
};
|
||||
|
||||
const Keypad: FunctionComponent<PropsWithChildren<Props>> = ({ children, onDigitPressProps, onZeroPressProps }) => {
|
||||
return (
|
||||
<section>
|
||||
<Row>
|
||||
<Digit digit="1" />
|
||||
<Digit digit="2">
|
||||
<Digit onPressProps={onDigitPressProps} digit="1" />
|
||||
<Digit onPressProps={onDigitPressProps} digit="2">
|
||||
<DigitLetters>ABC</DigitLetters>
|
||||
</Digit>
|
||||
<Digit digit="3">
|
||||
<Digit onPressProps={onDigitPressProps} digit="3">
|
||||
<DigitLetters>DEF</DigitLetters>
|
||||
</Digit>
|
||||
</Row>
|
||||
<Row>
|
||||
<Digit digit="4">
|
||||
<Digit onPressProps={onDigitPressProps} digit="4">
|
||||
<DigitLetters>GHI</DigitLetters>
|
||||
</Digit>
|
||||
<Digit digit="5">
|
||||
<Digit onPressProps={onDigitPressProps} digit="5">
|
||||
<DigitLetters>JKL</DigitLetters>
|
||||
</Digit>
|
||||
<Digit digit="6">
|
||||
<Digit onPressProps={onDigitPressProps} digit="6">
|
||||
<DigitLetters>MNO</DigitLetters>
|
||||
</Digit>
|
||||
</Row>
|
||||
<Row>
|
||||
<Digit digit="7">
|
||||
<Digit onPressProps={onDigitPressProps} digit="7">
|
||||
<DigitLetters>PQRS</DigitLetters>
|
||||
</Digit>
|
||||
<Digit digit="8">
|
||||
<Digit onPressProps={onDigitPressProps} digit="8">
|
||||
<DigitLetters>TUV</DigitLetters>
|
||||
</Digit>
|
||||
<Digit digit="9">
|
||||
<Digit onPressProps={onDigitPressProps} digit="9">
|
||||
<DigitLetters>WXYZ</DigitLetters>
|
||||
</Digit>
|
||||
</Row>
|
||||
<Row>
|
||||
<Digit digit="*" />
|
||||
<ZeroDigit />
|
||||
<Digit digit="#" />
|
||||
<Digit onPressProps={onDigitPressProps} digit="*" />
|
||||
<ZeroDigit onPressProps={onZeroPressProps} />
|
||||
<Digit onPressProps={onDigitPressProps} digit="#" />
|
||||
</Row>
|
||||
{typeof children !== "undefined" ? <Row>{children}</Row> : null}
|
||||
</section>
|
||||
@ -58,27 +64,32 @@ const DigitLetters: FunctionComponent<PropsWithChildren<{}>> = ({ children }) =>
|
||||
|
||||
type DigitProps = {
|
||||
digit: string;
|
||||
onPressProps: Props["onDigitPressProps"];
|
||||
};
|
||||
|
||||
const Digit: FunctionComponent<PropsWithChildren<DigitProps>> = ({ children, digit }) => {
|
||||
const Digit: FunctionComponent<PropsWithChildren<DigitProps>> = (props) => {
|
||||
const pressDigit = usePressDigit();
|
||||
const onPressProps = {
|
||||
onPress() {
|
||||
// navigator.vibrate(1); // removed in webkit
|
||||
pressDigit(digit);
|
||||
pressDigit(props.digit);
|
||||
},
|
||||
};
|
||||
const { pressProps } = usePress(onPressProps);
|
||||
const { pressProps } = usePress(props.onPressProps?.(props.digit) ?? onPressProps);
|
||||
|
||||
return (
|
||||
<div {...pressProps} className="text-3xl cursor-pointer select-none">
|
||||
{digit}
|
||||
{children}
|
||||
{props.digit}
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const ZeroDigit: FunctionComponent = () => {
|
||||
type ZeroDigitProps = {
|
||||
onPressProps: Props["onZeroPressProps"];
|
||||
};
|
||||
|
||||
const ZeroDigit: FunctionComponent<ZeroDigitProps> = (props) => {
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pressDigit = usePressDigit();
|
||||
const longPressDigit = useLongPressDigit();
|
||||
@ -96,7 +107,7 @@ const ZeroDigit: FunctionComponent = () => {
|
||||
}
|
||||
},
|
||||
};
|
||||
const { pressProps } = usePress(onPressProps);
|
||||
const { pressProps } = usePress(props.onPressProps ?? onPressProps);
|
||||
|
||||
return (
|
||||
<div {...pressProps} className="text-3xl cursor-pointer select-none">
|
||||
|
110
app/features/phone-calls/hooks/use-device.ts
Normal file
110
app/features/phone-calls/hooks/use-device.ts
Normal file
@ -0,0 +1,110 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { type TwilioError, Call, Device } from "@twilio/voice-sdk";
|
||||
import { useFetcher } from "@remix-run/react";
|
||||
|
||||
import type { TwilioTokenLoaderData } from "~/features/phone-calls/loaders/twilio-token";
|
||||
|
||||
export default function useDevice() {
|
||||
const jwt = useDeviceToken();
|
||||
const [device, setDevice] = useState<Device | null>(null);
|
||||
const [isDeviceReady, setIsDeviceReady] = useState(() => device?.state === Device.State.Registered);
|
||||
|
||||
useEffect(() => {
|
||||
jwt.refresh();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (jwt.token && device?.state === Device.State.Registered && device?.token !== jwt.token) {
|
||||
device.updateToken(jwt.token);
|
||||
}
|
||||
}, [jwt.token, device]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!jwt.token || device?.state === Device.State.Registered) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newDevice = new Device(jwt.token, {
|
||||
codecPreferences: [Call.Codec.Opus, Call.Codec.PCMU],
|
||||
sounds: {
|
||||
[Device.SoundName.Disconnect]: undefined, // TODO
|
||||
},
|
||||
});
|
||||
newDevice.register(); // TODO throwing an error
|
||||
setDevice(newDevice);
|
||||
}, [device?.state, jwt.token, setDevice]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!device) {
|
||||
return;
|
||||
}
|
||||
|
||||
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") {
|
||||
return;
|
||||
}
|
||||
|
||||
device.off("registered", onDeviceRegistered);
|
||||
device.off("unregistered", onDeviceUnregistered);
|
||||
device.off("error", onDeviceError);
|
||||
device.off("incoming", onDeviceIncoming);
|
||||
device.off("tokenWillExpire", onTokenWillExpire);
|
||||
};
|
||||
}, [device]);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function useDeviceToken() {
|
||||
const fetcher = useFetcher<TwilioTokenLoaderData>();
|
||||
|
||||
return {
|
||||
token: fetcher.data,
|
||||
refresh: () => fetcher.load("/outgoing-call/twilio-token"),
|
||||
};
|
||||
}
|
100
app/features/phone-calls/hooks/use-make-call.ts
Normal file
100
app/features/phone-calls/hooks/use-make-call.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { useNavigate } from "@remix-run/react";
|
||||
import type { Call } from "@twilio/voice-sdk";
|
||||
|
||||
import useDevice from "./use-device";
|
||||
|
||||
type Params = {
|
||||
recipient: string;
|
||||
onHangUp?: () => void;
|
||||
};
|
||||
|
||||
export default function useMakeCall({ recipient, onHangUp }: Params) {
|
||||
const navigate = useNavigate();
|
||||
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null);
|
||||
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],
|
||||
);
|
||||
|
||||
const makeCall = useCallback(
|
||||
async function makeCall() {
|
||||
if (!device || !isDeviceReady) {
|
||||
console.warn("device is not ready yet, can't make the call");
|
||||
return;
|
||||
}
|
||||
|
||||
if (state !== "initial") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (device.isBusy) {
|
||||
console.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?.();
|
||||
navigate("/keypad");
|
||||
// TODO: outgoingConnection.off is not a function
|
||||
outgoingConnection?.off("cancel", endCall);
|
||||
outgoingConnection?.off("disconnect", endCall);
|
||||
},
|
||||
[device, endCall, onHangUp, outgoingConnection, navigate],
|
||||
);
|
||||
|
||||
return {
|
||||
makeCall,
|
||||
sendDigits,
|
||||
hangUp,
|
||||
state,
|
||||
};
|
||||
}
|
||||
|
||||
type State = "initial" | "ready" | "calling" | "call_in_progress" | "call_ending" | "call_ended";
|
63
app/features/phone-calls/loaders/twilio-token.ts
Normal file
63
app/features/phone-calls/loaders/twilio-token.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { type LoaderFunction } from "@remix-run/node";
|
||||
import Twilio from "twilio";
|
||||
|
||||
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
|
||||
import { encrypt } from "~/utils/encryption";
|
||||
import db from "~/utils/db.server";
|
||||
import { commitSession } from "~/utils/session.server";
|
||||
import getTwilioClient from "~/utils/twilio.server";
|
||||
|
||||
export type TwilioTokenLoaderData = string;
|
||||
|
||||
const loader: LoaderFunction = async ({ request }) => {
|
||||
const { user, organization, twilioAccount } = await requireLoggedIn(request);
|
||||
if (!twilioAccount || !twilioAccount.twimlAppSid) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
|
||||
const twilioClient = getTwilioClient(twilioAccount);
|
||||
let shouldRefreshSession = false;
|
||||
let { apiKeySid, apiKeySecret } = twilioAccount;
|
||||
if (apiKeySid && apiKeySecret) {
|
||||
try {
|
||||
await twilioClient.keys.get(apiKeySid).fetch();
|
||||
} catch (error: any) {
|
||||
if (error.code !== 20404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
apiKeySid = null;
|
||||
apiKeySecret = null;
|
||||
}
|
||||
}
|
||||
if (!apiKeySid || !apiKeySecret) {
|
||||
shouldRefreshSession = true;
|
||||
const apiKey = await twilioClient.newKeys.create({ friendlyName: "Shellphone" });
|
||||
apiKeySid = apiKey.sid;
|
||||
apiKeySecret = apiKey.secret;
|
||||
await db.twilioAccount.update({
|
||||
where: { subAccountSid: twilioAccount.subAccountSid },
|
||||
data: { apiKeySid: apiKey.sid, apiKeySecret: encrypt(apiKey.secret) },
|
||||
});
|
||||
}
|
||||
|
||||
const accessToken = new Twilio.jwt.AccessToken(twilioAccount.subAccountSid, apiKeySid, apiKeySecret, {
|
||||
identity: `${organization.id}__${user.id}`,
|
||||
ttl: 3600,
|
||||
});
|
||||
const grant = new Twilio.jwt.AccessToken.VoiceGrant({
|
||||
outgoingApplicationSid: twilioAccount.twimlAppSid,
|
||||
incomingAllow: true,
|
||||
});
|
||||
accessToken.addGrant(grant);
|
||||
|
||||
const headers = new Headers({ "Content-Type": "text/plain" });
|
||||
if (shouldRefreshSession) {
|
||||
const { session } = await refreshSessionData(request);
|
||||
headers.set("Set-Cookie", await commitSession(session));
|
||||
}
|
||||
|
||||
return new Response(accessToken.toJwt(), { headers });
|
||||
};
|
||||
|
||||
export default loader;
|
Reference in New Issue
Block a user