Advertisement
Guest User

Untitled

a guest
Apr 7th, 2021
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.70 KB | None | 0 0
  1. import React, { Component, Fragment } from 'react';
  2. import { connect } from 'react-redux';
  3. import { StyleSheet } from 'react-native';
  4. import {
  5. Platform,
  6. ScrollView,
  7. Text,
  8. TextInput,
  9. TouchableOpacity,
  10. View,
  11. Dimensions,
  12. Button
  13. } from 'react-native';
  14. import RtcEngine, { ClientRole, ChannelProfile, RtcLocalView,
  15. RtcRemoteView } from 'react-native-agora';
  16. import RtmEngine from 'agora-react-native-rtm';
  17. import IdleTimerManager from 'react-native-idle-timer';
  18. import requestCameraAndAudioPermission from '../../util/VideoPermisions';
  19. import {APPLICATION_CLIENT_ROUTES, APPLICATION_ROUTES} from "../../constants";
  20.  
  21. let dimensions = {
  22. //get dimensions of the device to use in view styles
  23. width: Dimensions.get('window').width,
  24. height: Dimensions.get('window').height,
  25. };
  26.  
  27. class VideoScreen extends Component {
  28. _rtcEngine;
  29. _rtmEngine;
  30.  
  31. constructor(props) {
  32. super(props);
  33. IdleTimerManager.setIdleTimerDisabled(true);
  34.  
  35. this.state = {
  36. peerIds: [], //Array for storing connected peers
  37. appId: '26180e17618e4741ad482f9b938b7c87',
  38. token: null,
  39. isHost: true,
  40. channelName: 'Yyy',
  41. joinSucceed: false,
  42. rtcUid: parseInt((new Date().getTime() + '').slice(4, 13), 10),
  43. myUsername: '',
  44. usernames: {},
  45. audMute: false
  46. };
  47. if (Platform.OS === 'android') {
  48. // Request required permissions from Android
  49. requestCameraAndAudioPermission().then(() => {
  50. console.log('requested!');
  51. });
  52. }
  53. }
  54.  
  55. componentDidMount() {
  56. this.unsubscribeFocus = this.props.navigation.addListener(
  57. 'focus',
  58. async () => {
  59. this.setState({myUsername: this.props.user.firstName + this.props.user.lastName})
  60. await this.initRTC();
  61. await this.initRTM();
  62. await this.startCall();
  63. }
  64. );
  65. }
  66.  
  67. async sendTestMessage() {
  68. await this._rtmEngine
  69. ?.sendMessageByChannelId(this.state.channelName, 'popopopopopopopopopopopopop')
  70. .catch((e) => console.log(e))
  71. .done(() => console.log('MESSAGE SENT'));
  72. }
  73.  
  74. componentWillUnmount() {
  75. this._rtmEngine?.destroyClient();
  76. this._rtcEngine?.destroy();
  77. }
  78. /**
  79. * @name initRTC
  80. * @description Function to initialize the Rtc Engine, attach event listeners and actions
  81. */
  82. initRTC = async () => {
  83. const { appId, isHost } = this.state;
  84. this._rtcEngine = await RtcEngine.create(appId);
  85. await this._rtcEngine.enableVideo();
  86. await this._rtcEngine.setChannelProfile(ChannelProfile.LiveBroadcasting);
  87. await this._rtcEngine.setClientRole(
  88. isHost ? ClientRole.Broadcaster : ClientRole.Audience
  89. );
  90.  
  91. this._rtcEngine.addListener('Error', (err) => {
  92. console.log('Error', err);
  93. });
  94.  
  95. this._rtcEngine.addListener('UserJoined', (uid, elapsed) => {
  96. //console.log('UserJoined', uid, elapsed);
  97. // Get current peer IDs
  98. const { peerIds } = this.state;
  99. // If new user
  100. if (peerIds.indexOf(uid) === -1) {
  101. this.setState({
  102. // Add peer ID to state array
  103. peerIds: [...peerIds, uid],
  104. });
  105. }
  106. });
  107.  
  108. this._rtcEngine.addListener('UserOffline', (uid, reason) => {
  109. console.log('UserOffline', uid, reason);
  110. const { peerIds } = this.state;
  111. this.setState({
  112. // Remove peer ID from state array
  113. peerIds: peerIds.filter((id) => id !== uid),
  114. });
  115. });
  116.  
  117. // If Local user joins RTC channel
  118. this._rtcEngine.addListener(
  119. 'JoinChannelSuccess',
  120. (channel, uid, elapsed) => {
  121. //console.log('JoinChannelSuccess', channel, uid, elapsed);
  122. this.setState({
  123. joinSucceed: true,
  124. rtcUid: uid,
  125. peerIds: [...this.state.peerIds, uid]
  126. });
  127. console.log(this.state)
  128. }
  129. );
  130.  
  131. return true;
  132. };
  133.  
  134. /**
  135. * @name initRTM
  136. * @description Function to initialize the Rtm Engine, attach event listeners and use them to sync usernames
  137. */
  138. initRTM = async () => {
  139. let { appId, usernames, rtcUid } = this.state;
  140. this._rtmEngine = new RtmEngine();
  141. this._rtmEngine.on('error', (evt) => {
  142. console.log('ERRORRRRRRRRRRRRRRR', evt);
  143. });
  144.  
  145. this._rtmEngine.on('channelMessageReceived', (evt) => {
  146. console.log('XXXXXXXXXXXX')
  147. let { text } = evt;
  148. let data = text.split(':');
  149. console.log('cmr', evt);
  150. if (data[1] === '!leave') {
  151. let temp = JSON.parse(JSON.stringify(usernames));
  152. Object.keys(temp).map((k) => {
  153. if (k === data[0]) delete temp[k];
  154. });
  155. this.setState({
  156. usernames: temp,
  157. });
  158. } else {
  159. this.setState({
  160. usernames: { ...usernames, [data[0]]: data[1] },
  161. });
  162. }
  163. });
  164.  
  165. this._rtmEngine.on('messageReceived', (evt) => {
  166. console.log('MMMMMMMMM');
  167. let { text } = evt;
  168. let data = text.split(':');
  169. console.log('pm', evt);
  170. this.setState({
  171. usernames: { ...usernames, [data[0]]: data[1] },
  172. });
  173. });
  174.  
  175. this._rtmEngine.on('channelMemberJoined', (evt) => {
  176. console.log('aaaaaaaaaaaa')
  177. console.log('!spm', this.state.myUsername);
  178. this._rtmEngine?.sendMessageToPeer({
  179. peerId: evt.uid,
  180. text: rtcUid + ':' + this.state.myUsername,
  181. offline: false,
  182. });
  183. });
  184.  
  185. await this._rtmEngine.createClient(appId).catch((e) => console.log(e));
  186. return true;
  187. };
  188.  
  189. /**
  190. * @name startCall
  191. * @description Function to start the call
  192. */
  193. startCall = async () => {
  194. let { myUsername, token, channelName, rtcUid } = this.state;
  195. //if (myUsername) {
  196. // Join RTC Channel using null token and channel name
  197. await this._rtcEngine?.joinChannel(token, channelName, null, rtcUid);
  198. // Login & Join RTM Channel
  199. await this._rtmEngine
  200. ?.login({ uid: myUsername })
  201. .catch((e) => console.log(e));
  202. await this._rtmEngine
  203. ?.joinChannel(channelName)
  204. .catch((e) => console.log(e));
  205. await this._rtmEngine
  206. ?.sendMessageByChannelId(channelName, rtcUid + ':' + myUsername)
  207. .catch((e) => console.log(e));
  208. //}
  209. };
  210.  
  211. /**
  212. * @name toggleRole
  213. * @description Function to toggle the roll between broadcaster and audience
  214. */
  215. toggleRole = async () => {
  216. this._rtcEngine?.setClientRole(
  217. !this.state.isHost ? ClientRole.Broadcaster : ClientRole.Audience
  218. );
  219. this.setState((ps) => {
  220. return { isHost: !ps.isHost };
  221. });
  222. };
  223.  
  224.  
  225. /**
  226. * @name toggleAudio
  227. * @description Function to toggle local user's audio
  228. */
  229. toggleAudio() {
  230. let mute = this.state.audMute;
  231. console.log('Audio toggle', mute);
  232. this._rtcEngine?.muteLocalAudioStream(!mute);
  233. this.setState({
  234. audMute: !mute,
  235. });
  236. }
  237. /**
  238. * @name toggleVideo
  239. * @description Function to toggle local user's video
  240. */
  241. toggleVideo() {
  242. let mute = this.state.vidMute;
  243. console.log('Video toggle', mute);
  244. this.setState({
  245. vidMute: !mute,
  246. }, () => {
  247. this._rtcEngine?.muteLocalVideoStream(!mute);
  248. });
  249. }
  250. /**
  251. * @name endCall
  252. * @description Function to end the call
  253. */
  254. endCall = async () => {
  255. let { channelName, rtcUid } = this.state;
  256. await this._rtcEngine?.leaveChannel();
  257. await this._rtmEngine
  258. ?.sendMessageByChannelId(channelName, rtcUid + ':!leave')
  259. .catch((e) => console.log(e));
  260. this.setState({ peerIds: [], joinSucceed: false, usernames: {} });
  261. await this._rtmEngine?.logout().catch((e) => console.log(e));
  262. };
  263.  
  264. async refreshCamera() {
  265. await this.endCall();
  266. this.startCall();
  267. }
  268.  
  269. render() {
  270. const { joinSucceed, isHost, channelName, myUsername } = this.state;
  271. return (
  272. <View style={styles.full}>
  273. <Button title="Send Test Message" onPress={() => this.sendTestMessage()} />
  274. {this.state.peerIds.length > 1 ? (
  275. <View style={styles.full}>
  276. <View style={{height: (dimensions.height * 3) / 4 - 50}}>
  277. <RtcLocalView.SurfaceView
  278. style={styles.full}
  279. channelId={channelName}
  280. zOrderMediaOverlay={true}
  281. uid={this.state.peerIds[0]}
  282. />
  283. </View>
  284. <View style={{height: dimensions.height / 4}}>
  285. <ScrollView
  286. horizontal={true}
  287. decelerationRate={0}
  288. snapToInterval={dimensions.width / 2}
  289. snapToAlignment={'center'}
  290. style={{
  291. width: dimensions.width,
  292. height: dimensions.height / 4,
  293. }}>
  294. {this.state.peerIds.slice(1).map(data => (
  295. <TouchableOpacity
  296. style={{
  297. width: dimensions.width / 2,
  298. height: dimensions.height / 4,
  299. }}
  300. onPress={() => this.peerClick(data)}
  301. key={data}>
  302. <RtcRemoteView.SurfaceView
  303. key={data}
  304. uid={data} //id of the user who sees the stream
  305. style={{
  306. width: dimensions.width / 2,
  307. height: dimensions.height / 4,
  308. }}
  309. channelId={channelName}
  310. />
  311. </TouchableOpacity>
  312. ))}
  313. </ScrollView>
  314. </View>
  315. </View>
  316. ) : this.state.peerIds.length > 0 ? (
  317. <View style={{height: dimensions.height - 50}}>
  318. <RtcRemoteView.SurfaceView
  319. key={this.state.peerIds[0]}
  320. uid={this.state.peerIds[0]} //id of the user who sees the stream
  321. style={styles.full}
  322. channelId={channelName}
  323. />
  324. </View>
  325. ) : (
  326. <Text>No users connected</Text>
  327. )}
  328. {!this.state.vidMute ? ( //view for local video
  329. <RtcLocalView.SurfaceView
  330. style={styles.localVideoStyle}
  331. channelId={channelName}
  332. zOrderMediaOverlay={true}
  333. uid={this.state.peerIds[0]}
  334. />
  335. ) : (
  336. <View />
  337. )}
  338. <View style={styles.buttonBar}>
  339. <Button
  340. style={styles.iconStyle}
  341. backgroundColor="#0093E9"
  342. title={this.state.audMute ? 'mic-off' : 'mic'}
  343. onPress={() => this.toggleAudio()}
  344. />
  345. <Button
  346. style={styles.iconStyle}
  347. backgroundColor="reds"
  348. title="call-end"
  349. onPress={() => this.endCall()}
  350. />
  351. <Button
  352. style={styles.iconStyle}
  353. backgroundColor="#0093E9"
  354. title={this.state.vidMute ? 'videocam-off' : 'videocam'}
  355. onPress={() => this.toggleVideo()}
  356. />
  357.  
  358. <Button
  359. style={styles.iconStyle}
  360. backgroundColor="#0093E9"
  361. title={'switch-video'}
  362. onPress={() => this._rtcEngine?.switchCamera()}
  363. />
  364.  
  365. <Button
  366. style={styles.iconStyle}
  367. backgroundColor="#0093E9"
  368. title={'refresh'}
  369. onPress={() => this.refreshCamera()}
  370. />
  371. </View>
  372. </View>
  373. );
  374. }
  375. }
  376.  
  377. const mapStateToProps = (state) => ({
  378. user: state.user.details,
  379. });
  380.  
  381. export default connect(mapStateToProps, {
  382. })(VideoScreen);
  383.  
  384. const styles = StyleSheet.create({
  385. buttonBar: {
  386. height: 50,
  387. backgroundColor: '#0093E9',
  388. display: 'flex',
  389. width: '100%',
  390. position: 'absolute',
  391. bottom: 0,
  392. left: 0,
  393. flexDirection: 'row',
  394. justifyContent: 'center',
  395. alignContent: 'center',
  396. },
  397. localVideoStyle: {
  398. width: 140,
  399. height: 160,
  400. position: 'absolute',
  401. top: 5,
  402. right: 5,
  403. zIndex: 100,
  404. },
  405. iconStyle: {
  406. fontSize: 34,
  407. paddingTop: 15,
  408. paddingLeft: 20,
  409. paddingRight: 20,
  410. paddingBottom: 15,
  411. borderRadius: 0,
  412. },
  413. full: {
  414. flex: 1,
  415. },
  416. buttonText: {
  417. color: '#fff',
  418. },
  419. button: {
  420. paddingHorizontal: 16,
  421. paddingVertical: 8,
  422. backgroundColor: '#38373A',
  423. },
  424. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement