react-native-jannuscustom

1.3.6 • Public • Published
import { mediaDevices, MediaStream, RTCIceCandidate, RTCPeerConnection, RTCSessionDescription, RTCView } from 'react-native-webrtc';
import React from 'react';
import { Dimensions, FlatList, StatusBar, TouchableOpacity, View, Text } from 'react-native';
import { JanusMain, JanusVideoRoomPlugin, JanusShareScreenPlugin } from 'react-native-jannuscustom';
const \_height = Dimensions.get("window").height;
const \_width = Dimensions.get("window").width;
import WebView from 'react-native-webview';
import io from 'socket.io-client';
import { ScrollView } from 'react-native-gesture-handler';
import Janus from './janus.mobile.js';
import Icon from 'react-native-vector-icons/FontAwesome';
JanusMain.setDependencies({
RTCPeerConnection,
RTCSessionDescription,
RTCIceCandidate,
MediaStream,
});

class video extends React.Component {
constructor(props) {
super(props);
const \_window = Dimensions.get("window");
var \_win = \_window;
if (\_win.width < \_win.height) {
\_win.width = \_window.height;
\_win.height = \_win.width;
}
var camWidth = 200;
if (\_win.width > 1024) camWidth = 300;
else if (\_win.width > 900) camWidth = 250;
else if (\_win.width < 700) camWidth = 170;
var camHeigh = Math.ceil(camWidth / 1.4);
var remainWidth = \_win.width - camWidth;
var scale = Platform.OS == 'ios' ? Platform.isPad ? remainWidth / 920 : remainWidth / 980 : remainWidth / 960;//530

var boardHei = 530 \* scale;

    var starHei = 20;
    if ((_win.height - boardHei) / 2 > 100) {
      starHei = 50;
    } else if ((_win.height - boardHei) / 2 > 50) {
      starHei = 30;
    }
    if (scale > 1.0)
      scale = 1.0;
    this.state = {
      stream: null,
      publishers: [],
      publishersScreen: [],
      camWidth: camWidth,
      camHeigh: camHeigh,
      scale: scale.toFixed(2),
      remWidth: _win.width - camWidth,
      isPublishing: false,
      isMute: false,
    };

}

async receivePublisher(publisher) {
try {
let videoRoom = new JanusVideoRoomPlugin(this.janus);
videoRoom.setRoomID(1234);
videoRoom.setOnStreamListener((stream) => {
this.setState(state => ({
publishers: [
...state.publishers,
{
publisher: publisher,
stream: stream,
},
],
}));
});

      await videoRoom.createPeer();
      await videoRoom.connect();
      await videoRoom.receive(this.videoRoom.getUserPrivateID(), publisher);
    } catch (e) {
      console.error(e);
    }

}
async receivePublisherScreen(publisher) {
try {
let videoRoomScreen = new JanusShareScreenPlugin(this.janus1);
videoRoomScreen.setRoomID("Your roomID number");
videoRoomScreen.setOnStreamListener((stream) => {
console.log("stream", stream);
this.setState({
publishersScreen: [
{
publisherScreen: publisher,
streamScreen: stream,
},
],
});
});

      await videoRoomScreen.createPeer();
      await videoRoomScreen.connect();
      await videoRoomScreen.receive(this.videoRoomScreen.getUserPrivateID(), publisher);
    } catch (e) {
      console.error(e);
    }

}

async removePublisher(publisherID) {
try {
this.setState(state => ({
publishers: state.publishers.filter(pub => pub.publisher == null || pub.publisher.id !== publisherID),
}));
} catch (e) {
console.error(e);
}
}
async removePublisherScreen(publisherID) {
console.log("removePublisherScreen", publisherID);
try {
this.setState({
publishersScreen: [],
});
} catch (e) {
console.error(e);
}
}

async initJanus(stream) {
try {
this.setState(state => ({
publishers: [
{
publisher: null,
stream: stream,
},
],
}));

      let host = "12.34.56.78"("your Host")
      let server = "ws://" + host + ":1111"("your server)
      this.janus = new JanusMain(server);
      this.janus.setApiSecret('janusrocks');
      await this.janus.init();

      this.videoRoom = new JanusVideoRoomPlugin(this.janus);
      this.videoRoom.setRoomID(1234);
      var nameObj = {
        name: 'can',
        role: 'Student'
      }
      this.videoRoom.setDisplayName(JSON.stringify(nameObj));
      this.videoRoom.setOnPublishersListener((publishers) => {
        for (let i = 0; i < publishers.length; i++) {
          this.receivePublisher(publishers[i]);
        }
      });
      this.videoRoom.setOnPublisherJoinedListener((publisher) => {
        this.receivePublisher(publisher);
      });
      this.videoRoom.setOnPublisherLeftListener((publisherID) => {
        this.removePublisher(publisherID);
      });
      this.videoRoom.setOnWebRTCUpListener(async () => {

      });


      this.videoRoom.checkRoomExist(554466).then((res) => {
             console.log("checkExist", res);
        })
        
      await this.videoRoom.createPeer();
      await this.videoRoom.connect();
      await this.videoRoom.join();
      await this.videoRoom.publish(stream);

    } catch (e) {
      console.error('main', JSON.stringify(e));
    }

}
async initJanusScreen() {
try {
      let host = "12.23.56.78"("Your Host")
      let server = "ws://" + host + ":1111"("Change this to your server")
      this.janus1 = new JanusMain(server);
      this.janus1.setApiSecret('janusrocks');
      await this.janus1.init();

      this.videoRoomScreen = new JanusShareScreenPlugin(this.janus1);
      this.videoRoomScreen.setRoomID("Your RoomID to join share screen ");
      var nameObjScreen = {
        name: 'can',
        role: 'Student'
      }
      this.videoRoomScreen.setDisplayName(JSON.stringify(nameObjScreen));
      this.videoRoomScreen.setonPublishersListenerShareScreen((publishers) => {
        for (let i = 0; i < publishers.length; i++) {
          this.receivePublisherScreen(publishers[i]);
        }
      });
      this.videoRoomScreen.setonPublisherJoinedListenerShareScreen((publisher) => {
        this.receivePublisherScreen(publisher);
      });
      this.videoRoomScreen.setOnPublisherLeftListener((publisherID) => {
        this.removePublisherScreen(publisherID);
      });
      this.videoRoomScreen.setOnWebRTCUpListener(async (test) => {
        console.log('test', test)
      });

      await this.videoRoomScreen.createPeer();
      await this.videoRoomScreen.connect();
      await this.videoRoomScreen.joinShareScreen();
      console.log("this.state.publishersScreen", this.state.publishersScreen);

    } catch (e) {
      console.error('main', JSON.stringify(e));
    }

}

getMediaStream = async () => {
let isFront = true;
let sourceInfos = await mediaDevices.enumerateDevices();
let videoSourceId;
for (let i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
console.log(sourceInfo);
if (sourceInfo.kind == 'videoinput' && sourceInfo.facing == (isFront ? 'front' : 'environment')) {
videoSourceId = sourceInfo.deviceId;
}
}

    let stream = await mediaDevices.getUserMedia({
      audio: true,
      video: {
        facingMode: (isFront ? 'user' : 'environment'),
      },
    });
    await this.initJanus(stream);

};

async componentDidMount() {
// this.getMediaStream();
this.socket = io("Your sever", { transports: ['websocket'] });
console.log('socket', this.socket);
this.socket.connect();
this.socket.on('connect', (msg) => {
console.log('connected', msg);
this.socket.emit('room', '123');
this.socket.emit('gethistchat', '123');
});

    this.socket.on('count_client', (data) => {
      console.log(`num-client: ${data}`);
    });

    this.socket.on('gethistchat', (data) => {
      console.log(`gethistchat: ${data}`, data);
    });

    this.socket.on('rev-messages', (data) => {
      console.log(`rev-messages: ${data}`,data);
    });

}

componentWillUnmount = async () => {
if (this.janus) {
await this.janus.destroy();
}
this.socket.removeAllListeners('count_client');
this.socket.removeAllListeners('gethist');
this.socket.removeAllListeners('rev-messages');
this.socket.disconnect();
};

renderView() {
}

render() {
if (this.state.publishersScreen.length > 0) {
console.log("this.state.publishersScreen", this.state.publishersScreen);
}
return (
<View style={{ flex: 1, width: '100%', height: '100%', flexDirection: 'row' }}>
{/_ <StatusBar translucent={true} barStyle={'light-content'} />
<FlatList
data={this.state.publishers}
numColumns={2}
keyExtractor={(item, index) => {
if (item.publisher === null) {
return `rtc-default`;
}
return `rtc-${item.publisher.id}`;
}}
renderItem={({ item }) => (
<RTCView style={{
              flex: 1,
              width: (Dimensions.get('window').width / 2),
              height: (Dimensions.get('window').height / 2),
            }} objectFit={'cover'} streamURL={item.stream.toURL()} />
)}
/> _/}
<View style={{
          flexDirection: 'row', alignItems: 'center',
          justifyContent: 'space-between', marginHorizontal: 10,
          height: Platform.OS == 'ios' ? Platform.isPad ? _height / 1.4 : _height / 1.3 : _height / 1.3,
          marginTop: Platform.OS == 'ios' ? Platform.isPad ? 30 : 0 : 0,
          width: _width / 1.05,
          alignSelf: 'center'
        }}>
<View style={{ flex: 1, borderRadius: 8, backgroundColor: '#fff', marginLeft: 10, overflow: 'hidden' }}>
<View style={{
              paddingBottom: 3, position: 'absolute',
              top: Platform.OS == 'ios' ? Platform.isPad ? 20 : 5 : 5, left: 10, zIndex: 9999
            }}>

            </View>
            <TouchableOpacity
              onPress={() => {
                if (this.state.isMute == false) {
                  this.setState({ isMute: true });
                  this.videoRoom.muteAudio();
                } else {
                  this.setState({ isMute: false });
                  this.videoRoom.unmuteAudio();
                }
              }}
              style={{ position: 'absolute', top: 10, left: 10, zIndex: 9999 }} >
              {
                this.state.isMute == false ?
                  <Icon name="microphone" size={30} color="black" />
                  :
                  <Icon name="microphone-slash" size={30} color="black" />
              }

            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                // this.videoRoom.joinShareScreen();
                this.initJanusScreen()
                // console.log("this.state.publishersScreen", this.state.publishersScreen);
              }}
              style={{ position: 'absolute', top: 10, left: 40, zIndex: 9999 }} >
              <Icon name="video-camera" size={30} color="black" />

            </TouchableOpacity>
            {
              this.state.publishersScreen.length > 0 ?
                this.state.publishersScreen.map((item, index) => {
                  console.log("publishersScreenItem", item);
                  // let role = item.displa;
                  return (
                    <>
                      <RTCView style={{
                        flex: 1,
                        backgroundColor: 'transparent',
                        marginTop: Platform.OS == 'ios' ? Platform.isPad ? 50 : 0 : 25,
                        marginLeft: Platform.OS == 'ios' ? Platform.isPad ? -5 : 23 : 0
                      }}
                        objectFit={'cover'} streamURL={item.streamScreen.toURL()} />
                    </>
                  )
                })
                : <WebView
                  style={{ flex: 1, backgroundColor: 'transparent', marginTop: Platform.OS == 'ios' ? Platform.isPad ? 50 : 0 : 25, marginLeft: Platform.OS == 'ios' ? Platform.isPad ? -5 : 23 : 0 }}
                  ref={(reff) => this.webView = reff}
                  originWhitelist={['*']}
                  mixedContentMode="always"
                  injectedJavaScript={`setScale("${this.state.scale}")`}
                  allowFileAccess={true}
                  allowUniversalAccessFromFileURLs={true}
                  useWebKit={true}
                  allowsInlineMediaPlayback={true}
                  onMessage={this.onMessageFromWeb}
                  onLoadEnd={this.webViewLoadDone}
                  scalesPageToFit={true}
                  source={{ uri:"your webview link" }}
                />
            }

            {
              !!this.state.playingVideo && (
                <Video source={this.state.playingVideo}
                  ref={(ref) => this._player = ref}
                  resizeMode='contain'
                  playWhenInactive={true}
                  paused={this.state.videoPause}
                  style={styles.backgroundVideo} />
              )
            }


          </View>
          <View style={{
            width: this.state.camWidth * 1.19, paddingHorizontal: 2,
            flexDirection: 'column',
            justifyContent: 'space-between',
            marginTop: 3
          }}>
            <View style={{
              backgroundColor: Platform.OS == 'ios' ? this.state.remoteUrl == '' ? '#F2F2F2' : "#fff" : '#F2F2F2',
              borderRadius: 10,
              marginBottom: Platform.OS == 'ios' ? Platform.isPad ? "8%" : 0 : '3%',
              marginLeft: Platform.OS == 'ios' ? Platform.isPad ? 25 : this.state.remoteUrl == '' ? 15 : 15 : 5,
              height: Platform.OS == 'ios' ? Platform.isPad ? this.state.camHeigh * 1.3 : this.state.camHeigh : this.state.camHeigh / 1.15,
              width: this.state.remoteUrl == '' ? Platform.OS == 'ios' ? Platform.isPad ? _width / 3.77 : _width / 3.9 : this.state.camWidth * 1.15 : Platform.OS == 'ios' ? this.state.camWidth * 1.05 : this.state.camWidth * 1.15,
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              {
                this.state.remoteUrl !== '' && this.state.isOffCam && <RTCView
                  streamURL={this.state.remoteUrl}
                  objectFit="contain"
                  zOrder={10}
                  style={{
                    flex: 1,
                    width: Platform.OS == 'ios' ? this.state.camWidth * 1.05 : this.state.camWidth * 1.1,
                    borderRadius: 10,
                    borderWidth: 1, borderColor: '#fff',
                    height: Platform.OS == 'ios' ? Platform.isPad ? this.state.camHeigh * 1.2 : this.state.camHeigh / 1.05 : this.state.camHeigh / 1.2
                  }} />
              }

              {
                this.state.publishers.filter((item, index) => {
                  return this.state.publishers.indexOf(item) === index;
                }).map((item, index) => {
                  console.log('item', item?.publisher?.displayName);
                  if (item?.publisher?.displayName !== undefined) {
                    console.log('item', JSON.parse(item?.publisher?.displayName).role);
                  }
                  // let role = item.displa;
                  return (
                    <>
                      {
                        item?.publisher?.displayName !== undefined && (
                          JSON.parse(item?.publisher?.displayName).role == "Teacher" && (

                            <RTCView style={{
                              flex: 1,
                              width: this.state.camWidth,
                              borderRadius: 10,
                              borderWidth: 1, borderColor: '#fff',
                              height: this.state.camHeigh / 1.15,
                            }} objectFit={'cover'} streamURL={item.stream.toURL()} />
                          )
                        )

                      }
                    </>
                  )
                })
              }

            </View>

            <View style={{
              backgroundColor: Platform.OS == 'ios' ? '#fff' : '#F2F2F2',
              borderRadius: 10, marginTop: 3,
              marginLeft: Platform.OS == 'ios' ? Platform.isPad ? 25 : this.state.localUrl == '' ? 15 : 15 : 5,
              height: this.state.camHeigh / 1.15,
              width: this.state.localUrl == '' ? Platform.OS == 'ios' ? Platform.isPad ? _width / 3.77 : _width / 3.9 : this.state.camWidth * 1.15 : Platform.OS == 'ios' ? this.state.camWidth * 1.05 : this.state.camWidth * 1.15,
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: "row"
            }}>
              <ScrollView>
                <ScrollView
                  nestedScrollEnabled={true}
                  horizontal={true}
                  contentContainerStyle={{ width: this.state.camWidth * 1.1, flexWrap: 'wrap', paddingHorizontal: 2, height: this.state.camHeigh / 1.2, }}
                  style={{ width: "100%" }}
                >
                  {
                    this.state.publishers.filter((item, index) => {
                      return this.state.publishers.indexOf(item) === index;
                    }).map((item, index) => {
                      console.log('item2', item);
                      return (
                        <>
                          {
                            item?.publisher?.displayName !== undefined ? (
                              JSON.parse(item?.publisher?.displayName).role == "Student" && index < 5 && (

                                <View style={{ width: this.state.camWidth / 2, backgroundColor: "yellow", height: this.state.camHeigh / 2.5, margin: 1 }}>
                                  <RTCView style={{
                                    flex: 1,
                                    width: this.state.camWidth / 2,
                                    borderRadius: 10,
                                    marginLeft: 15,
                                    borderWidth: 1, borderColor: '#fff',
                                    height: this.state.camHeigh,
                                  }} objectFit={'cover'} streamURL={item.stream.toURL()} />
                                </View>
                              )
                            ) : (
                              <View style={{ width: this.state.camWidth / 2, backgroundColor: "yellow", height: this.state.camHeigh / 2.5, margin: 1 }}>
                                <RTCView style={{
                                  flex: 1,
                                  width: this.state.camWidth / 2,
                                  borderRadius: 10,
                                  marginLeft: 15,
                                  borderWidth: 1, borderColor: '#fff',
                                  height: this.state.camHeigh,
                                }} objectFit={'cover'} streamURL={item.stream.toURL()} />
                              </View>
                            )
                          }
                        </>
                      )
                    })
                  }
                </ScrollView>
              </ScrollView>
            </View>
          </View>
        </View>
      </View>
    );

}
}

export default video;

Readme

Keywords

Package Sidebar

Install

npm i react-native-jannuscustom

Weekly Downloads

1

Version

1.3.6

License

MIT

Unpacked Size

79 kB

Total Files

13

Last publish

Collaborators

  • vuhai2112