Skip to content

Commit

Permalink
feat: update Web/base-react-next
Browse files Browse the repository at this point in the history
  • Loading branch information
Rychou authored and anderlu committed Jan 11, 2022
1 parent 7e691ac commit 228c11d
Show file tree
Hide file tree
Showing 11 changed files with 106 additions and 43 deletions.
9 changes: 4 additions & 5 deletions Web/base-react-next/public/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
'use strict';
/* exported TimelineDataSeries, TimelineGraphView */

// The maximum number of data points bufferred for each stats. Old data points
// will be shifted out when the buffer is full.
const MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000;

const TimelineDataSeries = (function() {
/**
* @constructor
Expand All @@ -30,6 +26,9 @@ const TimelineDataSeries = (function() {
this.cacheStartTime_ = null;
this.cacheStepSize_ = 0;
this.cacheValues_ = [];
// The maximum number of data points bufferred for each stats. Old data points
// will be shifted out when the buffer is full.
this.maxStatsDataPointBufferSize = 1000;
}

TimelineDataSeries.prototype = {
Expand Down Expand Up @@ -60,7 +59,7 @@ const TimelineDataSeries = (function() {
let time = new Date(timeTicks);
this.dataPoints_.push(new DataPoint(time, value));

if (this.dataPoints_.length > MAX_STATS_DATA_POINT_BUFFER_SIZE) {
if (this.dataPoints_.length > this.maxStatsDataPointBufferSize) {
this.dataPoints_.shift();
}
},
Expand Down
21 changes: 16 additions & 5 deletions Web/base-react-next/src/components/BaseRTC.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,14 @@ export default class RTC extends React.Component {
microphoneId: this.microphoneID,
mirror: this.mirror,
});
await this.localStream.initialize();
this.addStream && this.addStream(this.localStream);
return this.localStream;
try {
await this.localStream.initialize();
this.addStream && this.addStream(this.localStream);
return this.localStream;
} catch (error) {
this.localStream = null;
alert(`${JSON.stringify(error.message)}`);
}
}

destroyLocalStream() {
Expand Down Expand Up @@ -350,8 +355,14 @@ export default class RTC extends React.Component {
console.error(error);
alert(error);
});
this.client.on('client-banned', (error) => {
this.client.on('client-banned', async (error) => {
console.error(`client has been banned for ${error}`);

this.isPublished = false;
this.localStream = null;
this.setState && this.setState('publish', this.isPublished);
await this.handleLeave();

alert(error);
});
// fired when a remote peer is joining the room
Expand All @@ -378,13 +389,13 @@ export default class RTC extends React.Component {
console.log(`remote stream added: [${remoteUserID}] type: ${remoteStream.getType()}`);
// subscribe to this remote stream
this.handleSubscribe(remoteStream);
this.addStream && this.addStream(remoteStream);
}
});
// fired when a remote stream has been subscribed
this.client.on('stream-subscribed', (event) => {
const { stream: remoteStream } = event;
console.log('stream-subscribed userId: ', remoteStream.getUserId());
this.addStream && this.addStream(remoteStream);
});
// fired when the remote stream is removed, e.g. the remote user called Client.unpublish()
this.client.on('stream-removed', (event) => {
Expand Down
27 changes: 18 additions & 9 deletions Web/base-react-next/src/components/CountryCodeSelect/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import a18n from 'a18n';
/* eslint-disable no-use-before-define */
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import styles from './index.module.scss';
import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete';
import InputAdornment from '@material-ui/core/InputAdornment';
import Input from '@material-ui/core/Input';
import { COUNTRIES } from '../../utils/constants';
import { getLanguage } from '@utils/common';

// ISO 3166-1 alpha-2
// ⚠️ No support for IE 11
Expand All @@ -25,6 +26,13 @@ function countryToFlag(isoCode) {

export default function CountryCodeSelect(props) {
const [defaultValue] = useState(() => (props.defaultValue ? props.defaultValue : 46));
const [mountFlag, setMountFlag] = useState(false);

useEffect(() => {
const language = getLanguage();
a18n.setLocale(language);
setMountFlag(true);
}, []);

const handleChange = (event, newValue, reason) => {
console.log('CountryCodeSelect handleChange', event, newValue, reason);
Expand Down Expand Up @@ -57,14 +65,15 @@ export default function CountryCodeSelect(props) {
</React.Fragment>
)}
renderInput={params => (<div ref= {params.InputProps.ref}>
<Input
type= "text"
placeholder={a18n('区号')}
startAdornment= {
<InputAdornment position="start">+</InputAdornment>
}
{...params.inputProps}
/>
{ mountFlag && <Input
type= "text"
placeholder={a18n('区号')}
startAdornment= {
<InputAdornment position="start">+</InputAdornment>
}
{...params.inputProps}
/>
}
</div>
)}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@ export default function DeviceData({ deviceType, updateDeviceList, updateActiveD
alert(a18n`请允许网页访问${deviceType === 'microphone' ? a18n('麦克风') : a18n('摄像头')}的权限!`);
} else if (error.name === 'NotFoundError') {
alert(a18n`请检查${deviceType === 'microphone' ? a18n('麦克风') : a18n('摄像头')}设备连接是否正常!`);
} else if (error.name === 'NotReadableError') {
alert(a18n`请检查${deviceType === 'microphone' ? a18n('麦克风') : a18n('摄像头')}设备是否被其它应用占用或未授权应用权限!`);
}
}

const list = await getDeviceList(deviceType);
updateDeviceList && updateDeviceList(list);
const activeDeviceId = list[0].deviceId;
const activeDeviceId = (list[0] && list[0].deviceId) || '';
updateActiveDeviceId && updateActiveDeviceId(activeDeviceId);
}, []);

Expand Down
6 changes: 3 additions & 3 deletions Web/base-react-next/src/components/DeviceSelect/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ export default function DeviceSelect({ deviceType, onChange }) {
const [activeDevice, setActiveDevice] = useState({});
const [activeDeviceId, setActiveDeviceId] = useState('');

const updateDeviceList = (list) => {
const updateDeviceList = (list = []) => {
setDeviceList((prevList) => {
if (prevList.length === 0) {
setActiveDevice(list[0]);
setActiveDeviceId(list[0].deviceId);
list[0] && setActiveDevice(list[0]);
list[0] && list[0].deviceId && setActiveDeviceId(list[0].deviceId);
}
return list;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import RTC from '@components/BaseRTC';
import toast from '@components/Toast';

class Client extends RTC {
async handlePublish(videoBitRate = 480) {
async handlePublish(options) {
if (!this.isJoined || this.isPublished) {
return;
}
await this.initLocalStream();

await this.localStream.setVideoProfile({
width: 640,
height: 480,
frameRate: 15,
bitrate: videoBitRate,
width: (options && options.videoWidth) || 640,
height: (options && options.videoHeight) || 480,
frameRate: (options && options.videoFps) || 15,
bitrate: (options && options.videoBitRate) || 900,
});

try {
Expand Down
3 changes: 2 additions & 1 deletion Web/base-react-next/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"麦克风": "Mic",
"摄像头": "Camera",
"请检查%s设备连接是否正常!": "Check whether device %s is connected.",
"请检查%s设备是否被其它应用占用!": "Check whether device %s is occupied by other applications.",
"中文": "Chinese",
"英文": "English",
"语言切换": "Language",
Expand Down Expand Up @@ -87,7 +88,7 @@
"远端流为空,无法录制": "The remote stream is empty and cannot be recorded",
"录制内容为空,请先录制": "The recording is empty, please record first",
"请先同意隐私协议!": "Agree to the Privacy Policy first.",
"请检查手机号是否正确": "Invalid phone number",
"请检查手机号、区号是否正确": "Please check whether the cell phone number and area code are correct",
"请检查密码,密码长度不低于6个字符": "The password must contain at least 6 characters.",
"登录异常,请重新登录": "Login error. Please try again.",
"请检查短信验证码": "Verification code required",
Expand Down
3 changes: 2 additions & 1 deletion Web/base-react-next/src/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"麦克风": "麦克风",
"摄像头": "摄像头",
"请检查%s设备连接是否正常!": "请检查%s设备连接是否正常!",
"请检查%s设备是否被其它应用占用!": "请检查%s设备是否被其它应用占用!",
"中文": "中文",
"英文": "英文",
"语言切换": "语言切换",
Expand Down Expand Up @@ -83,7 +84,7 @@
"远端流为空,无法录制": "远端流为空,无法录制",
"录制内容为空,请先录制": "录制内容为空,请先录制",
"请先同意隐私协议!": "请先同意隐私协议!",
"请检查手机号是否正确": "请检查手机号是否正确",
"请检查手机号、区号是否正确": "请检查手机号、区号是否正确",
"请检查密码,密码长度不低于6个字符": "请检查密码,密码长度不低于6个字符",
"登录异常,请重新登录": "登录异常,请重新登录",
"请检查短信验证码": "请检查短信验证码",
Expand Down
59 changes: 48 additions & 11 deletions Web/base-react-next/src/pages/improve-bwe/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import RoomIDInput from '@components/RoomIDInput';
import { getNavConfig } from '@api/nav';
import { getUrlParam } from '@utils/utils';
import { handlePageUrl, handlePageChange, getLanguage } from '@utils/common';
import { Button, Accordion, AccordionSummary, AccordionDetails, makeStyles, Select, TextField, Typography, MenuItem, FormControl, InputLabel } from '@material-ui/core';
import { Button, Accordion, AccordionSummary, AccordionDetails, makeStyles, TextField, Typography } from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import SideBar from '@components/SideBar';
import styles from '@styles/common.module.scss';
Expand Down Expand Up @@ -64,9 +64,12 @@ export default function BasicRtc(props) {
const [isJoined, setIsJoined] = useState(false);
const [isPublished, setIsPublished] = useState(false);
const [isMobile, setIsMobile] = useState(false);
const [videoBitRate, setVideoBitRate] = useState(500);
const [bandValue, setBandValue] = useState('None');
const bandWidthList = ['None', '2000', '1000', '500', '250', '125'];
const [videoWidth, setVideoWidth] = useState(640);
const [videoHeight, setVideoHeight] = useState(480);
const [videoFps, setVideoFps] = useState(15);
const [videoBitRate, setVideoBitRate] = useState(900);
// const [bandValue, setBandValue] = useState('None');
// const bandWidthList = ['None', '2000', '1000', '500', '250', '125'];
const [mountFlag, setMountFlag] = useState(false);

useEffect(() => {
Expand Down Expand Up @@ -98,18 +101,21 @@ export default function BasicRtc(props) {

let bytes;
let packets;
let framesSent;
RTC && RTC.client.getLocalVideoStats().then((stats) => {
(Object.keys(stats || {}) || []).forEach((userId) => {
console.log(`userId: ${userId} bytesSent: ${stats[userId].bytesSent} packetsSent: ${stats[userId].packetsSent}
framesEncoded: ${stats[userId].framesEncoded} framesSent: ${stats[userId].framesSent} frameWidth: ${stats[userId].frameWidth}
frameHeight: stats[userId].frameHeight`);
frameHeight: ${stats[userId].frameHeight}`);
bytes = stats[userId].bytesSent;
packets = stats[userId].packetsSent;
framesSent = stats[userId].framesSent;
const now = new Date().getTime();
if (lastResult) {
// calculate bitrate
const bitrate = (8 * (bytes - lastResult.bytes)) / (now - lastResult.timestamp);
console.log(`video bitrate: ${bitrate}`);
console.log(`video fps: ${(framesSent - lastResult.framesSent) / (now - lastResult.timestamp) * 1000}`);
// append to chart
bitrateSeries.addPoint(now, bitrate);
bitrateGraph.setDataSeries([bitrateSeries]);
Expand All @@ -119,10 +125,10 @@ export default function BasicRtc(props) {
packetGraph.setDataSeries([packetSeries]);
packetGraph.updateEndDate();
}
lastResult = { bytes, packets, timestamp: now };
lastResult = { bytes, packets, timestamp: now, framesSent };
});
});
}, 1000);
}, 3000);
} else {
clearInterval(timerId);
}
Expand All @@ -133,11 +139,21 @@ export default function BasicRtc(props) {

const handleJoin = async () => {
await RTC.handleJoin();
await RTC.handlePublish(videoBitRate);
await RTC.handlePublish({
videoWidth,
videoHeight,
videoFps,
videoBitRate,
});
};

const handlePublish = async () => {
await RTC.handlePublish();
await RTC.handlePublish({
videoWidth,
videoHeight,
videoFps,
videoBitRate,
});
};

const handleUnPublish = async () => {
Expand Down Expand Up @@ -470,22 +486,43 @@ export default function BasicRtc(props) {
<UserIDInput disabled={isJoined} onChange={value => setUserID(value)}></UserIDInput>
<RoomIDInput disabled={isJoined} onChange={value => setRoomID(value)}></RoomIDInput>

<TextField
value={videoWidth}
label="videoWidth"
className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}
onChange={e => setVideoWidth(e.target.value)}
></TextField>

<TextField
value={videoHeight}
label="videoHeight"
className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}
onChange={e => setVideoHeight(e.target.value)}
></TextField>

<TextField
value={videoFps}
label="VideoFps"
className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}
onChange={e => setVideoFps(e.target.value)}
></TextField>

<TextField
value={videoBitRate}
label="VideoBitrate(kbps)"
className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}
onChange={e => setVideoBitRate(e.target.value)}
></TextField>

<FormControl className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}>
{/* <FormControl className={clsx(classes['band-input'], isMobile && classes['band-input-mobile'])}>
<InputLabel id="simple-select-label">BandWidth</InputLabel>
<Select
value={bandValue}
onChange={e => setBandValue(e.target.value)}
>
{bandWidthList.map(num => <MenuItem value={num} key={num}>{num}</MenuItem>)}
</Select>
</FormControl>
</FormControl> */}

<DeviceSelect deviceType="camera" onChange={value => setCameraID(value)}></DeviceSelect>
<DeviceSelect deviceType="microphone" onChange={value => setMicrophoneID(value)}></DeviceSelect>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ export default function BasicRtc(props) {
try {
const mediaStream = new MediaStream();
mediaStream.addTrack(remoteStreamConfigList[0].stream.getAudioTrack());
mediaStream.addTrack(remoteStreamConfigList[0].stream.getVideoTrack());
mediaRecorder = new MediaRecorder(mediaStream);
} catch (error) {
console.error('Exception while creating MediaRecorder:', error);
Expand Down
6 changes: 4 additions & 2 deletions Web/base-react-next/src/utils/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
* @param {String} phoneNumber
* @param {Number} phoneArea
*/
export function checkPhoneNumber(phoneNumber, phoneArea = 86) {
if (!phoneNumber) return false;
export function checkPhoneNumber(phoneNumber, phoneArea) {
if (!phoneNumber || !phoneArea) {
return false;
}
const reg = /^1[3|4|5|7|8|6|9][0-9]\d{8}$/;

switch (phoneArea) {
Expand Down

0 comments on commit 228c11d

Please sign in to comment.