bigbluebutton-Github/bigbluebutton-html5/imports/ui/components/video-dock/component.jsx

582 lines
16 KiB
React
Raw Normal View History

import React, { Component } from 'react';
2018-01-08 14:17:18 +08:00
import { styles } from './styles';
import { defineMessages, injectIntl } from 'react-intl';
import VideoService from './service';
import { log } from '/imports/ui/services/api';
import { notify } from '/imports/ui/services/notification';
import { toast } from 'react-toastify';
import Toast from '/imports/ui/components/toast/component';
const intlMessages = defineMessages({
iceCandidateError: {
id: 'app.video.iceCandidateError',
description: 'Error message for ice candidate fail',
},
permissionError: {
id: 'app.video.permissionError',
description: 'Error message for webcam permission',
},
sharingError: {
id: 'app.video.sharingError',
description: 'Error on sharing webcam',
},
chromeExtensionError: {
id: 'app.video.chromeExtensionError',
description: 'Error message for Chrome Extension not installed',
},
chromeExtensionErrorLink: {
id: 'app.video.chromeExtensionErrorLink',
description: 'Error message for Chrome Extension not installed',
},
});
class VideoElement extends Component {
constructor(props) {
super(props);
2017-09-01 23:26:57 +08:00
}
render() {
return <video id={`video-elem-${this.props.videoId}`} width={320} height={240} autoPlay={true} playsInline={true} />;
}
componentDidMount() {
this.props.onMount(this.props.videoId, false);
}
2017-09-01 23:26:57 +08:00
}
class VideoDock extends Component {
2017-09-01 23:26:57 +08:00
constructor(props) {
super(props);
// Set a valid bbb-webrtc-sfu application server socket in the settings
this.ws = new ReconnectingWebSocket(Meteor.settings.public.kurento.wsUrl);
this.wsQueue = [];
this.webRtcPeers = {};
this.reconnectWebcam = false;
this.reconnectList = [];
this.sharedCameraTimeout = null;
this.subscribedCamerasTimeouts = [];
2017-09-01 23:26:57 +08:00
this.state = {
videos: {},
sharedWebcam : false,
2017-09-01 23:26:57 +08:00
};
this.unshareWebcam = this.unshareWebcam.bind(this);
this.shareWebcam = this.shareWebcam.bind(this);
this.onWsOpen = this.onWsOpen.bind(this);
this.onWsClose = this.onWsClose.bind(this);
this.onWsMessage = this.onWsMessage.bind(this);
2017-09-01 23:26:57 +08:00
}
setupReconnectVideos() {
for (id in this.webRtcPeers) {
this.disconnected(id);
this.stop(id);
}
}
reconnectVideos() {
for (i in this.reconnectList) {
const id = this.reconnectList[i];
// TODO: base this on BBB API users instead of using memory
if (id != this.myId) {
setTimeout(() => {
log('debug', ` [camera] Trying to reconnect camera ${id}`);
this.start(id, false);
}, 5000);
}
}
if (this.reconnectWebcam) {
log('debug', ` [camera] Trying to re-share ${this.myId} after reconnect.`);
this.start(this.myId, true);
}
this.reconnectWebcam = false;
this.reconnectList = [];
}
2017-09-01 23:26:57 +08:00
componentDidMount() {
const ws = this.ws;
const { users, userId } = this.props;
for (let i = 0; i < users.length; i++) {
if (users[i].has_stream && users[i].userId !== userId) {
// FIX: Really ugly hack, but sometimes the ICE candidates aren't
// generated properly when we send videos right after componentDidMount
setTimeout(() => {
this.start(users[i].userId, false);
}, 2000);
}
}
2017-09-01 23:26:57 +08:00
document.addEventListener('joinVideo', this.shareWebcam.bind(this));// TODO find a better way to do this
document.addEventListener('exitVideo', this.unshareWebcam.bind(this));
document.addEventListener('installChromeExtension', this.installChromeExtension.bind(this));
2017-09-20 11:12:10 +08:00
window.addEventListener('resize', this.adjustVideos);
2017-09-01 23:26:57 +08:00
ws.addEventListener('message', this.onWsMessage);
}
2017-09-01 23:26:57 +08:00
componentWillMount () {
this.ws.addEventListener('open', this.onWsOpen);
this.ws.addEventListener('close', this.onWsClose);
window.addEventListener('online', this.ws.open.bind(this.ws));
window.addEventListener('offline', this.ws.close.bind(this.ws));
}
2017-09-01 23:26:57 +08:00
componentWillUnmount () {
document.removeEventListener('joinVideo', this.shareWebcam);
document.removeEventListener('exitVideo', this.unshareWebcam);
document.removeEventListener('installChromeExtension', this.installChromeExtension);
window.removeEventListener('resize', this.adjustVideos);
this.ws.removeEventListener('message', this.onWsMessage);
this.ws.removeEventListener('open', this.onWsOpen);
this.ws.removeEventListener('close', this.onWsClose);
// Close websocket connection to prevent multiple reconnects from happening
window.removeEventListener('online', this.ws.open);
window.removeEventListener('offline', this.ws.close);
this.ws.close();
}
2017-09-01 23:26:57 +08:00
adjustVideos () {
setTimeout(() => {
window.adjustVideos('webcamArea', true);
}, 0);
}
2017-09-01 23:26:57 +08:00
onWsOpen () {
log('debug', '------ Websocket connection opened.');
// -- Resend queued messages that happened when socket was not connected
while (this.wsQueue.length > 0) {
this.sendMessage(this.wsQueue.pop());
}
this.reconnectVideos();
}
onWsClose (error) {
log('debug', '------ Websocket connection closed.');
this.setupReconnectVideos();
}
onWsMessage (msg) {
const { intl } = this.props;
const parsedMessage = JSON.parse(msg.data);
2017-09-01 23:26:57 +08:00
console.log('Received message new ws message: ');
console.log(parsedMessage);
2017-09-01 23:26:57 +08:00
switch (parsedMessage.id) {
2017-09-01 23:26:57 +08:00
case 'startResponse':
this.startResponse(parsedMessage);
break;
2017-09-01 23:26:57 +08:00
case 'error':
this.handleError(parsedMessage);
break;
case 'playStart':
this.handlePlayStart(parsedMessage);
break;
case 'playStop':
this.handlePlayStop(parsedMessage);
2017-09-01 23:26:57 +08:00
break;
case 'iceCandidate':
const webRtcPeer = this.webRtcPeers[parsedMessage.cameraId];
if (typeof webRtcPeer !== 'undefined' && webRtcPeer !== null) {
if (webRtcPeer.didSDPAnswered) {
webRtcPeer.addIceCandidate(parsedMessage.candidate, (err) => {
if (err) {
this.notifyError(intl.formatMessage(intlMessages.iceCandidateError));
return log('error', `Error adding candidate: ${err}`);
}
});
2017-09-01 23:26:57 +08:00
} else {
webRtcPeer.iceQueue.push(parsedMessage.candidate);
2017-09-01 23:26:57 +08:00
}
} else {
log('error', ' [ICE] Message arrived after the peer was already thrown out, discarding it...');
}
break;
}
};
2017-09-01 23:26:57 +08:00
start(id, shareWebcam) {
2017-09-01 23:26:57 +08:00
const that = this;
console.log(`Starting video call for video: ${id} with ${shareWebcam}`);
2017-09-01 23:26:57 +08:00
if (shareWebcam) {
VideoService.joiningVideo();
this.setState({sharedWebcam: true});
this.myId = id;
this.initWebRTC(id, true);
} else {
// initWebRTC with shareWebcam false will be called after react mounts the element
this.createVideoTag(id);
}
}
initWebRTC(id, shareWebcam) {
let that = this;
const { intl } = this.props;
2017-09-01 23:26:57 +08:00
const onIceCandidate = function (candidate) {
const message = {
type: 'video',
role: shareWebcam ? 'share' : 'viewer',
2017-09-01 23:26:57 +08:00
id: 'onIceCandidate',
candidate,
cameraId: id,
};
that.sendMessage(message);
};
let videoConstraints = {};
2017-11-29 03:31:36 +08:00
if (!!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)) { // Custom constraints for Safari
videoConstraints = {
width: {min:320, max:640},
height: {min:240, max:480}
}
} else {
videoConstraints = {
width: {min: 320, ideal: 320},
height: {min: 240, ideal:240},
frameRate: {min: 5, ideal: 10}
};
}
let options = {
2017-12-06 03:13:42 +08:00
mediaConstraints: {
audio: false,
2017-11-29 03:31:36 +08:00
video: videoConstraints
},
2017-09-01 23:26:57 +08:00
onicecandidate: onIceCandidate,
};
let peerObj;
if (shareWebcam) {
options.localVideo = this.refs.videoInput;
2017-09-01 23:26:57 +08:00
peerObj = kurentoUtils.WebRtcPeer.WebRtcPeerSendonly;
} else {
peerObj = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly;
options.remoteVideo = document.getElementById(`video-elem-${id}`);
2017-09-01 23:26:57 +08:00
}
let webRtcPeer = new peerObj(options, function (error) {
2017-09-01 23:26:57 +08:00
if (error) {
2017-12-06 03:13:42 +08:00
log('error', ' WebRTC peerObj create error');
log('error', error);
that.notifyError(intl.formatMessage(intlMessages.permissionError));
/* This notification error is displayed considering kurento-utils
* returned the error 'The request is not allowed by the user agent
* or the platform in the current context.', but there are other
* errors that could be returned. */
2017-12-06 03:13:42 +08:00
that.destroyWebRTCPeer(id);
that.destroyVideoTag(id);
VideoService.resetState();
2017-12-06 03:13:42 +08:00
return log('error', error);
2017-09-01 23:26:57 +08:00
}
2017-11-29 03:31:36 +08:00
this.didSDPAnswered = false;
this.iceQueue = [];
that.webRtcPeers[id] = webRtcPeer;
if (shareWebcam) {
that.sharedWebcam = webRtcPeer;
}
2017-09-01 23:26:57 +08:00
this.generateOffer((error, offerSdp) => {
if (error) {
2017-12-06 03:13:42 +08:00
log('error', ' WebRtc generate offer error');
that.destroyWebRTCPeer(id);
that.destroyVideoTag(id);
return log('error', error);
2017-09-01 23:26:57 +08:00
}
console.log(`Invoking SDP offer callback function ${location.host}`);
2017-09-01 23:26:57 +08:00
const message = {
type: 'video',
role: shareWebcam ? 'share' : 'viewer',
2017-09-01 23:26:57 +08:00
id: 'start',
sdpOffer: offerSdp,
cameraId: id,
};
that.sendMessage(message);
});
2017-11-29 03:31:36 +08:00
while (this.iceQueue.length) {
let candidate = this.iceQueue.shift();
2017-11-29 03:31:36 +08:00
this.addIceCandidate(candidate, (err) => {
if (err) {
this.notifyError(intl.formatMessage(intlMessages.iceCandidateError));
2017-11-29 03:31:36 +08:00
return console.error(`Error adding candidate: ${err}`);
}
2017-11-29 03:31:36 +08:00
});
}
this.didSDPAnswered = true;
2017-09-01 23:26:57 +08:00
});
}
disconnected(id) {
if (this.sharedWebcam) {
log('debug', ' [camera] Webcam disconnected, will try re-share webcam later.');
this.reconnectWebcam = true;
} else {
this.reconnectList.push(id);
2017-12-06 03:13:42 +08:00
log('debug', ` [camera] ${id} disconnected, will try re-subscribe later.`);
}
}
2017-09-01 23:26:57 +08:00
stop(id) {
const { userId } = this.props;
2017-12-21 01:05:05 +08:00
this.sendMessage({
type: 'video',
role: id == userId ? 'share' : 'viewer',
2017-12-21 01:05:05 +08:00
id: 'stop',
cameraId: id,
});
2017-12-06 03:13:42 +08:00
if (id === userId) {
VideoService.exitedVideo();
}
2017-12-06 03:13:42 +08:00
this.destroyWebRTCPeer(id);
this.destroyVideoTag(id);
}
createVideoTag(id) {
let videos = this.state.videos;
2017-12-06 03:13:42 +08:00
videos[id] = true;
this.setState({videos: videos})
2017-12-06 03:13:42 +08:00
}
destroyVideoTag(id) {
let videos = this.state.videos;
delete videos[id];
this.setState({videos: videos});
if (id == this.myId) {
this.setState({sharedWebcam: false});
}
2017-12-06 03:13:42 +08:00
}
destroyWebRTCPeer(id) {
const webRtcPeer = this.webRtcPeers[id];
2017-09-01 23:26:57 +08:00
if (webRtcPeer) {
log('info', 'Stopping WebRTC peer');
2017-09-01 23:26:57 +08:00
if (id == this.myId && this.sharedWebcam) {
this.sharedWebcam.dispose();
this.sharedWebcam = null;
}
2017-09-01 23:26:57 +08:00
webRtcPeer.dispose();
delete this.webRtcPeers[id];
2017-09-01 23:26:57 +08:00
} else {
2017-12-06 03:13:42 +08:00
log('info', 'No WebRTC peer to stop (not an error)');
2017-09-01 23:26:57 +08:00
}
}
shareWebcam() {
const { users, userId } = this.props;
2017-09-01 23:26:57 +08:00
if (this.connectedToMediaServer()) {
this.start(userId, true);
} else {
log("error", "Not connected to media server");
}
2017-09-01 23:26:57 +08:00
}
unshareWebcam() {
VideoService.exitingVideo();
2017-12-06 03:13:42 +08:00
log('info', 'Unsharing webcam');
const { userId } = this.props;
VideoService.sendUserUnshareWebcam(userId);
2017-09-01 23:26:57 +08:00
}
startResponse(message) {
const id = message.cameraId;
const webRtcPeer = this.webRtcPeers[id];
2017-09-01 23:26:57 +08:00
if (message.sdpAnswer == null) {
return log('debug', 'Null sdp answer. Camera unplugged?');
2017-09-01 23:26:57 +08:00
}
if (webRtcPeer == null) {
return log('debug', 'Null webrtc peer ????');
2017-09-01 23:26:57 +08:00
}
log('info', 'SDP answer received from server. Processing ...');
2017-09-01 23:26:57 +08:00
webRtcPeer.processAnswer(message.sdpAnswer, (error) => {
if (error) {
2017-12-06 03:13:42 +08:00
return log('error', error);
2017-09-01 23:26:57 +08:00
}
});
if (message.cameraId == this.props.userId) {
log('info', "camera id sendusershare ", id);
VideoService.sendUserShareWebcam(id);
}
2017-09-01 23:26:57 +08:00
}
sendMessage(message) {
const ws = this.ws;
2017-09-01 23:26:57 +08:00
if (this.connectedToMediaServer()) {
const jsonMessage = JSON.stringify(message);
console.log(`Sending message: ${jsonMessage}`);
ws.send(jsonMessage, (error) => {
if (error) {
console.error(`client: Websocket error "${error}" on message "${jsonMessage.id}"`);
}
});
} else {
// No need to queue video stop messages
2017-12-06 03:13:42 +08:00
if (message.id != 'stop') {
this.wsQueue.push(message);
}
}
2017-09-01 23:26:57 +08:00
}
connectedToMediaServer() {
return this.ws.readyState === WebSocket.OPEN;
}
connectionStatus() {
return this.ws.readyState;
}
2017-09-01 23:26:57 +08:00
handlePlayStop(message) {
log('info', 'Handle play stop <--------------------');
log('error', message);
2017-09-01 23:26:57 +08:00
if (message.cameraId == this.props.userId) {
2017-12-21 01:05:05 +08:00
this.unshareWebcam();
} else {
this.stop(message.cameraId);
}
2017-09-01 23:26:57 +08:00
}
handlePlayStart(message) {
log('info', 'Handle play start <===================');
if (message.cameraId == this.props.userId) {
VideoService.joinedVideo();
}
2017-09-01 23:26:57 +08:00
}
handleError(message) {
const { intl } = this.props;
this.notifyError(intl.formatMessage(intlMessages.sharingError));
if (message.cameraId == this.props.userId) {
this.unshareWebcam();
} else {
this.stop(message.cameraId);
}
2017-12-06 03:13:42 +08:00
console.error(' Handle error --------------------->');
log('debug', message.message);
2017-09-01 23:26:57 +08:00
}
notifyError(message) {
notify(message, 'error', 'video');
}
installChromeExtension() {
const { intl } = this.props;
const CHROME_EXTENSION_LINK = Meteor.settings.public.kurento.chromeExtensionLink;
this.notifyError(<div>{intl.formatMessage(intlMessages.chromeExtensionError)} <a href={CHROME_EXTENSION_LINK} target="_blank">{intl.formatMessage(intlMessages.chromeExtensionErrorLink)}</a></div>);
}
componentDidUpdate() {
this.adjustVideos();
}
render() {
let cssClass;
if (this.state.sharedWebcam) {
cssClass = styles.sharedWebcamVideoLocal;
}
else {
cssClass = styles.sharedWebcamVideo;
}
return (
2017-09-01 23:26:57 +08:00
<div className={styles.videoDock}>
<div id="webcamArea">
{Object.keys(this.state.videos).map((id) => {
return (<VideoElement videoId={id} key={id} onMount={this.initWebRTC.bind(this)} />);
})}
<video autoPlay={true} playsInline={true} muted={true} id="shareWebcamVideo" className={cssClass} ref="videoInput" />
</div>
</div>
);
}
2017-09-01 23:26:57 +08:00
shouldComponentUpdate(nextProps, nextState) {
const { users, userId } = this.props;
2017-09-01 23:26:57 +08:00
const nextUsers = nextProps.users;
if (users) {
let suc = false;
for (let i = 0; i < users.length; i++) {
2017-09-19 21:53:27 +08:00
if (users && users[i] &&
nextUsers && nextUsers[i]) {
if (users[i].has_stream !== nextUsers[i].has_stream) {
console.log(`User ${nextUsers[i].has_stream ? '' : 'un'}shared webcam ${users[i].userId}`);
2017-09-01 23:26:57 +08:00
2017-09-19 21:53:27 +08:00
if (nextUsers[i].has_stream) {
if (userId !== users[i].userId) {
this.start(users[i].userId, false);
}
2017-09-01 23:26:57 +08:00
} else {
2017-09-19 21:53:27 +08:00
this.stop(users[i].userId);
2017-09-01 23:26:57 +08:00
}
if (!nextUsers[i].has_stream) {
this.destroyVideoTag(users[i].userId);
}
2017-09-01 23:26:57 +08:00
suc = suc || true;
}
}
}
return true;
}
return false;
}
}
export default injectIntl(VideoDock);