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

496 lines
13 KiB
React
Raw Normal View History

2018-02-17 03:18:53 +08:00
import React, { Component } from 'react';
import { styles } from './styles';
import { defineMessages, injectIntl } from 'react-intl';
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';
import _ from 'lodash';
import VideoService from './service';
import VideoList from './video-list/component';
2018-02-17 03:18:53 +08:00
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',
},
2018-02-17 03:18:53 +08:00
});
const RECONNECT_WAIT_TIME = 5000;
const CAMERA_SHARE_FAILED_WAIT_TIME = 10000;
class VideoProvider extends Component {
constructor(props) {
super(props);
this.state = {
2018-03-12 23:29:51 +08:00
sharedWebcam: false,
socketOpen: false,
2018-02-17 03:18:53 +08:00
};
// Set a valid bbb-webrtc-sfu application server socket in the settings
this.ws = new ReconnectingWebSocket(Meteor.settings.public.kurento.wsUrl);
this.wsQueue = [];
this.reconnectWebcam = false;
this.cameraTimeouts = {};
this.webRtcPeers = {};
this.openWs = this.ws.open.bind(this.ws);
2018-02-17 03:18:53 +08:00
this.onWsOpen = this.onWsOpen.bind(this);
this.onWsClose = this.onWsClose.bind(this);
this.onWsMessage = this.onWsMessage.bind(this);
this.unshareWebcam = this.unshareWebcam.bind(this);
this.shareWebcam = this.shareWebcam.bind(this);
}
componentWillMount() {
this.ws.addEventListener('open', this.onWsOpen);
this.ws.addEventListener('close', this.onWsClose);
window.addEventListener('online', this.openWs);
2018-02-17 03:18:53 +08:00
window.addEventListener('offline', this.onWsClose);
}
componentDidMount() {
document.addEventListener('joinVideo', this.shareWebcam); // TODO find a better way to do this
document.addEventListener('exitVideo', this.unshareWebcam);
2018-02-17 03:18:53 +08:00
this.ws.addEventListener('message', this.onWsMessage);
}
shouldComponentUpdate({ users: nextUsers }, nextState) {
const { users } = this.props;
return !_.isEqual(this.state, nextState) || users.length !== nextUsers.length;
}
componentWillUpdate({ users, userId }) {
const usersSharingIds = users.map(u => u.id);
const usersConnected = Object.keys(this.webRtcPeers);
const usersToConnect = usersSharingIds.filter(id => !usersConnected.includes(id));
const usersToDisconnect = usersConnected.filter(id => !usersSharingIds.includes(id));
usersToConnect.forEach(id => this.createWebRTCPeer(id, userId === id));
usersToDisconnect.forEach(id => this.stopWebRTCPeer(id));
console.warn('[usersToConnect]', usersToConnect);
console.warn('[usersToDisconnect]', usersToDisconnect);
}
2018-02-17 03:18:53 +08:00
componentWillUnmount() {
document.removeEventListener('joinVideo', this.shareWebcam);
document.removeEventListener('exitVideo', this.unshareWebcam);
this.ws.removeEventListener('message', this.onWsMessage);
this.ws.removeEventListener('open', this.onWsOpen);
this.ws.removeEventListener('close', this.onWsClose);
window.removeEventListener('online', this.openWs);
2018-02-17 03:18:53 +08:00
window.removeEventListener('offline', this.onWsClose);
// Unshare user webcam
if (this.state.sharedWebcam) {
this.unshareWebcam();
}
Object.keys(this.webRtcPeers).forEach((id) => {
this.stopWebRTCPeer(id);
2018-02-17 03:18:53 +08:00
});
// Close websocket connection to prevent multiple reconnects from happening
// Don't disonnect socket on unmount to prevent multiple reconnects
// this.ws.close();
2018-02-17 03:18:53 +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.setState({ socketOpen: true });
2018-02-17 03:18:53 +08:00
}
onWsClose(error) {
log('debug', '------ Websocket connection closed.');
this.stopWebRTCPeer(this.props.userId);
this.setState({ socketOpen: false });
2018-02-17 03:18:53 +08:00
}
disconnected(id) {
this.reconnectList.push(id);
2018-02-17 03:18:53 +08:00
log('debug', ` [camera] ${id} disconnected, will try re-subscribe later.`);
}
onWsMessage(msg) {
const { intl } = this.props;
const parsedMessage = JSON.parse(msg.data);
console.log('Received message new ws message: ');
console.log(parsedMessage);
switch (parsedMessage.id) {
case 'startResponse':
this.startResponse(parsedMessage);
break;
case 'playStart':
this.handlePlayStart(parsedMessage);
break;
case 'playStop':
this.handlePlayStop(parsedMessage);
break;
case 'iceCandidate':
this.handleIceCandidate(parsedMessage);
break;
case 'error':
default:
this.handleError(parsedMessage);
break;
}
}
sendMessage(message) {
const ws = this.ws;
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
if (message.id != 'stop') {
this.wsQueue.push(message);
}
}
}
connectedToMediaServer() {
return this.ws.readyState === WebSocket.OPEN;
}
startResponse(message) {
const id = message.cameraId;
const webRtcPeer = this.webRtcPeers[id];
if (message.sdpAnswer == null || webRtcPeer == null) {
return log('debug', 'Null sdp answer or null webrtcpeer');
}
log('info', 'SDP answer received from server. Processing ...');
webRtcPeer.processAnswer(message.sdpAnswer, (error) => {
if (error) {
return log('error', error);
}
2018-02-17 05:11:59 +08:00
if (message.cameraId == this.props.userId) {
2018-02-17 03:18:53 +08:00
log('info', 'camera id sendusershare ', id);
VideoService.sendUserShareWebcam(id);
}
});
}
handleIceCandidate(message) {
2018-03-12 23:29:51 +08:00
const { intl } = this.props;
2018-02-17 03:18:53 +08:00
const webRtcPeer = this.webRtcPeers[message.cameraId];
if (webRtcPeer) {
if (webRtcPeer.didSDPAnswered) {
webRtcPeer.addIceCandidate(message.candidate, (err) => {
if (err) {
this.notifyError(intl.formatMessage(intlMessages.iceCandidateError));
return log('error', `Error adding candidate: ${err}`);
}
});
} else {
webRtcPeer.iceQueue.push(message.candidate);
}
} else {
log('error', ' [ICE] Message arrived after the peer was already thrown out, discarding it...');
}
}
stopWebRTCPeer(id) {
log('info', 'Stopping webcam', id);
const userId = this.props.userId
const shareWebcam = id === userId;
2018-02-17 03:18:53 +08:00
if (shareWebcam) {
this.unshareWebcam();
}
this.sendMessage({
type: 'video',
role: shareWebcam ? 'share' : 'viewer',
id: 'stop',
cameraId: id,
});
2018-02-17 03:18:53 +08:00
// Clear the shared camera fail timeout when destroying
clearTimeout(this.cameraTimeouts[id]);
delete this.cameraTimeouts[id];
this.destroyWebRTCPeer(id);
}
2018-02-17 03:18:53 +08:00
destroyWebRTCPeer(id) {
const webRtcPeer = this.webRtcPeers[id];
2018-02-17 03:18:53 +08:00
if (webRtcPeer) {
log('info', 'Stopping WebRTC peer');
webRtcPeer.dispose();
delete this.webRtcPeers[id];
} else {
log('info', 'No WebRTC peer to stop (not an error)');
}
}
createWebRTCPeer(id, shareWebcam) {
2018-02-17 03:18:53 +08:00
const that = this;
const { intl, meetingId } = this.props;
2018-02-17 03:18:53 +08:00
2018-04-09 22:39:27 +08:00
const videoConstraints = {
width: {
min: 320,
max: 640,
},
height: {
min: 180,
max: 480,
2018-04-09 22:39:27 +08:00
},
};
if (!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)) {
videoConstraints.frameRate = { min: 5, ideal: 10 };
}
const options = {
2018-02-17 05:11:59 +08:00
mediaConstraints: {
audio: false,
2018-04-09 22:39:27 +08:00
video: videoConstraints,
2018-02-17 05:11:59 +08:00
},
onicecandidate: this.getOnIceCandidateCallback(id, shareWebcam),
};
let WebRtcPeerObj = window.kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly;
2018-02-17 05:11:59 +08:00
if (shareWebcam) {
WebRtcPeerObj = window.kurentoUtils.WebRtcPeer.WebRtcPeerSendonly;
2018-04-09 22:39:27 +08:00
this.shareWebcam();
2018-02-17 05:11:59 +08:00
}
WebRtcPeerObj.started = false;
that.webRtcPeers[id] = new WebRtcPeerObj(options, function (error) {
2018-02-17 03:18:53 +08:00
if (error) {
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. */
that.stopWebRTCPeer(id);
if (shareWebcam) {
that.unshareWebcam();
}
2018-02-17 03:18:53 +08:00
return log('error', error);
}
this.didSDPAnswered = false;
this.iceQueue = [];
this.generateOffer((error, offerSdp) => {
if (error) {
log('error', ' WebRtc generate offer error');
that.stopWebRTCPeer(id);
2018-02-17 03:18:53 +08:00
return log('error', error);
}
that.cameraTimeouts[id] = setTimeout(() => {
log('error', `Camera share has not suceeded in ${CAMERA_SHARE_FAILED_WAIT_TIME} for ${id}`);
if (that.props.userId == id) {
that.notifyError(intl.formatMessage(intlMessages.sharingError));
that.unshareWebcam();
that.destroyWebRTCPeer(id);
} else {
that.stopWebRTCPeer(id);
that.createWebRTCPeer(id, shareWebcam);
}
}, CAMERA_SHARE_FAILED_WAIT_TIME);
2018-02-17 03:18:53 +08:00
console.log(`Invoking SDP offer callback function ${location.host}`);
const message = {
type: 'video',
role: shareWebcam ? 'share' : 'viewer',
id: 'start',
sdpOffer: offerSdp,
cameraId: id,
meetingId,
2018-02-17 03:18:53 +08:00
};
that.sendMessage(message);
});
while (this.iceQueue.length) {
const candidate = this.iceQueue.shift();
this.addIceCandidate(candidate, (err) => {
if (err) {
this.notifyError(intl.formatMessage(intlMessages.iceCandidateError));
return console.error(`Error adding candidate: ${err}`);
}
});
}
this.didSDPAnswered = true;
});
}
getOnIceCandidateCallback(id, shareWebcam) {
const that = this;
2018-02-17 03:18:53 +08:00
return function (candidate) {
const message = {
type: 'video',
role: shareWebcam ? 'share' : 'viewer',
id: 'onIceCandidate',
candidate,
cameraId: id,
};
that.sendMessage(message);
};
}
2018-02-17 03:18:53 +08:00
attachVideoStream(id, video) {
if (video.srcObject) return; // Skip if the stream is already attached
2018-02-17 03:18:53 +08:00
const isCurrent = id === this.props.userId;
const peer = this.webRtcPeers[id];
const { peerConnection } = peer;
const attachVideoStream = () => {
const stream = isCurrent ? peer.getLocalStream() : peer.getRemoteStream();
video.pause();
video.srcObject = stream;
video.load();
};
if (peer) {
if (peer.started === true) {
attachVideoStream();
return;
}
2018-02-17 03:18:53 +08:00
peer.on('playStart', attachVideoStream);
}
2018-02-17 03:18:53 +08:00
}
handlePlayStop(message) {
const id = message.cameraId;
log('info', 'Handle play stop for camera', id);
this.stopWebRTCPeer(id);
2018-02-17 03:18:53 +08:00
}
handlePlayStart(message) {
const id = message.cameraId;
log('info', 'Handle play start for camera', id);
2018-02-17 03:18:53 +08:00
const peer = this.webRtcPeers[id];
2018-02-17 03:18:53 +08:00
// Clear camera shared timeout when camera succesfully starts
clearTimeout(this.cameraTimeouts[id]);
this.cameraTimeouts[id] = null;
2018-02-17 03:18:53 +08:00
peer.emit('playStart');
peer.started = true;
2018-02-17 05:11:59 +08:00
if (message.cameraId == this.props.userId) {
2018-02-17 03:18:53 +08:00
VideoService.joinedVideo();
}
}
handleError(message) {
const { intl } = this.props;
2018-02-17 05:11:59 +08:00
const userId = this.props.userId;
2018-02-17 03:18:53 +08:00
if (message.cameraId == userId) {
this.unshareWebcam();
this.notifyError(intl.formatMessage(intlMessages.sharingError));
} else {
this.stopWebRTCPeer(message.cameraId);
2018-02-17 03:18:53 +08:00
}
console.error(' Handle error --------------------->');
log('debug', message.message);
}
notifyError(message) {
notify(message, 'error', 'video');
}
shareWebcam() {
2018-04-09 22:39:27 +08:00
const { intl } = this.props;
2018-02-17 03:18:53 +08:00
if (this.connectedToMediaServer()) {
log('info', 'Sharing webcam');
this.setState({ sharedWebcam: true });
VideoService.joiningVideo();
} else {
log('debug', 'Error on sharing webcam');
this.notifyError(intl.formatMessage(intlMessages.sharingError));
}
2018-02-17 03:18:53 +08:00
}
unshareWebcam() {
log('info', 'Unsharing webcam');
2018-02-17 05:11:59 +08:00
VideoService.sendUserUnshareWebcam(this.props.userId);
VideoService.exitedVideo();
this.setState({ sharedWebcam: false });
2018-02-17 03:18:53 +08:00
}
render() {
if (!this.state.socketOpen) return null;
2018-02-17 03:18:53 +08:00
return (
<VideoList
users={this.props.users}
onMount={this.attachVideoStream.bind(this)}
/>
2018-02-17 03:18:53 +08:00
);
}
}
2018-03-12 23:29:51 +08:00
export default injectIntl(VideoProvider);