Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component, Fragment } from 'react';
- import { connect } from 'react-redux';
- import { StyleSheet } from 'react-native';
- import {
- Platform,
- ScrollView,
- Text,
- TextInput,
- TouchableOpacity,
- View,
- Dimensions,
- Button
- } from 'react-native';
- import RtcEngine, { ClientRole, ChannelProfile, RtcLocalView,
- RtcRemoteView } from 'react-native-agora';
- import RtmEngine from 'agora-react-native-rtm';
- import IdleTimerManager from 'react-native-idle-timer';
- import requestCameraAndAudioPermission from '../../util/VideoPermisions';
- import {APPLICATION_CLIENT_ROUTES, APPLICATION_ROUTES} from "../../constants";
- let dimensions = {
- //get dimensions of the device to use in view styles
- width: Dimensions.get('window').width,
- height: Dimensions.get('window').height,
- };
- class VideoScreen extends Component {
- _rtcEngine;
- _rtmEngine;
- constructor(props) {
- super(props);
- IdleTimerManager.setIdleTimerDisabled(true);
- this.state = {
- peerIds: [], //Array for storing connected peers
- appId: '26180e17618e4741ad482f9b938b7c87',
- token: null,
- isHost: true,
- channelName: 'Yyy',
- joinSucceed: false,
- rtcUid: parseInt((new Date().getTime() + '').slice(4, 13), 10),
- myUsername: '',
- usernames: {},
- audMute: false
- };
- if (Platform.OS === 'android') {
- // Request required permissions from Android
- requestCameraAndAudioPermission().then(() => {
- console.log('requested!');
- });
- }
- }
- componentDidMount() {
- this.unsubscribeFocus = this.props.navigation.addListener(
- 'focus',
- async () => {
- this.setState({myUsername: this.props.user.firstName + this.props.user.lastName})
- await this.initRTC();
- await this.initRTM();
- await this.startCall();
- }
- );
- }
- async sendTestMessage() {
- await this._rtmEngine
- ?.sendMessageByChannelId(this.state.channelName, 'popopopopopopopopopopopopop')
- .catch((e) => console.log(e))
- .done(() => console.log('MESSAGE SENT'));
- }
- componentWillUnmount() {
- this._rtmEngine?.destroyClient();
- this._rtcEngine?.destroy();
- }
- /**
- * @name initRTC
- * @description Function to initialize the Rtc Engine, attach event listeners and actions
- */
- initRTC = async () => {
- const { appId, isHost } = this.state;
- this._rtcEngine = await RtcEngine.create(appId);
- await this._rtcEngine.enableVideo();
- await this._rtcEngine.setChannelProfile(ChannelProfile.LiveBroadcasting);
- await this._rtcEngine.setClientRole(
- isHost ? ClientRole.Broadcaster : ClientRole.Audience
- );
- this._rtcEngine.addListener('Error', (err) => {
- console.log('Error', err);
- });
- this._rtcEngine.addListener('UserJoined', (uid, elapsed) => {
- //console.log('UserJoined', uid, elapsed);
- // Get current peer IDs
- const { peerIds } = this.state;
- // If new user
- if (peerIds.indexOf(uid) === -1) {
- this.setState({
- // Add peer ID to state array
- peerIds: [...peerIds, uid],
- });
- }
- });
- this._rtcEngine.addListener('UserOffline', (uid, reason) => {
- console.log('UserOffline', uid, reason);
- const { peerIds } = this.state;
- this.setState({
- // Remove peer ID from state array
- peerIds: peerIds.filter((id) => id !== uid),
- });
- });
- // If Local user joins RTC channel
- this._rtcEngine.addListener(
- 'JoinChannelSuccess',
- (channel, uid, elapsed) => {
- //console.log('JoinChannelSuccess', channel, uid, elapsed);
- this.setState({
- joinSucceed: true,
- rtcUid: uid,
- peerIds: [...this.state.peerIds, uid]
- });
- console.log(this.state)
- }
- );
- return true;
- };
- /**
- * @name initRTM
- * @description Function to initialize the Rtm Engine, attach event listeners and use them to sync usernames
- */
- initRTM = async () => {
- let { appId, usernames, rtcUid } = this.state;
- this._rtmEngine = new RtmEngine();
- this._rtmEngine.on('error', (evt) => {
- console.log('ERRORRRRRRRRRRRRRRR', evt);
- });
- this._rtmEngine.on('channelMessageReceived', (evt) => {
- console.log('XXXXXXXXXXXX')
- let { text } = evt;
- let data = text.split(':');
- console.log('cmr', evt);
- if (data[1] === '!leave') {
- let temp = JSON.parse(JSON.stringify(usernames));
- Object.keys(temp).map((k) => {
- if (k === data[0]) delete temp[k];
- });
- this.setState({
- usernames: temp,
- });
- } else {
- this.setState({
- usernames: { ...usernames, [data[0]]: data[1] },
- });
- }
- });
- this._rtmEngine.on('messageReceived', (evt) => {
- console.log('MMMMMMMMM');
- let { text } = evt;
- let data = text.split(':');
- console.log('pm', evt);
- this.setState({
- usernames: { ...usernames, [data[0]]: data[1] },
- });
- });
- this._rtmEngine.on('channelMemberJoined', (evt) => {
- console.log('aaaaaaaaaaaa')
- console.log('!spm', this.state.myUsername);
- this._rtmEngine?.sendMessageToPeer({
- peerId: evt.uid,
- text: rtcUid + ':' + this.state.myUsername,
- offline: false,
- });
- });
- await this._rtmEngine.createClient(appId).catch((e) => console.log(e));
- return true;
- };
- /**
- * @name startCall
- * @description Function to start the call
- */
- startCall = async () => {
- let { myUsername, token, channelName, rtcUid } = this.state;
- //if (myUsername) {
- // Join RTC Channel using null token and channel name
- await this._rtcEngine?.joinChannel(token, channelName, null, rtcUid);
- // Login & Join RTM Channel
- await this._rtmEngine
- ?.login({ uid: myUsername })
- .catch((e) => console.log(e));
- await this._rtmEngine
- ?.joinChannel(channelName)
- .catch((e) => console.log(e));
- await this._rtmEngine
- ?.sendMessageByChannelId(channelName, rtcUid + ':' + myUsername)
- .catch((e) => console.log(e));
- //}
- };
- /**
- * @name toggleRole
- * @description Function to toggle the roll between broadcaster and audience
- */
- toggleRole = async () => {
- this._rtcEngine?.setClientRole(
- !this.state.isHost ? ClientRole.Broadcaster : ClientRole.Audience
- );
- this.setState((ps) => {
- return { isHost: !ps.isHost };
- });
- };
- /**
- * @name toggleAudio
- * @description Function to toggle local user's audio
- */
- toggleAudio() {
- let mute = this.state.audMute;
- console.log('Audio toggle', mute);
- this._rtcEngine?.muteLocalAudioStream(!mute);
- this.setState({
- audMute: !mute,
- });
- }
- /**
- * @name toggleVideo
- * @description Function to toggle local user's video
- */
- toggleVideo() {
- let mute = this.state.vidMute;
- console.log('Video toggle', mute);
- this.setState({
- vidMute: !mute,
- }, () => {
- this._rtcEngine?.muteLocalVideoStream(!mute);
- });
- }
- /**
- * @name endCall
- * @description Function to end the call
- */
- endCall = async () => {
- let { channelName, rtcUid } = this.state;
- await this._rtcEngine?.leaveChannel();
- await this._rtmEngine
- ?.sendMessageByChannelId(channelName, rtcUid + ':!leave')
- .catch((e) => console.log(e));
- this.setState({ peerIds: [], joinSucceed: false, usernames: {} });
- await this._rtmEngine?.logout().catch((e) => console.log(e));
- };
- async refreshCamera() {
- await this.endCall();
- this.startCall();
- }
- render() {
- const { joinSucceed, isHost, channelName, myUsername } = this.state;
- return (
- <View style={styles.full}>
- <Button title="Send Test Message" onPress={() => this.sendTestMessage()} />
- {this.state.peerIds.length > 1 ? (
- <View style={styles.full}>
- <View style={{height: (dimensions.height * 3) / 4 - 50}}>
- <RtcLocalView.SurfaceView
- style={styles.full}
- channelId={channelName}
- zOrderMediaOverlay={true}
- uid={this.state.peerIds[0]}
- />
- </View>
- <View style={{height: dimensions.height / 4}}>
- <ScrollView
- horizontal={true}
- decelerationRate={0}
- snapToInterval={dimensions.width / 2}
- snapToAlignment={'center'}
- style={{
- width: dimensions.width,
- height: dimensions.height / 4,
- }}>
- {this.state.peerIds.slice(1).map(data => (
- <TouchableOpacity
- style={{
- width: dimensions.width / 2,
- height: dimensions.height / 4,
- }}
- onPress={() => this.peerClick(data)}
- key={data}>
- <RtcRemoteView.SurfaceView
- key={data}
- uid={data} //id of the user who sees the stream
- style={{
- width: dimensions.width / 2,
- height: dimensions.height / 4,
- }}
- channelId={channelName}
- />
- </TouchableOpacity>
- ))}
- </ScrollView>
- </View>
- </View>
- ) : this.state.peerIds.length > 0 ? (
- <View style={{height: dimensions.height - 50}}>
- <RtcRemoteView.SurfaceView
- key={this.state.peerIds[0]}
- uid={this.state.peerIds[0]} //id of the user who sees the stream
- style={styles.full}
- channelId={channelName}
- />
- </View>
- ) : (
- <Text>No users connected</Text>
- )}
- {!this.state.vidMute ? ( //view for local video
- <RtcLocalView.SurfaceView
- style={styles.localVideoStyle}
- channelId={channelName}
- zOrderMediaOverlay={true}
- uid={this.state.peerIds[0]}
- />
- ) : (
- <View />
- )}
- <View style={styles.buttonBar}>
- <Button
- style={styles.iconStyle}
- backgroundColor="#0093E9"
- title={this.state.audMute ? 'mic-off' : 'mic'}
- onPress={() => this.toggleAudio()}
- />
- <Button
- style={styles.iconStyle}
- backgroundColor="reds"
- title="call-end"
- onPress={() => this.endCall()}
- />
- <Button
- style={styles.iconStyle}
- backgroundColor="#0093E9"
- title={this.state.vidMute ? 'videocam-off' : 'videocam'}
- onPress={() => this.toggleVideo()}
- />
- <Button
- style={styles.iconStyle}
- backgroundColor="#0093E9"
- title={'switch-video'}
- onPress={() => this._rtcEngine?.switchCamera()}
- />
- <Button
- style={styles.iconStyle}
- backgroundColor="#0093E9"
- title={'refresh'}
- onPress={() => this.refreshCamera()}
- />
- </View>
- </View>
- );
- }
- }
- const mapStateToProps = (state) => ({
- user: state.user.details,
- });
- export default connect(mapStateToProps, {
- })(VideoScreen);
- const styles = StyleSheet.create({
- buttonBar: {
- height: 50,
- backgroundColor: '#0093E9',
- display: 'flex',
- width: '100%',
- position: 'absolute',
- bottom: 0,
- left: 0,
- flexDirection: 'row',
- justifyContent: 'center',
- alignContent: 'center',
- },
- localVideoStyle: {
- width: 140,
- height: 160,
- position: 'absolute',
- top: 5,
- right: 5,
- zIndex: 100,
- },
- iconStyle: {
- fontSize: 34,
- paddingTop: 15,
- paddingLeft: 20,
- paddingRight: 20,
- paddingBottom: 15,
- borderRadius: 0,
- },
- full: {
- flex: 1,
- },
- buttonText: {
- color: '#fff',
- },
- button: {
- paddingHorizontal: 16,
- paddingVertical: 8,
- backgroundColor: '#38373A',
- },
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement