微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

twilio 设备连接和重新连接

如何解决twilio 设备连接和重新连接

我正在尝试为 twilio 调用连接创建上下文 api。如果我以正确的方式进行操作,我想从 twilio 专家那里获得帮助。在这种情况下,我想要做的是连接 twilio 设备,如果令牌过期,则重新连接。但是这样,拨出电话还没有工作,我可以看到设备已准备好打印在我的控制台上。当我尝试调用时,deviceInstance 状态显示为空。

我就是这样

import { Device,Connection } from 'twilio-client';

import twilioReducers from './twilioReducers';

interface ITwilioContext {
  // device?: Device;
  setDeviceOnline?: () => void;
  state: InitialStateType;
  dispatch: React.dispatch<any>;
  handleDeviceOutgoing: (params: OutgoingProps) => void;
}

export const TwilioContext = createContext<ITwilioContext>({});

const TwilioProvider = ({ children }: { children: React.ReactNode }) => {
  const [deviceInstance,setDeviceInstance] = useState<Device | null>(null);
  const [activeWorkspaceId] = useLocalStorage('activeWorkspaceId',null);
  const { t } = useTranslation();

  const [getVoicetoken,{ data }] = useLazyQuery(VOICE_TOKEN,{
    fetchPolicy: 'network-only',errorPolicy: 'ignore',onError: err => console.error(err),});

  // Commented inorder to prevent reintialization
  // const device = new Device();

  const initialState = { direction: '',showPhoneWidget: false };
  const [state,dispatch] = useReducer(twilioReducers,initialState);


  /* event handlers for twilio device */
  const handleDeviceReady = (device: Device) => {
    console.log('Device ready');
    setDeviceInstance(device);
  };

  const handleDeviceOffline = async (device: Device) => {
    console.log('Device offline',device);
    if (device.token) {
      const twilioTokenDecoded = jwtDecode<JwtPayload>(device.token);
      if ((twilioTokenDecoded as any).exp <= Date.Now() / 1000) {
        await getVoicetoken({});
        console.log('twilio new token data',data);
      }
    }
  };

  const handleDeviceError = (error: Connection.Error) => {
    console.log('Device error',error);
    if (TWILIO_ERRORS[error.code] !== undefined) {
      ToastMessage({
        content: t(TWILIO_ERRORS[error.code].errorKey,TWILIO_ERRORS[error.code].message),type: 'danger',});
    }
  };
  /* ----------------------------- */

  /* handle incoming calls */
  const handleDeviceIncoming = (connection: Connection) => {
    console.log('incoming',connection);
    dispatch({
      type: ACTIONS.INCOMING_CALL,data: connection,});
    connection.on(deviceEvent.CANCEL,() => {
      console.log('incoming-cancel');
      dispatch({
        type: ACTIONS.INCOMING_CALL_CANCEL,});
    });

    connection.on(deviceEvent.disCONNECT,() => {
      console.log('incoming-disconnect');
      dispatch({
        type: ACTIONS.INCOMING_CALL_disCONNECT,});
    });

    connection.on(deviceEvent.ACCEPT,() => {
      console.log('incoming-call-accept');
      dispatch({
        type: ACTIONS.ANSWER_INCOMING_CALL,});
    });

    connection.on(deviceEvent.REJECT,() => {
      console.log('incoming-call-reject');
      dispatch({
        type: ACTIONS.REJECT_INCOMING_CALL,updateConversationStatus: true,});
    });
    connection.on(deviceEvent.ERROR,(err: Connection.Error) => {
      console.log('Connection error occured',err);
      dispatch({
        type: ACTIONS.INCOMING_CALL_ERROR,status: 'error',});
    });
  };
  /* ----------------------------- */

  /* handle outgoing calls */
  const handleDeviceOutgoing = (params: OutgoingProps) => {
    if (deviceInstance) {
      if (deviceInstance.isInitialized || deviceInstance.status() !== 'ready') {
        ToastMessage({ content: t('error.deviceSetup','Device is offline.'),type: 'danger' });
        return;
      }
      const connection = deviceInstance.connect(params); // copied from premvp
      dispatch({
        type: ACTIONS.OUTGOING_CALL_INITIATED,status: 'connecting',channelId: params?.channel_sid,});
      connection.on(deviceEvent.RINGING,(val: boolean) => {
        if (val) {
          dispatch({
            type: ACTIONS.OUTGOING_CALL_RINGING,});
        }
      });

      connection.on(deviceEvent.CANCEL,() => {
        console.log('Connection cancelled');
        dispatch({
          type: ACTIONS.OUTGOING_CALL_disCONNECT,});
      });

      connection.on(deviceEvent.disCONNECT,(conn: Connection) => {
        // handle user hungup
        console.log('Connection disconnected',conn);
        dispatch({
          type: ACTIONS.OUTGOING_CALL_disCONNECT,});
      });

      connection.on(deviceEvent.ACCEPT,(conn: Connection) => {
        console.log('Connected to the user',conn); // handle user answercall
        dispatch({
          type: ACTIONS.OUTGOING_CALL_ANSWERED,});
      });

      connection.on(deviceEvent.REJECT,(conn: Connection) => {
        console.log('Rejected',conn); // handle user answercall
        dispatch({
          type: ACTIONS.REJECT_OUTGOING_CALL,});
      });

      connection.on(deviceEvent.ERROR,(err: Connection.Error) => {
        console.log('Connection error occured',err);
      });
    } else {
      console.log('No Device Instance exist');
    }
  };
  /* ----------------------------- */

  useEffect(() => {
    const device = new Device();
    console.log('device',device,data);
    if (data?.getVoicetoken?.data?.voicetoken) {
      device.setup(data?.getVoicetoken?.data?.voicetoken,deviceConfig);
      device.on(deviceEvent.READY,handleDeviceReady);
      device.on(deviceEvent.OFFLINE,handleDeviceOffline);
      device.on(deviceEvent.ERROR,handleDeviceError);
      device.on(deviceEvent.INCOMING,handleDeviceIncoming);
    }
    return () => {
      device.destroy();
      setDeviceInstance(null);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[data?.getVoicetoken?.data?.voicetoken]);

  useEffect(() => {
    if (activeWorkspaceId !== '') {
      getVoicetoken({});
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[activeWorkspaceId]);

  const value = useMemo(() => {
    return {
      state,dispatch,deviceInstance,handleDeviceOutgoing,};
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[state]);

  return <TwilioContext.Provider value={value}>{children}</TwilioContext.Provider>;
};

export default TwilioProvider;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。