refresh device token before it expires every hour

This commit is contained in:
m5r 2021-09-02 05:54:14 +08:00
parent c41fea755d
commit 98778c7a7b
4 changed files with 48 additions and 15 deletions

View File

@ -1,14 +1,36 @@
import { useEffect } from "react"; import { useCallback, useEffect } from "react";
import { useMutation } from "blitz"; import { useMutation } from "blitz";
import type { TwilioError } from "@twilio/voice-sdk"; import type { TwilioError } from "@twilio/voice-sdk";
import { Call, Device } from "@twilio/voice-sdk"; import { Call, Device } from "@twilio/voice-sdk";
import { atom, useAtom } from "jotai"; import { atom, useAtom } from "jotai";
import getToken from "../mutations/get-token"; import getToken, { ttl } from "../mutations/get-token";
import appLogger from "../../../integrations/logger";
const logger = appLogger.child({ module: "use-device" });
export default function useDevice() { export default function useDevice() {
const [device, setDevice] = useAtom(deviceAtom); const [device, setDevice] = useAtom(deviceAtom);
const [getTokenMutation] = useMutation(getToken); const [getTokenMutation] = useMutation(getToken);
const refreshToken = useCallback(async () => {
if (!device) {
logger.error("Tried refreshing accessToken for an uninitialized device");
return;
}
const token = await getTokenMutation();
device.updateToken(token);
}, [device, getTokenMutation]);
const isDeviceReady = device?.state === Device.State.Registered;
useEffect(() => {
if (!isDeviceReady) {
return;
}
const intervalId = setInterval(refreshToken, ttl - 30);
return () => clearInterval(intervalId);
}, [isDeviceReady, refreshToken]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
@ -22,14 +44,16 @@ export default function useDevice() {
device.register(); device.register();
setDevice(device); setDevice(device);
})(); })();
}, [getTokenMutation]); }, [getTokenMutation, setDevice]);
useEffect(() => { useEffect(() => {
if (!device) { if (!device) {
return; return;
} }
(window as any).device = device; console.log("ok");
// @ts-ignore
window.device = device;
device.on("error", onDeviceError); device.on("error", onDeviceError);
device.on("incoming", onDeviceIncoming); device.on("incoming", onDeviceIncoming);
@ -39,7 +63,14 @@ export default function useDevice() {
}; };
}, [device]); }, [device]);
return device; // @ts-ignore
window.refreshToken = refreshToken;
return {
device,
isDeviceReady,
refreshToken,
};
function onDeviceError(error: TwilioError.TwilioError, call?: Call) { function onDeviceError(error: TwilioError.TwilioError, call?: Call) {
// TODO gracefully handle errors: possibly hang up the call, redirect to keypad // TODO gracefully handle errors: possibly hang up the call, redirect to keypad

View File

@ -12,7 +12,7 @@ type Params = {
export default function useMakeCall({ recipient, onHangUp }: Params) { export default function useMakeCall({ recipient, onHangUp }: Params) {
const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null); const [outgoingConnection, setOutgoingConnection] = useState<Call | null>(null);
const [state, setState] = useState<State>("initial"); const [state, setState] = useState<State>("initial");
const device = useDevice(); const { device, isDeviceReady } = useDevice();
const router = useRouter(); const router = useRouter();
return { return {
@ -23,8 +23,8 @@ export default function useMakeCall({ recipient, onHangUp }: Params) {
}; };
async function makeCall() { async function makeCall() {
if (!device) { if (!device || !isDeviceReady) {
console.error("no device initialized, can't make the call"); console.error("device is not ready yet, can't make the call");
return; return;
} }

View File

@ -4,6 +4,8 @@ import Twilio from "twilio";
import db from "db"; import db from "db";
import getCurrentPhoneNumber from "../../phone-numbers/queries/get-current-phone-number"; import getCurrentPhoneNumber from "../../phone-numbers/queries/get-current-phone-number";
export const ttl = 3600;
export default resolver.pipe(resolver.authorize(), async (_ = null, context) => { export default resolver.pipe(resolver.authorize(), async (_ = null, context) => {
const phoneNumber = await getCurrentPhoneNumber({}, context); const phoneNumber = await getCurrentPhoneNumber({}, context);
if (!phoneNumber) { if (!phoneNumber) {

View File

@ -1,6 +1,6 @@
import type { BlitzPage } from "blitz"; import type { BlitzPage } from "blitz";
import { Routes, useRouter } from "blitz"; import { Routes, useRouter } from "blitz";
import { useEffect, useMemo } from "react"; import { useCallback, useEffect } from "react";
import { atom, useAtom } from "jotai"; import { atom, useAtom } from "jotai";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPhoneAlt as faPhone } from "@fortawesome/pro-solid-svg-icons"; import { faPhoneAlt as faPhone } from "@fortawesome/pro-solid-svg-icons";
@ -15,13 +15,13 @@ const OutgoingCall: BlitzPage = () => {
useRequireOnboarding(); useRequireOnboarding();
const [phoneNumber, setPhoneNumber] = useAtom(phoneNumberAtom); const [phoneNumber, setPhoneNumber] = useAtom(phoneNumberAtom);
const router = useRouter(); const router = useRouter();
const device = useDevice(); const { isDeviceReady } = useDevice();
const recipient = decodeURIComponent(router.params.recipient); const recipient = decodeURIComponent(router.params.recipient);
const onHangUp = useMemo(() => () => setPhoneNumber(""), [setPhoneNumber]); const onHangUp = useCallback(() => setPhoneNumber(""), [setPhoneNumber]);
const call = useMakeCall({ recipient, onHangUp }); const call = useMakeCall({ recipient, onHangUp });
const pressDigit = useAtom(pressDigitAtom)[1]; const pressDigit = useAtom(pressDigitAtom)[1];
const onDigitPressProps = useMemo( const onDigitPressProps = useCallback(
() => (digit: string) => ({ (digit: string) => ({
onPress() { onPress() {
pressDigit(digit); pressDigit(digit);
@ -32,10 +32,10 @@ const OutgoingCall: BlitzPage = () => {
); );
useEffect(() => { useEffect(() => {
if (device !== null) { if (isDeviceReady) {
call.makeCall(); call.makeCall();
} }
}, [device]); }, [isDeviceReady]);
return ( return (
<div className="w-96 h-full flex flex-col justify-around py-5 mx-auto text-center text-black bg-white"> <div className="w-96 h-full flex flex-col justify-around py-5 mx-auto text-center text-black bg-white">