import * as React from "react"; import "./ClassroomMedia.less"; import {Room, ViewMode, RoomState} from "white-web-sdk"; import {Button, Radio, Tooltip, notification, Icon, message} from "antd"; import {GuestUserType, HostUserType} from "../../pages/RoomManager"; import * as set_video from "../../assets/image/set_video.svg"; import * as hangUp from "../../assets/image/hangUp.svg"; import * as menu_in from "../../assets/image/menu_in.svg"; import * as close_white from "../../assets/image/close_white.svg"; import * as microphone_open from "../../assets/image/microphone_open.svg"; import * as microphone_close from "../../assets/image/microphone_close.svg"; import * as camera_open from "../../assets/image/camera_open.svg"; import * as camera_close from "../../assets/image/camera_close.svg"; import ClassroomMediaManager from "./ClassroomMediaManager"; import Identicon from "@netless/identicon"; import {ClassModeType, IdentityType, RtcType, RtcEnum} from "../../pages/NetlessRoomTypes"; import {roomStore} from "../../models/RoomStore"; import {observer} from "mobx-react"; import uuid from "uuid"; import { projectStore } from "../../models/ProjectStore"; export type NetlessStream = { state: {isAudioOpen: boolean, isVideoOpen: boolean, isInStage: boolean, identity?: IdentityType}, } & any; export type ClassroomMediaStates = { isRtcStart: boolean; isMaskAppear: boolean; isFullScreen: boolean; streams: NetlessStream[]; isLocalStreamPublish: boolean; isRtcLoading: boolean; isCameraOpen: boolean; isMicrophoneOpen: boolean; localStream: NetlessStream; }; export type ClassroomMediaProps = { userId: number; channelId: string; room: Room; isAllMemberAudioClose: boolean, classMode: ClassModeType; handleManagerState: () => void; applyForRtc: boolean; isVideoEnable: boolean; isAllowHandUp: boolean; identity?: IdentityType; rtc?: RtcType; userAvatarUrl?: string; roomState: RoomState; }; @observer class ClassroomMedia extends React.Component { private agoraClient: any; public classroomMediaManager: ClassroomMediaManager; public constructor(props: ClassroomMediaProps) { super(props); this.state = { isRtcStart: false, isMaskAppear: false, isFullScreen: false, streams: [], isRtcLoading: false, isLocalStreamPublish: false, isCameraOpen: false, isMicrophoneOpen: false, localStream: null, }; } public componentDidMount(): void { const {userId, identity, rtc} = this.props; if (identity !== IdentityType.host && this.props.isVideoEnable) { const key = `${Date.now()}`; const btn = ( ); if (this.props.classMode === ClassModeType.discuss) { notification.open({ message: `Hello!`, duration: 8, description: "The teacher in this classroom has opened the video communication invitation, please confirm whether to join.", icon: , btn, key, top: 64, }); } else { notification.open({ message: `Hello!`, duration: 8, description: "The teacher in this classroom has started the video lecture, please confirm whether to subscribe or not.", icon: , btn, key, top: 64, }); } } roomStore.startRtc = this.startRtc; roomStore.stopRtc = this.stopRtc; if (rtc && rtc.defaultStart) { this.startRtc(); } } public UNSAFE_componentWillReceiveProps(nextProps: ClassroomMediaProps): void { if (this.props.isVideoEnable !== nextProps.isVideoEnable) { if (nextProps.isVideoEnable) { this.videoJoinRemind(); } else { notification.close("notification"); if (this.props.identity !== IdentityType.host) { this.stopRtc(); } } } if (this.props.classMode !== nextProps.classMode) { if (this.props.identity !== IdentityType.host && nextProps.classMode === ClassModeType.lecture) { this.unpublishStream(true); } else if (this.props.identity === IdentityType.guest && nextProps.classMode === ClassModeType.discuss && !this.state.isLocalStreamPublish && this.props.isVideoEnable) { const key = `${Date.now()}`; const btn = ( ); notification.open({ message: `Hello!`, duration: 8, description: "The teachers in this classroom are open for free discussion. Please confirm whether you want to join.", icon: , btn, key, top: 64, }); } } if (this.props.isAllowHandUp !== nextProps.isAllowHandUp && nextProps.classMode === ClassModeType.lecture && this.props.identity === IdentityType.guest) { if (nextProps.isAllowHandUp) { message.info("The teacher starts to raise your hand, and you can click the [raise your hand] icon in the lower right corner to apply for interaction."); } else { message.info("The teacher closed her hand."); } } if (this.props.isAllMemberAudioClose !== nextProps.isAllMemberAudioClose) { const {localStream} = this.state; if (this.props.identity !== IdentityType.host && localStream) { const uid = localStream.getId(); if (nextProps.isAllMemberAudioClose) { localStream.muteAudio(); this.setAudioState(uid, false); } else { localStream.unmuteAudio(); this.setAudioState(uid, true); } } } if (this.props.applyForRtc !== nextProps.applyForRtc) { const {roomState} = this.props; const hostInfo: HostUserType = (roomState.globalState as any).hostInfo; if (hostInfo.classMode === ClassModeType.lecture && nextProps.applyForRtc && nextProps.isVideoEnable) { const {rtc, userId} = this.props; const {localStream} = this.state; if (localStream) { this.publishStream(); } else { this.createLocalStream(userId); } } else if (hostInfo.classMode === ClassModeType.lecture && !nextProps.applyForRtc) { this.unpublishStream(true); } } } private videoJoinRemind = (): void => { const {userId} = this.props; if (this.props.identity !== IdentityType.host && !this.state.isRtcStart) { const key = `notification`; const btn = ( ); if (this.props.classMode === ClassModeType.discuss) { notification.open({ message: `Hello!`, duration: 8, description: "The teacher in this classroom has opened the video communication invitation, please confirm whether to join.", icon: , btn, key, top: 64, }); } else { notification.open({ message: `Hello!`, duration: 8, description: "The teacher in this classroom has started the video lecture, please confirm whether to subscribe or not.", icon: , btn, key, top: 64, }); } } } private setLocalStreamState = (state: boolean): void => { this.setState({isLocalStreamPublish: state}); } private handleHandup = (classMode: ClassModeType, room: Room, userId?: string): void => { const {roomState} = this.props; const globalGuestUsers: GuestUserType[] = (roomState.globalState as any).guestUsers; const selfHostInfo: HostUserType = (roomState.globalState as any).hostInfo; if (userId) { if (classMode === ClassModeType.lecture && globalGuestUsers) { const users = globalGuestUsers.map((user: GuestUserType) => { if (parseInt(user.userId) === this.props.userId) { user.isHandUp = !user.isHandUp; } return user; }); room.setGlobalState({guestUsers: users}); } } else { if (classMode !== ClassModeType.discuss && globalGuestUsers) { const users = globalGuestUsers.map((user: GuestUserType) => { user.isHandUp = false; user.isReadOnly = true; user.cameraState = ViewMode.Follower; user.disableCameraTransform = true; return user; }); selfHostInfo.cameraState = ViewMode.Broadcaster; selfHostInfo.disableCameraTransform = false; room.setGlobalState({guestUsers: users, hostInfo: selfHostInfo}); } else if (classMode === ClassModeType.discuss && globalGuestUsers) { const users = globalGuestUsers.map((user: GuestUserType) => { user.isHandUp = false; user.isReadOnly = false; user.cameraState = ViewMode.Freedom; user.disableCameraTransform = false; return user; }); selfHostInfo.cameraState = ViewMode.Freedom; selfHostInfo.disableCameraTransform = false; room.setGlobalState({guestUsers: users, hostInfo: selfHostInfo}); } } } private renderHostController = (hostInfo: HostUserType): React.ReactNode => { const {room, roomState} = this.props; const guestUsers: GuestUserType[] = (roomState.globalState as any).guestUsers; if (hostInfo.classMode) { if (this.props.identity === IdentityType.host) { return ( { this.handleHandup(evt.target.value, room); if (hostInfo.classMode === ClassModeType.lecture) { room.setGlobalState({hostInfo: {...hostInfo, classMode: evt.target.value}}); } else { room.setGlobalState({hostInfo: {...hostInfo, classMode: evt.target.value}, guestUsers: guestUsers}); } }}> {projectStore.isEnglish() ? "Lecture" : "讲课模式"} {projectStore.isEnglish() ? "Interactive" : "自由互动"} ); } else { if (projectStore.isEnglish()) { return (
Class mode: {this.handleModeText(hostInfo.classMode)}
); } else { return (
模式:{this.handleModeText(hostInfo.classMode)}
); } } } else { return null; } } private renderHandUpController = (hostInfo: HostUserType): React.ReactNode => { const {room} = this.props; if (hostInfo.classMode) { if (this.props.identity === IdentityType.host && hostInfo.classMode === ClassModeType.lecture) { return ( { this.handleHandup(evt.target.value, room); room.setGlobalState({hostInfo: {...hostInfo, isAllowHandUp: evt.target.value}}); }} > {"Allow to raise hands"} {"Raising hands is forbidden"} ); } else { return null; } } else { return null; } } private handleModeText = (classMode: ClassModeType) => { switch (classMode) { case ClassModeType.discuss: { return "Interactive"; } case ClassModeType.lecture: { return "Lecture"; } default: { return "Hand Up"; } } } private renderRtcBtn = (): React.ReactNode => { const {rtc, roomState, identity} = this.props; const hostInfo: HostUserType = (roomState.globalState as any).hostInfo; if (rtc) { if (hostInfo.classMode === ClassModeType.discuss) { if (identity === IdentityType.listener && !hostInfo.isVideoEnable) { return null; } return (
{this.state.isRtcLoading ?
); } else { if (identity === IdentityType.host) { return (
{this.state.isRtcLoading ?
); } else { if (hostInfo.isVideoEnable) { return (
{this.state.isRtcLoading ?
); } else { return null; } } } } else { return null; } } private renderHost = (): React.ReactNode => { const {roomState, handleManagerState} = this.props; const hostInfo: HostUserType = (roomState.globalState as any).hostInfo; if (hostInfo) { return (
{this.renderRtcBtn()}
handleManagerState()} className="manager-box-btn-right-inner">
{hostInfo.avatar ? : }
{projectStore.isEnglish() ?
Teacher: {hostInfo.name ? hostInfo.name : hostInfo.userId}
:
老师:{hostInfo.name ? hostInfo.name : hostInfo.userId}
} {this.renderHostController(hostInfo)} {this.renderHandUpController(hostInfo)}
); } else { return null; } } private switchCamera = (): void => { const {localStream} = this.state; if (localStream) { const uid = localStream.getId(); if (this.state.isCameraOpen) { const isVideoMute = localStream.muteVideo(); this.setVideoState(uid, false); if (isVideoMute) { this.setState({isCameraOpen: false}); } else { message.warning("Failed to turn off camera"); } } else { const isVideoMute = localStream.unmuteVideo(); this.setVideoState(uid, true); if (isVideoMute) { this.setState({isCameraOpen: true}); } else { message.warning("Failed to open the camera."); } } } } private switchMicrophone = (): void => { const {localStream} = this.state; if (localStream) { const uid = localStream.getId(); if (this.state.isMicrophoneOpen) { const isAudioMute = localStream.muteAudio(); this.setAudioState(uid, false); if (isAudioMute) { this.setState({isMicrophoneOpen: false}); } else { message.warning("Failed to close microphone"); } } else { const isAudioMute = localStream.unmuteAudio(); this.setAudioState(uid, true); if (isAudioMute) { this.setState({isMicrophoneOpen: true}); } else { message.warning("Failed to open microphone"); } } } } private renderSetIcon = (): React.ReactNode => { return (
{ this.setState({isMaskAppear: !this.state.isMaskAppear}); }} className="netless-set-icon"> {this.state.isMaskAppear ? : }
); } private renderJoinVideoIcon = (): React.ReactNode => { const {rtc, userId, identity, classMode} = this.props; if (this.state.isRtcStart && rtc) { if (identity === IdentityType.guest && classMode === ClassModeType.discuss && !this.state.isLocalStreamPublish) { return (
{this.state.isRtcLoading ?
); } else { return null; } } else { return null; } } private setUpCassroomMediaManagerRef (ref: any): void { this.classroomMediaManager = ref; } public render(): React.ReactNode { const {roomState} = this.props; const hostInfo: HostUserType = (roomState.globalState as any).hostInfo; return (
{!this.state.isRtcStart &&
{this.renderHost()}
}
{this.renderSetIcon()} {this.renderJoinVideoIcon()} {this.state.isMaskAppear &&
{ if (roomStore.isRecording && this.props.identity === IdentityType.host) { const key = `rtc-close`; const btn = ( ); notification.open({ message: `Turn off RTC reminders`, duration: 6, description: "You are starting recording service, please stop recording before closing RTC. Otherwise the video and the whiteboard will not record for the same length of time.", icon: , btn, key, top: 64, }); } else { this.stopRtc(); } }}>
{hostInfo.avatar ? : }
{projectStore.isEnglish() ?
Teacher: {hostInfo.name ? hostInfo.name : hostInfo.userId}
:
老师:{hostInfo.name ? hostInfo.name : hostInfo.userId}
} {this.renderHostController(hostInfo)} {this.renderHandUpController(hostInfo)}
{ this.switchMicrophone(); }} className="classroom-box-video-set"> {this.state.isMicrophoneOpen ? : }
{ this.switchCamera(); }} className="classroom-box-video-set"> {this.state.isCameraOpen ? : }
}
); } private setMediaState = (state: boolean): void => { const {room, identity, roomState} = this.props; if (identity === IdentityType.host) { room.setGlobalState({hostInfo: { ...(roomState.globalState as any).hostInfo, isVideoEnable: state, }}); } } private startRtc = async (shouldRecord?: boolean) => { const {rtc, classMode, userId, channelId, identity} = this.props; if (rtc) { let token: string | number[] = ""; let channel: string = channelId; const {rtcObj} = rtc; if (rtc.channel) { channel = rtc.channel; } if (rtc.authConfig !== undefined) { token = rtc.authConfig.token; } const appId = rtc.appId; // 按钮 loading if (!rtcObj) { return; } this.setState({isRtcLoading: true}); // 初始化 const AgoraRTC = rtcObj; if (!this.agoraClient) { this.agoraClient = AgoraRTC.createClient({mode: "live", codec: "h264"}); } this.addRtcListeners(this.agoraClient); this.agoraClient.init(appId, () => { console.log("AgoraRTC client initialized"); this.agoraClient.join(token, channel, userId, (uid: number) => { console.log("User " + uid + " join channel successfully"); // 创建本地流对象 if (identity === IdentityType.host) { this.createLocalStream(userId, identity, shouldRecord); } else if (identity === IdentityType.guest) { if (classMode === ClassModeType.discuss) { this.createLocalStream(userId); } else { this.setMediaState(true); this.setState({isRtcStart: true, isRtcLoading: false}); } } else { this.setMediaState(true); this.setState({isRtcStart: true, isRtcLoading: false}); } // 添加监听 }, (err: any) => { console.log(err); }); }, (err: any) => { console.log("AgoraRTC client init failed", err); }); } else { message.warning("Please add rtc configuration, otherwise it cannot be opened"); } } private stopRtc = (): void => { const { rtc } = this.props; if (rtc && this.agoraClient) { const {localStream} = this.state; this.unpublishStream(); this.agoraClient.leave(() => { this.setState({streams: [], isRtcStart: false, isMaskAppear: false}); roomStore.isRtcOpen = false; this.setMediaState(false); if (localStream) { if (localStream.isPlaying()) { localStream.stop(); } localStream.close(); } console.log("client leaves channel success"); }, (err: any) => { console.log("channel leave failed"); console.error(err); }); this.agoraClient = undefined; } } private unpublishStream = (isLocalStop?: boolean): void => { const {localStream} = this.state; if (localStream) { if (this.state.isLocalStreamPublish) { this.agoraClient.unpublish(localStream, (err: any) => { console.log("unpublish failed"); console.error(err); }); this.setState({isLocalStreamPublish: false}); } if (isLocalStop) { localStream.stop(); localStream.close(); this.removeStream(localStream); this.setState({localStream: null}); } } } private publishStream = (): void => { const {localStream} = this.state; if (localStream) { if (!this.state.isLocalStreamPublish) { this.agoraClient.publish(localStream, (err: any) => { console.log("publish failed"); console.error(err); }); this.setState({isLocalStreamPublish: true}); } } } private createLocalStream = (userId: number, identity?: IdentityType, shouldRecord?: boolean): void => { const { rtc } = this.props; if (rtc) { const { rtcObj } = rtc; const localStream = rtcObj.createStream({ streamID: userId, audio: true, video: true, }); // 初始化本地流 localStream.init(() => { console.log("getUserMedia successfully"); this.setMediaState(true); this.addStream(localStream); this.setState({ isRtcStart: true, isRtcLoading: false, isCameraOpen: true, isMicrophoneOpen: true, localStream: localStream}); if (identity === IdentityType.host) { roomStore.isRtcOpen = true; if (shouldRecord && roomStore.startRecord) { roomStore.startRecord(); } } }, (err: any) => { console.log("getUserMedia failed", err); }); } } private getStreamIdentity = (userId: number): IdentityType => { const {roomState} = this.props; const roomMember = roomState.roomMembers.find((roomMember: any) => { if (roomMember.payload && roomMember.payload.userId !== undefined) { if (parseInt(roomMember.payload.userId) === userId) { return roomMember; } } }); if (roomMember) { return roomMember.payload.identity; } else { return IdentityType.listener; } } private addStream = (stream: any): void => { if (stream) { if (!stream.getId) { const id = uuid.v4(); stream.getId = () => id; } let originalStreamArray = this.state.streams; stream.state = { isVideoOpen: true, isAudioOpen: true, isInStage: false, identity: this.getStreamIdentity(stream.getId()), }; if (originalStreamArray.length > 0) { originalStreamArray = [stream, ...originalStreamArray]; } else { originalStreamArray.push(stream); } this.setState({streams: originalStreamArray}); } } private setMemberToStageById = (userId: number): void => { const originalStreamArray = this.state.streams; const newStreams: NetlessStream[] = originalStreamArray.map(originalStream => { originalStream.isInStage = originalStream.getId() === userId; return originalStream; }); this.setState({streams: newStreams}); } private removeStream = (stream: any): void => { if (stream) { const originalStreamArray = this.state.streams; const newStream = originalStreamArray.filter(originalStream => { return stream.getId() !== originalStream.getId(); }); this.setState({streams: newStream}); } } private setVideoState = (uid: number, state: boolean): void => { const streams = this.state.streams.map(data => { if (data.getId() === uid) { data.state.isVideoOpen = state; } return data; }); this.setState({streams: streams}); } private setAudioState = (uid: number, state: boolean): void => { const streams = this.state.streams.map(data => { if (data.getId() === uid) { data.state.isAudioOpen = state; } return data; }); this.setState({streams: streams}); } private addRtcListeners = (rtcClient: any): void => { // 监听 rtcClient.on("stream-published", () => { console.log("Publish local stream successfully"); }); rtcClient.on("stream-added", (evt: any) => { const stream = evt.stream; console.log("New stream added: " + stream.getId()); rtcClient.subscribe(stream); }); rtcClient.on("stream-removed", (evt: any) => { const stream = evt.stream; this.removeStream(stream); }); rtcClient.on("stream-subscribed", (evt: any) => { const stream = evt.stream; this.addStream(stream); console.log("Subscribe remote stream successfully: " + stream.getId()); }); rtcClient.on("peer-leave", (evt: any) => { const stream = evt.stream; this.removeStream(stream); console.log("remote user left ", evt.uid); }); rtcClient.on("mute-video", (evt: any) => { const uid = evt.uid; this.setVideoState(uid, false); }); rtcClient.on("unmute-video", (evt: any) => { const uid = evt.uid; this.setVideoState(uid, true); }); rtcClient.on("mute-audio", (evt: any) => { const uid = evt.uid; this.setAudioState(uid, false); }); rtcClient.on("unmute-audio", (evt: any) => { const uid = evt.uid; this.setAudioState(uid, true); }); } } export default ClassroomMedia;