Отключение сеанса в открытом токе с использованием React Native - PullRequest
0 голосов
/ 01 августа 2020

Пока я снова подключаю событие сеанса, которое происходит несколько раз, пока я не очищу его из недавнего меню на мобильном телефоне, я думаю, что эта проблема связана с тем, что я не могу должным образом отключить сеанс, я просто возвращаю экран туда, где хочу to go.

Я использую функциональные компоненты, и я также использовал этот метод ниже:

otSessionRef.current.createSession({
    apiKey: OPENTOKAPI_KEY,
    sessionId: currentSelectedSchedule.sessionId,
    token: currentSelectedSchedule.token,
  });

Вышеупомянутый метод, дающий TypeError: undefined не является объектом (оценка 'sessionOptions.proxyUrl ')

Я думаю, что если я отключу сеанс должным образом, я думаю, что эта проблема решит

Ниже приведен полный код

import React, {useState, useEffect, useRef} from 'react';
import {View, Image, TouchableWithoutFeedback, ActivityIndicator, Dimensions, AppRegistry} from 'react-native';
import {OTSession, OTPublisher, OTSubscriber, OT} from 'opentok-react-native';
import {useSelector} from 'react-redux';
import {IappointmentsPageState} from '../../interfaces/appointments-page-interface';
import videoScreenStyles from './video-call-css';
import {OPENTOKAPI_KEY} from '../../utils/appConstants';
import {Connection, Session, Stream, TimerData, TimerInterface} from './video-call-model';
import {primaryColor, secondaryColor} from '../../utils/colors';
import {Text} from 'native-base';
import {LinearGradient} from "expo-linear-gradient";
import {appointmentCancel} from "../../utils/strings";
import {Button} from "react-native-elements";
import {Stopwatch, Timer} from 'react-native-stopwatch-timer';


function VideoScreen({navigation}: { navigation: any }) {

    const otSessionRef = useRef(OTSession);

    const currentSelectedSchedule = useSelector((state: IappointmentsPageState) => state.appointmentsPageState.selectedSchedule);

    const [videoCallConnected, setVideoCallConnected] = useState(false);

    const [mic, setMic] = useState(true);

    const [video, setVideo] = useState(true);

    const [rotato, setRotato] = useState('front');

    const [loading, setLoading] = useState(true);

    const endCallHandler = () => {
        // otSessionRef.current.disconnectSession();
        navigation.navigate('AppointmentsTab');
    }
    const micHandler = () => {
        setMic(!mic)
    }
    const videoHandler = () => {
        setVideo(!video);
    }
    const rotatoHandler = () => {
        if (rotato == 'front') {
            setRotato('back');
        } else {
            setRotato('front');
        }
    }

    // useEffect(() => {
    //     // otSessionRef.current.createSession({
    //     //     apiKey: OPENTOKAPI_KEY,
    //     //     sessionId: currentSelectedSchedule.sessionId,
    //     //     token: currentSelectedSchedule.token,
    //     // });
    //     return () => {
    //         otSessionRef.current.disconnect();
    //     };
    // });


    useEffect(() => {
        rotato
    }, [rotato]);

    useEffect(() => {
        // otSessionRef.current.createSession({
        //     apiKey: OPENTOKAPI_KEY,
        //     sessionId: currentSelectedSchedule.sessionId,
        //     token: currentSelectedSchedule.token,
        // });
        return () => {
            otSessionRef.current.disconnectSession();
        }
    }, []);

    const publisherProperties = {
        publishAudio: mic,
        cameraPosition: rotato,
        publishVideo: video,
    };

    const sessionEventHandlers = {
        connectionCreated: (event: Connection) => {
            publisherViewHandler();
        },
        streamDestroyed: event => {
            // console.log('Stream destroyed!', event);
        },
        connectionDestroyed: (event: Connection) => {
            // if (event.connectionId != null) {
            //     if (currentSelectedSchedule.fee > 0) {
            //         navigation.navigate('Payment');
            //     } else {
            //         navigation.navigate('AppointmentsTab');
            //     }
            // }
            publisherViewHandler();
        },
        sessionConnected: (event: Session) => {
            // console.log('Stream destroyed!', event);
        },
        sessionDisconnected: (event: Session) => {
            // console.log('sessionDisconnected', event);
            publisherViewHandler();
        },
        sessionReconnected: (event: Session) => {
            publisherViewHandler();
        },
        streamCreated: (event: Stream) => {
            // console.log('Stream destroyed!', event);
        },
        streamPropertyChanged: (event: Stream) => {
            // console.log('Stream destroyed!', event);
        },
        signal: (event) => {
            console.log('Single', event.type);
            // if (therapistTimer == '' || therapistTimer != event.type) {
            //     console.log('Single',event.type);
            //     setTherapistTimer(event.type);
            // }else {
            //     console.log('Event Type',event.type);
            // }
            // setTherapistTimer(event.type);
            // setTherapistTimer('baby');
            // const timerDataJson: TimerData = JSON.parse(event.data.toString().replace('\\', ''));
            // if (timerDataJson.type == 'timer') {
            //     console.log(timerDataJson);
            //     setTherapistTimer(!therapistTimer);
            //     setTherapistDataTimer(timerDataJson);
            // } else if (timerDataJson.type == 'stopwatch') {
            //     console.log(timerDataJson);
            // } else {
            //     console.log(timerDataJson);
            //     setTherapistTimer(!therapistTimer);
            // }
        },
    };

    const publisherViewHandler = () => {
        setTimeout(() => {
            setVideoCallConnected(!videoCallConnected);
            setLoading(!loading);
        }, 3000);
    }

    const cancelHandler = () => {
        navigation.navigate('AppointmentsTab');
    }

    const options = {
        container: {
            backgroundColor: '#000',
            padding: 5,
            borderRadius: 5,
            width: 220,
        },
        text: {
            fontSize: 30,
            color: '#FFF',
            marginLeft: 7,
        }
    };

    return (
        <View style={videoScreenStyles.oTSubscriberStyles}>

            {/*<Timer totalDuration={360} secs start={therapistTimer}*/}
            {/*       reset={false}*/}
            {/*       options={options}*/}
            {/*/>*/}
            {/*<Stopwatch laps msecs start={this.state.stopwatchStart}*/}
            {/*           reset={this.state.stopwatchReset}*/}
            {/*           options={options}*/}
            {/*           getTime={this.getFormattedTime}/>*/}


            <OTSession apiKey={OPENTOKAPI_KEY} sessionId={currentSelectedSchedule.sessionId}
                       token={currentSelectedSchedule.token} eventHandlers={sessionEventHandlers} ref={otSessionRef}>
                {videoCallConnected ? <OTPublisher properties={publisherProperties}
                                                   style={videoScreenStyles.oTPublisherStyles}
                /> : null}
                {loading ? <View style={videoScreenStyles.centered}>
                    <ActivityIndicator size="large" color={primaryColor}/>
                    <Text style={videoScreenStyles.texTherapist}>Please wait still therapist join the call</Text>
                    <Button
                        ViewComponent={LinearGradient}
                        onPress={() => cancelHandler()}
                        linearGradientProps={{
                            colors: [primaryColor, secondaryColor],
                            start: {x: 0.5, y: 0},
                            end: {x: 0.5, y: 1},
                        }}
                        buttonStyle={{height: 30, width: 70, borderRadius: 15}}
                        title={appointmentCancel}
                        titleStyle={{fontSize: 12, marginTop: 0, paddingTop: 0, fontWeight: 'bold'}}
                    />
                </View> : null}
                <OTSubscriber
                    style={videoScreenStyles.oTSubscriberStyles}
                />
            </OTSession>
            {/*{loading ? null : <View style={videoScreenStyles.timerBar}>*/}
            {/*    <Text> {therapistTimer}</Text>*/}
            {/*</View>}*/}
            {loading ? null : <View style={videoScreenStyles.bottomBar}>
                <TouchableWithoutFeedback onPress={endCallHandler}>
                    <Image source={require('./../../assets/video/endcall_icn.png')}/>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={micHandler}>
                    <Image
                        source={!mic ? require('./../../assets/video/micicn_mute.png') : require('./../../assets/video/mic_icn.png')}/>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={videoHandler}>
                    <Image
                        source={!video ? require('./../../assets/video/videoicn_off.png') : require('./../../assets/video/video_icn.png')}/>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={rotatoHandler}>
                    <Image style={videoScreenStyles.videoCallImage}
                           source={rotato == 'front' ? require('./../../assets/video/front_rotate.png') : require('./../../assets/video/back_rotate.png')}/>
                </TouchableWithoutFeedback>
            </View>}
        </View>
    );
}

export default VideoScreen;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...