repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/100_MeetingManagerSignin/MeetingManagerSingin.tsx | import { Button, CircularProgress, Container, createStyles, CssBaseline, makeStyles } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { useAppState } from "../../providers/AppStateProvider";
const lineSpacerHeihgt = 10
export const useStyles = makeStyles((theme) =>
createStyles({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
button:{
width:100
},
buttonList:{
display:"flex",
flexDirection:"column",
alignItems:"center"
},
lineSpacer:{
height:lineSpacerHeihgt,
},
}),
);
type InternalStage = "Signining" | "Joining" | "Entering"
type State = {
internalStage: InternalStage,
userName: string | null
}
export const MeetingManagerSignin = () => {
const classes = useStyles();
//// Query Parameters
const query = new URLSearchParams(window.location.search);
const meetingName = query.get('meetingName') || null // meeting name is already encoded
const attendeeId = query.get('attendeeId') || null
const uuid = query.get('uuid') || null
const { onetimeCodeInfo, handleSinginWithOnetimeCodeRequest, handleSinginWithOnetimeCode, setStage, setMessage, joinMeeting, enterMeeting,
audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting} = useAppState()
const [ isLoading, setIsLoading] = useState(false)
const [state, setState] = useState<State>({internalStage:"Signining", userName:null})
const onetimeCodeClicked = async (code:string) =>{
setIsLoading(true)
////// Signin
const res = await handleSinginWithOnetimeCode(onetimeCodeInfo!.meetingName, onetimeCodeInfo!.attendeeId, onetimeCodeInfo!.uuid, code)
if(res.result){
setState({...state, userName: res.attendeeName||null, internalStage:"Joining"})
}else{
setMessage("Exception", "Signin error", [`can not sigin. please generate code and retry.`] )
setIsLoading(false)
}
}
useEffect(()=>{
if(state.internalStage === "Signining"){
handleSinginWithOnetimeCodeRequest(meetingName!, attendeeId!, uuid!)
}else if(state.internalStage === "Joining" && state.userName){
console.log("joining...")
joinMeeting(onetimeCodeInfo!.meetingName!, state.userName).then(()=>{
setState({...state, internalStage:"Entering"})
}).catch(e=>{
console.log(e)
setMessage("Exception", "Enter Room Failed", [`${e.message}`, `(code: ${e.code})`] )
setIsLoading(false)
})
}else if(state.internalStage === "Entering"){
console.log("entering...")
const p1 = audioInputDeviceSetting!.setAudioInput("dummy")
const p2 = videoInputDeviceSetting!.setVideoInput(null)
// const audioOutput = (audioOutputList && audioOutputList!.length > 0) ? audioOutputList[0].deviceId:null
// const p3 = audioOutputDeviceSetting!.setAudioOutput(audioOutput)
// const audioOutput = (audioOutputList && audioOutputList!.length > 0) ? audioOutputList[0].deviceId:null
const p3 = audioOutputDeviceSetting!.setAudioOutput(null)
enterMeeting().then(()=>{
Promise.all([p1,p2,p3]).then(()=>{
setIsLoading(false)
setStage("MEETING_MANAGER")
})
}).catch(e=>{
setIsLoading(false)
console.log(e)
})
}
},[state.internalStage, state.userName]) // eslint-disable-line
let passwordSelector
if(isLoading){
passwordSelector = <CircularProgress />
}else if(onetimeCodeInfo){
passwordSelector = onetimeCodeInfo.codes.map(x=>{
return (
<div key={x}>
<div>
<Button color="primary" variant="outlined" className={classes.button} key={x} onClick={()=>{onetimeCodeClicked(x)}}>{x}</Button>
</div>
<div className={classes.lineSpacer} />
</div>
)
})
}else{
passwordSelector = <div>now loading</div>
}
return (
<Container maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<div>
Select your code.
</div>
<div className={classes.buttonList}>
{passwordSelector}
</div>
</div>
</Container>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/const.ts | <filename>frontend3/src/pages/023_meetingRoom/components/ScreenView/const.ts<gh_stars>0
export type PictureInPictureType = "None" | "TOP_LEFT" | "TOP_RIGHT" | "BOTTOM_LEFT" | "BOTTOM_RIGHT"
export type FocustTarget = "SharedContent" | "Speaker"
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/022_waitingRoom/WaitingRoom.tsx | <gh_stars>0
import { Avatar, Box, Button, CircularProgress, Container, CssBaseline, FormControl, Grid, InputLabel, Link, makeStyles, MenuItem, Select, Typography } from "@material-ui/core";
import React, { useEffect, useMemo, useState } from "react";
import { useAppState } from "../../providers/AppStateProvider";
import { MeetingRoom } from '@material-ui/icons'
import { Copyright } from "../000_common/Copyright";
import { DeviceInfo } from "../../utils";
import { VirtualBackgroundSegmentationType } from "../../frameProcessors/VirtualBackground";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.primary.main,
},
form: {
width: '100%',
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
formControl: {
margin: theme.spacing(1),
width: '100%'
// minWidth: 120,
},
cameraPreview: {
width: '50%'
},
}));
export const WaitingRoom = () => {
const classes = useStyles()
const { userId, userName, meetingName, audioInputList, videoInputList, audioOutputList,
audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting,
setStage, handleSignOut, reloadDevices, enterMeeting} = useAppState()
const [isLoading, setIsLoading] = useState(false)
//// Default Device ID
const defaultDeiceId = (deviceList: DeviceInfo[] | null) => {
if(!deviceList){
return "None"
}
const defaultDevice = deviceList.find(dev=>{return dev.deviceId !== "default"})
return defaultDevice ? defaultDevice.deviceId : "None"
}
const defaultAudioInputDevice = defaultDeiceId(audioInputList)
const defaultVideoInputDevice = defaultDeiceId(videoInputList)
const defaultAudioOutputDevice = defaultDeiceId(audioOutputList)
const [audioInputDeviceId, setAudioInputDeviceId] = useState(defaultAudioInputDevice)
const [videoInputDeviceId, setVideoInputDeviceId] = useState(defaultVideoInputDevice)
const [audioOutputDeviceId, setAudioOutputDeviceId] = useState(defaultAudioOutputDevice)
const [segmentationType, setSegmentationType] = useState<VirtualBackgroundSegmentationType>("GoogleMeetTFLite")
const onReloadDeviceClicked = () =>{
reloadDevices()
}
const onEnterClicked = () => {
setIsLoading(true)
enterMeeting().then(()=>{
setIsLoading(false)
videoInputDeviceSetting!.startLocalVideoTile()
setStage("MEETING_ROOM")
}).catch(e=>{
setIsLoading(false)
console.log(e)
})
}
useEffect(() => {
const videoEl = document.getElementById("camera-preview") as HTMLVideoElement
videoInputDeviceSetting!.setPreviewVideoElement(videoEl)
},[])// eslint-disable-line
useEffect(() => {
if (videoInputDeviceId === "None") {
videoInputDeviceSetting!.setVideoInput(null).then(()=>{
videoInputDeviceSetting!.stopPreview()
})
} else if (videoInputDeviceId=== "File") {
// fileInputRef.current!.click()
} else {
videoInputDeviceSetting!.setVideoInput(videoInputDeviceId).then(()=>{
videoInputDeviceSetting!.startPreview()
})
}
},[videoInputDeviceId]) // eslint-disable-line
useEffect(()=>{
if (segmentationType === "None") {
videoInputDeviceSetting!.setVirtualBackgroundSegmentationType("None").then(()=>{
})
} else {
videoInputDeviceSetting!.setVirtualBackgroundSegmentationType(segmentationType).then(()=>{
})
}
},[segmentationType]) // eslint-disable-line
useEffect(()=>{
if (audioInputDeviceId === "None") {
audioInputDeviceSetting!.setAudioInput(null)
} else {
audioInputDeviceSetting!.setAudioInput(audioInputDeviceId)
}
},[audioInputDeviceId]) // eslint-disable-line
useEffect(()=>{
if (audioOutputDeviceId === "None") {
audioOutputDeviceSetting!.setAudioOutput(null)
} else {
audioOutputDeviceSetting!.setAudioOutput(audioOutputDeviceId)
}
},[audioOutputDeviceId]) // eslint-disable-line
const videoPreview = useMemo(()=>{
return (<video id="camera-preview" className={classes.cameraPreview} />)
},[])// eslint-disable-line
return (
<Container maxWidth="xs" >
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<MeetingRoom />
</Avatar>
<Typography variant="h4">
Waiting Meeting
</Typography>
<Typography>
You will join room <br />
(user:{userName}, room:{meetingName}) <br />
Setup your devices.
</Typography>
<form className={classes.form} noValidate>
<Button
fullWidth
variant="outlined"
color="primary"
onClick={onReloadDeviceClicked}
>
reload device list
</Button>
<FormControl className={classes.formControl} >
<InputLabel>Camera</InputLabel>
<Select onChange={(e)=>{setVideoInputDeviceId(e.target.value! as string)}} defaultValue={videoInputDeviceId}>
<MenuItem disabled value="Video">
<em>Video</em>
</MenuItem>
{videoInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<Typography>
Preview.(virtual bg is not applied here yet.)
</Typography>
{videoPreview}
<FormControl className={classes.formControl} >
<InputLabel>VirtualBG</InputLabel>
<Select onChange={(e)=>{setSegmentationType(e.target.value! as VirtualBackgroundSegmentationType)}} defaultValue={segmentationType}>
<MenuItem disabled value="Video">
<em>VirtualBG</em>
</MenuItem>
<MenuItem value="None">
<em>None</em>
</MenuItem>
<MenuItem value="BodyPix">
<em>BodyPix</em>
</MenuItem>
<MenuItem value="GoogleMeet">
<em>GoogleMeet</em>
</MenuItem>
<MenuItem value="GoogleMeetTFLite">
<em>GoogleMeetTFLite</em>
</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Microhpone</InputLabel>
<Select onChange={(e)=>{setAudioInputDeviceId(e.target.value! as string)}} defaultValue={audioInputDeviceId}>
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{audioInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Speaker</InputLabel>
<Select onChange={(e)=>{setAudioOutputDeviceId(e.target.value! as string)}} defaultValue={audioOutputDeviceId}>
<MenuItem disabled value="Video">
<em>Speaker</em>
</MenuItem>
{audioOutputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId} >{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<Grid container direction="column" alignItems="center" >
{
isLoading ?
<CircularProgress />
:
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onEnterClicked}
id="submit"
>
Enter
</Button>
}
</Grid>
<Grid container direction="column" >
<Grid item xs>
<Link onClick={(e: any) => { setStage("ENTRANCE") }}>
Go Back
</Link>
</Grid>
<Grid item xs>
<Link onClick={(e: any) => { handleSignOut(userId!); setStage("SIGNIN") }}>
Sign out
</Link>
</Grid>
</Grid>
<Box mt={8}>
<Copyright />
</Box>
</form>
</div>
</Container>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useDeviceState.ts | import { useState} from 'react';
import { DeviceInfoList, getDeviceLists } from '../../utils';
export const useDeviceState = () =>{
const [deviceList, setDeviceList] = useState<DeviceInfoList|null>(null)
if (!deviceList) {
getDeviceLists().then(res => {
addtionalDevice(res)
setDeviceList(res)
})
}
const reloadDevices = () =>{
getDeviceLists().then(res => {
addtionalDevice(res)
setDeviceList(res)
})
}
const addtionalDevice = (l:DeviceInfoList) =>{
if(l){
l.audioinput?.push({
deviceId:"None",
groupId:"None",
kind:"audioinput",
label:"None"
})
l.videoinput?.push({
deviceId:"None",
groupId:"None",
kind:"videoinput",
label:"None"
})
l.audiooutput?.push({
deviceId:"None",
groupId:"None",
kind:"audiooutput",
label:"None"
})
}
}
return {
audioInputList: deviceList ? deviceList['audioinput'] : null,
videoInputList: deviceList ? deviceList['videoinput'] : null,
audioOutputList: deviceList ? deviceList['audiooutput'] : null,
reloadDevices
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/LineView.tsx | <gh_stars>0
import { useMemo } from "react";
import { useAppState } from "../../../../providers/AppStateProvider";
import { DrawableVideoTile } from "./DrawableVideoTile";
type Props = {
excludeSpeaker: boolean
excludeSharedContent: boolean
width:number
height:number
viewInLine: number
};
export const LineView = ({ excludeSpeaker, excludeSharedContent, width, height, viewInLine}: Props) => {
const { attendees, videoTileStates, activeSpeakerId, getUserNameByAttendeeIdFromList } = useAppState()
let targetTiles = Object.values(videoTileStates).filter(tile =>{
if(!attendees[tile.boundAttendeeId!]){
return true
}
return attendees[tile.boundAttendeeId!].isVideoPaused === false
})
if(excludeSharedContent){
targetTiles = targetTiles.filter(tile =>{return tile.isContent !== true})
}
if(excludeSpeaker){
targetTiles = targetTiles.filter(tile =>{return tile.boundAttendeeId !== activeSpeakerId})
}
// rendering flag
const targetIds = targetTiles.reduce<string>((ids,cur)=>{return `${ids}_${cur.boundAttendeeId}`},"")
const targetNames = targetTiles.reduce<string>((names,cur)=>{return `${names}_${getUserNameByAttendeeIdFromList(cur.boundAttendeeId!)}`},"")
const view = useMemo(()=>{
console.log("[LineView] Rendering")
return (
<div style={{display:"flex", flexWrap:"wrap", width:`${width}px`, height:`${height}px`, overflowX:"auto" }}>
{targetTiles?.map((tile, i) => {
const idPrefix = `drawable-videotile-${tile.boundAttendeeId}`
return (
<div key={`line-view-${i}`} style={{height:height-2, margin:"1px", flex:"0 0 auto", position:"relative"}} >
<DrawableVideoTile key={idPrefix} idPrefix={idPrefix} idSuffix="LineView" tile={tile} width={width/viewInLine} height={height}/>
<div style={{position:"absolute", lineHeight:1, fontSize:14, height:15, top:height-20, left:5, background:tile.boundAttendeeId === activeSpeakerId?"#ee<PASSWORD>":"#777777cc"}}>
{getUserNameByAttendeeIdFromList(tile.boundAttendeeId?tile.boundAttendeeId:"")}
</div>
</div>
)
})}
</div>
)
}, [targetIds, targetNames]) // eslint-disable-line
return (
<>
{view}
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/App.tsx | <reponame>diitalk/flect-chime-sdk-demo<filename>frontend3/src/App.tsx
import React, { useMemo } from 'react';
import './App.css';
import { MessageDialog } from './pages/000_common/MessageDialg';
import { SignIn } from './pages/010_signin';
import { SignUp } from './pages/011_signup';
import { Verify } from './pages/012_verify';
import { RequestChangePassword } from './pages/013_requestChangePassword';
import { NewPassword } from './pages/014_newPassword';
import { Entrance } from './pages/020_entrance';
import { CreateMeetingRoom } from './pages/021_createMeetingRoom';
import { WaitingRoom } from './pages/022_waitingRoom/WaitingRoom';
import { WaitingRoomAmongUs } from './pages/022_waitingRoom/WaitingRoomAmongUs';
import { MeetingRoom } from './pages/023_meetingRoom/MeetingRoom';
import { MeetingRoomAmongUs } from './pages/024_meetingRoomAmongUs/MeetingRoomAmongUs';
import { MeetingManagerSignin } from './pages/100_MeetingManagerSignin/MeetingManagerSingin';
import { MeetingManager } from './pages/101_MeetingManager/MeetingManager';
import { HeadlessMeetingManager } from './pages/200_HeadlessMeetingManager/HeadlessMeetingManager';
import { AppStateProvider, useAppState } from './providers/AppStateProvider';
const Router = () => {
const { stage, mode } = useAppState()
console.log(`[App] stage:${stage}`)
const page = useMemo(()=>{
switch(stage){
case "SIGNIN":
return <SignIn />
case "SIGNUP":
return <SignUp />
case "VERIFY":
return <Verify />
case "REQUEST_NEW_PASSWORD":
return <RequestChangePassword />
case "NEW_PASSWORD":
return <NewPassword />
case "ENTRANCE":
return <Entrance />
case "CREATE_MEETING_ROOM":
return <CreateMeetingRoom />
case "WAITING_ROOM":
if(mode === "amongus"){
return <WaitingRoomAmongUs />
}else{
return <WaitingRoom />
}
case "MEETING_ROOM":
if(mode === "amongus"){
return <MeetingRoomAmongUs />
}else {
return <MeetingRoom />
}
case "MEETING_MANAGER_SIGNIN":
return <MeetingManagerSignin />
case "MEETING_MANAGER":
return <MeetingManager />
case "HEADLESS_MEETING_MANAGER":
return <HeadlessMeetingManager />
default:
return <div>no view</div>
}
},[stage, mode])
return (
<div >
{page}
</div>
)
}
const App = () => {
return (
<div >
<AppStateProvider>
<Router />
<MessageDialog />
</AppStateProvider>
</div>
);
}
export default App;
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useMessageState.ts | import { useState } from "react"
export type MessageType = "None" | "Info" | "Exception"
type MessageState = {
messageActive: boolean,
messageType: MessageType,
messageTitle: string,
messageDetail: string[],
}
export const useMessageState = () =>{
const [state, setState] = useState<MessageState>({
messageActive:false,
messageType:"None",
messageTitle:"",
messageDetail:[],
})
const resolveMessage = () =>{
setState({...state, messageActive:false, messageType:"None", messageTitle:"", messageDetail:[]})
}
const setMessage = (type:MessageType, title:string, detail:string[]) => {
setState({...state, messageActive:true, messageType:type, messageTitle:title, messageDetail:detail})
}
return {...state, resolveMessage, setMessage}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/components/ChatArea.tsx | import React, { useMemo, useState } from 'react';
import { Button, makeStyles, TextField, withStyles } from '@material-ui/core';
import { useAppState } from '../../../providers/AppStateProvider';
import { blueGrey } from '@material-ui/core/colors';
const useStyles = makeStyles((theme) => ({
input_amongus: {
color: blueGrey[400],
},
message:{
width: "100%",
textAlign: 'left',
wordWrap: "break-word",
whiteSpace: "normal",
color:blueGrey[100]
},
sendButton:{
textAlign: 'right',
},
}));
const CustomTextField = withStyles({
root: {
'& input:valid + fieldset': {
borderColor: blueGrey[100],
borderWidth: 1,
},
'& input:invalid + fieldset': {
borderColor: blueGrey[100],
borderWidth: 1,
},
'& input:valid:focus + fieldset': {
borderColor: blueGrey[100],
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:valid:hover + fieldset': {
borderColor: blueGrey[100],
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:invalid:hover + fieldset': {
borderColor: blueGrey[100],
borderLeftWidth: 6,
color: blueGrey[300]
// padding: '4px !important',
},
'& label.Mui-focused': {
color: blueGrey[100],
},
'& label.MuiInputLabel-root': {
color: blueGrey[100],
},
},
})(TextField);
export const ChatArea = () => {
const classes = useStyles()
const { chatData, sendChatData, getUserNameByAttendeeIdFromList } = useAppState()
const [message, setMessage] = useState("")
const sendMessage = () => {
setMessage("")
sendChatData(message)
}
const messageList = useMemo(()=>{
const messages = chatData.slice(-8).map(x=>{
const name = getUserNameByAttendeeIdFromList(x.senderId)
// const date = new Date(x.createdDate).toLocaleTimeString()
const mess = (x.data as string).split("\n").map(l =>{return <>{l}</>})
return(
<div style={{display:"flex", flexDirection:"column"}}>
<div style={{color:blueGrey[300]}}>
{name}
</div>
<div className={classes.message} style={{marginLeft:"5px"}}>
{mess}
</div>
</div>
)
})
return(
<>
{messages}
</>
)
},[chatData]) // eslint-disable-line
return (
<>
<div style={{color:"burlywood"}}>
Message...
</div>
<div style={{marginLeft:"15pt"}}>
<div>
{messageList}
<div>
<CustomTextField
required
variant="outlined"
margin="normal"
fullWidth
label=""
autoComplete="email"
autoFocus
value={message}
onChange={(e) => setMessage(e.target.value)}
InputProps={{
className: classes.input_amongus,
}}
onKeyPress={e => {
if (e.key === 'Enter') {
sendMessage()
}
}}
/>
</div>
<div>
<Button variant="outlined" color="primary" size="small" onClick={sendMessage}>
send
</Button>
</div>
</div>
</div>
</>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useS3FileUploader.ts | import { useEffect, useState } from "react"
import { getPresignedURL } from "../../api/api"
import * as AWS from "aws-sdk";
const bucketName = "f-backendstack-dev-bucket"
const s3 = new AWS.S3({ params: { Bucket: bucketName } });
type UseS3FileUploader = {
idToken?: string,
accessToken?: string,
refreshToken?: string
}
export const useS3FileUploader = (props:UseS3FileUploader) =>{
// const uploadFileToS3 = async (key:string, data: Uint8Array) => {
// const postInfo = await getPresignedURL(key, props.idToken!, props.accessToken!, props.refreshToken!)
// console.log(`[getPresignedURLFromServer] ${postInfo.result}`)
// console.log(`[getPresignedURLFromServer] ${postInfo.url}`)
// console.log(`[getPresignedURLFromServer] ${postInfo.fields}`)
// const multiPartParams = postInfo.fields.ContentType ? postInfo.fields : {ContentType : "video/mp4" , ...postInfo.fields};
// const multiPartUploadResult = await s3.createMultipartUpload(multiPartParams).promise();
// // const formData = new FormData();
// // formData.append("Content-Type", "video/mp4");
// // Object.entries(postInfo.fields).forEach(([k, v]) => {
// // formData.append(k, v);
// // });
// // formData.append("file", file);
// }
// return {uploadFileToS3}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/components/dialog/SettingDialog.tsx | <reponame>diitalk/flect-chime-sdk-demo<filename>frontend3/src/pages/024_meetingRoomAmongUs/components/dialog/SettingDialog.tsx
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControl, InputLabel, MenuItem, Select, Switch, Typography } from "@material-ui/core"
import React, { useState } from "react"
import { useAppState } from "../../../../providers/AppStateProvider"
import { useStyles } from "../../css"
import { ViewMode } from "../../MeetingRoomAmongUs"
type SettingDialogProps={
open:boolean,
onClose:()=>void
viewMode:ViewMode
setViewMode:(mode:ViewMode) => void
debugEnable:boolean
setDebugEnable:(mode:boolean) => void
screenSize:number[]
setScreenSize:(size:number[])=>void
}
const ScreenSize:{[key:string]:number[]} = {
"640x480":[640,480],
"320x240":[320,240],
"160x120":[160,120],
"64x48":[64,48]
}
export const SettingDialog = (props:SettingDialogProps) =>{
const classes = useStyles()
const {audioInputDeviceSetting, audioOutputDeviceSetting, audioInputList, audioOutputList,
} = useAppState()
const [guiCounter, setGuiCounter] = useState(0)
const onInputAudioChange = async (e: any) => {
//// for input movie experiment [start]
const videoElem = document.getElementById("for-input-movie")! as HTMLVideoElement
videoElem.pause()
videoElem.srcObject=null
videoElem.src=""
//// for input movie experiment [end]
if (e.target.value === "None") {
await audioInputDeviceSetting!.setAudioInput(null)
setGuiCounter(guiCounter+1)
} else {
await audioInputDeviceSetting!.setAudioInput(e.target.value)
setGuiCounter(guiCounter+1)
}
}
const onSuppressionChange = async (e:any) =>{
if (e.target.value === "None") {
await audioInputDeviceSetting!.setAudioSuppressionEnable(false)
setGuiCounter(guiCounter+1)
} else {
await audioInputDeviceSetting!.setAudioSuppressionEnable(true)
await audioInputDeviceSetting!.setVoiceFocusSpec({variant:e.target.value})
setGuiCounter(guiCounter+1)
}
}
const onOutputAudioChange = async (e: any) => {
if (e.target.value === "None") {
await audioOutputDeviceSetting!.setAudioOutput(null)
setGuiCounter(guiCounter+1)
} else {
await audioOutputDeviceSetting!.setAudioOutput(e.target.value)
setGuiCounter(guiCounter+1)
}
}
const onViewModeChanged = async (e:any) =>{
props.setViewMode(e.target.value)
}
const onDebugEnableChanged = (event: React.ChangeEvent<HTMLInputElement>) => {
props.setDebugEnable(event.target.checked )
};
const onScreenSizeChanged = (e:any) => {
const size = ScreenSize[e.target.value as string]
props.setScreenSize(size)
}
return(
<div>
<Dialog disableBackdropClick disableEscapeKeyDown scroll="paper" open={props.open} onClose={props.onClose} >
<DialogTitle>
<Typography gutterBottom>
Settings
</Typography>
</DialogTitle>
<DialogContent>
<Typography variant="h5" gutterBottom>
Devices and Effects
</Typography>
{/* <form className={classes.form} noValidate> */}
<form noValidate>
<FormControl className={classes.formControl} >
<InputLabel>Microhpone</InputLabel>
<Select onChange={onInputAudioChange} value={audioInputDeviceSetting!.audioInput} >
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{audioInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Noise Suppression</InputLabel>
<Select onChange={onSuppressionChange} value={audioInputDeviceSetting!.audioSuppressionEnable ? audioInputDeviceSetting!.voiceFocusSpec?.variant: "None" } >
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{["None", "auto", "c100", "c50", "c20", "c10"].map(val => {
return <MenuItem value={val} key={val}>{val}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Speaker</InputLabel>
<Select onChange={onOutputAudioChange} value={audioOutputDeviceSetting!.audioOutput} >
<MenuItem disabled value="Video">
<em>Speaker</em>
</MenuItem>
{audioOutputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId} >{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<Divider />
<Typography variant="h5" gutterBottom>
Experimental
</Typography>
<FormControl className={classes.formControl} >
<InputLabel>View Mode</InputLabel>
<Select onChange={onViewModeChanged} value={props.viewMode} >
{["MultiTileView", "SeparateView"].map(val => {
return <MenuItem value={val} key={val}>{val}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>debug</InputLabel>
<Switch
checked={props.debugEnable}
onChange={onDebugEnableChanged}
inputProps={{ 'aria-label': 'secondary checkbox' }}
/>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>canvas size</InputLabel>
<Select onChange={onScreenSizeChanged} value={`${props.screenSize[0]}x${props.screenSize[1]}`} >
{Object.keys(ScreenSize).map(val => {
return <MenuItem value={val} key={val}>{val}</MenuItem>
})}
</Select>
</FormControl>
</form>
</DialogContent>
<DialogActions>
<Button onClick={props.onClose} color="primary">
Ok
</Button>
</DialogActions>
</Dialog>
<video id="for-input-movie" loop hidden />
</div>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/200_HeadlessMeetingManager/hooks/useRecorder.ts | import { DefaultDeviceController } from "amazon-chime-sdk-js"
import { useEffect, useMemo, useState } from "react"
import { useAppState } from "../../../providers/AppStateProvider"
import { Recorder } from "../../../providers/helper/Recorder"
import { getDateString } from "../../../utils"
type UseRecorderProps = {
meetingName : string
}
const framerate = 8
export const useRecorder = (props:UseRecorderProps) =>{
const decodedMeetingName = decodeURIComponent(props.meetingName!)
const { startRecordingCounter, stopRecordingCounter, audioInputDeviceSetting } = useAppState()
const [ activeCanvas, setActiveCanvas ] = useState<HTMLCanvasElement>()
const [ allCanvas, setAllCanvas ] = useState<HTMLCanvasElement>()
const activeRecorder = useMemo(()=>{return new Recorder()},[])
const allRecorder = useMemo(()=>{return new Recorder()},[])
const [ isRecording, setIsRecording] = useState(false)
const startRecordInternal = async (recorder:Recorder, srcCanvas:HTMLCanvasElement) => {
const audioElem = document.getElementById("for-speaker") as HTMLAudioElement
const stream = new MediaStream();
// @ts-ignore
const audioStream = audioElem.captureStream() as MediaStream
let localAudioStream = audioInputDeviceSetting?.audioInputForRecord
if(typeof localAudioStream === "string"){
localAudioStream = await navigator.mediaDevices.getUserMedia({audio:{deviceId:localAudioStream}})
}
const audioContext = DefaultDeviceController.getAudioContext();
const outputNode = audioContext.createMediaStreamDestination();
const sourceNode1 = audioContext.createMediaStreamSource(audioStream);
sourceNode1.connect(outputNode)
if(localAudioStream){
const sourceNode2 = audioContext.createMediaStreamSource(localAudioStream as MediaStream);
sourceNode2.connect(outputNode)
}
// @ts-ignore
const videoStream = srcCanvas.captureStream(framerate) as MediaStream
[outputNode.stream, videoStream].forEach(s=>{
s?.getTracks().forEach(t=>{
stream.addTrack(t)
})
});
recorder.startRecording(stream)
}
const startRecord = async () =>{
if(!activeCanvas || !allCanvas){
console.log("START RECORDER::: failed! canvas is null", activeCanvas, allCanvas)
return
}
if(isRecording){
console.log("START RECORDER::: failed! already recording")
return
}
startRecordInternal(activeRecorder, activeCanvas!)
startRecordInternal(allRecorder, allCanvas!)
setIsRecording(true)
return
}
const stopRecord = async () =>{
if(!isRecording){
console.log("STOP RECORDER::: failed! recording is not started")
return
}
activeRecorder?.stopRecording()
allRecorder?.stopRecording()
const dateString = getDateString()
await activeRecorder?.toMp4(`${dateString}_${decodedMeetingName}_active.mp4`)
await allRecorder?.toMp4(`${dateString}_${decodedMeetingName}_all.mp4`)
setIsRecording(false)
const event = new CustomEvent('uploadVideo');
document.dispatchEvent(event)
console.log("[useRecorder] stopRecording event fired")
}
useEffect(()=>{
console.log("START RECORDER:::", startRecordingCounter, stopRecordingCounter)
startRecord()
},[startRecordingCounter]) // eslint-disable-line
useEffect(()=>{
console.log("STOP RECORDER:FROM COUNTER!::", startRecordingCounter, stopRecordingCounter)
console.log("STOP RECORDER:::", startRecordingCounter, stopRecordingCounter)
stopRecord()
},[stopRecordingCounter]) // eslint-disable-line
return {isRecording, setActiveCanvas, setAllCanvas, stopRecord}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/MeetingRoomAmongUs.tsx | import React, { useEffect, useMemo, useRef, useState } from "react"
import { Tooltip, IconButton, Divider, FormControl, InputLabel, Select, MenuItem } from '@material-ui/core'
import { useAppState } from "../../providers/AppStateProvider";
import EmojiPeopleIcon from '@material-ui/icons/EmojiPeople';
import { blueGrey, red } from '@material-ui/core/colors';
import CameraRollIcon from '@material-ui/icons/CameraRoll';
import SportsEsportsIcon from '@material-ui/icons/SportsEsports';
import { useStyles } from "./css";
import { ICONS_ALIVE, ICONS_DEAD, REGIONS, STATES } from "../../providers/hooks/RealtimeSubscribers/useAmongUs";
import MicIcon from '@material-ui/icons/Mic';
import VolumeUpIcon from '@material-ui/icons/VolumeUp';
import ScreenShareIcon from '@material-ui/icons/ScreenShare';
import ViewComfyIcon from '@material-ui/icons/ViewComfy';
import SettingsIcon from '@material-ui/icons/Settings';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import { LeaveMeetingDialog } from "./components/dialog/LeaveMeetingDialog";
import { SettingDialog } from "./components/dialog/SettingDialog";
import { AudienceList } from "./components/AudienceList";
import { CreditPanel } from "./components/CreditPanel";
import { ChatArea } from "./components/ChatArea";
import { useScheduler } from "../../providers/hooks/useScheduler";
type ChimeState = {
arenaMicrophone:boolean
arenaSpeaker:boolean
arenaShareScreen:boolean
arenaViewScreen:boolean
fieldMicrophone:boolean
fieldSpeaker:boolean
}
///// Multi channel (N/A)
// const ChimeState_Arena:ChimeState = {
// arenaMicrophone:true,
// arenaSpeaker:true,
// arenaShareScreen:false,
// arenaViewScreen:true,
// fieldMicrophone:false,
// fieldSpeaker:false,
// }
// const ChimeState_Lobby:ChimeState = {
// arenaMicrophone:true,
// arenaSpeaker:true,
// arenaShareScreen:true,
// arenaViewScreen:true,
// fieldMicrophone:false,
// fieldSpeaker:false,
// }
// const ChimeState_Task:ChimeState = {
// arenaMicrophone:false,
// arenaSpeaker:false,
// arenaShareScreen:true,
// arenaViewScreen:false,
// fieldMicrophone:false,
// fieldSpeaker:false,
// }
// const ChimeState_Discuss:ChimeState = {
// arenaMicrophone:true,
// arenaSpeaker:false,
// arenaShareScreen:true,
// arenaViewScreen:false,
// fieldMicrophone:true,
// fieldSpeaker:true,
// }
// const ChimeState_Dead:ChimeState = {
// arenaMicrophone:true,
// arenaSpeaker:true,
// arenaShareScreen:true,
// arenaViewScreen:true,
// fieldMicrophone:false,
// fieldSpeaker:false,
// }
//// Single Channel
const ChimeState_Arena:ChimeState = {
arenaMicrophone:true,
arenaSpeaker:true,
arenaShareScreen:false,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Lobby:ChimeState = {
arenaMicrophone:true,
arenaSpeaker:true,
arenaShareScreen:true,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Task:ChimeState = {
arenaMicrophone:false,
arenaSpeaker:false,
arenaShareScreen:true,
arenaViewScreen:false,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Discuss:ChimeState = {
arenaMicrophone:true,
arenaSpeaker:true,
arenaShareScreen:true,
arenaViewScreen:false,
fieldMicrophone:true,
fieldSpeaker:true,
}
const ChimeState_Task_Dead:ChimeState = {
arenaMicrophone:true,
arenaSpeaker:true,
arenaShareScreen:true,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Discuss_Dead:ChimeState = {
arenaMicrophone:false,
arenaSpeaker:true,
arenaShareScreen:true,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Discuss_Arena:ChimeState = {
arenaMicrophone:false,
arenaSpeaker:true,
arenaShareScreen:false,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeState_Debug:ChimeState = {
arenaMicrophone:true,
arenaSpeaker:true,
arenaShareScreen:true,
arenaViewScreen:true,
fieldMicrophone:false,
fieldSpeaker:false,
}
const ChimeStateType = {
"Arena" : ChimeState_Arena,
"Lobby" : ChimeState_Lobby,
"Task" : ChimeState_Task,
"Discuss" : ChimeState_Discuss,
"Task_Dead" : ChimeState_Task_Dead,
"Discuss_Dead" : ChimeState_Discuss_Dead,
"Discuss_Arena" : ChimeState_Discuss_Arena,
"Debug" :ChimeState_Debug,
}
const mapFileNames = [
'map00_Skeld.png',
'map01_Mira.png',
'map02_Polus.png',
'map03_dlekS.png',
'map04_Airship.png',
]
export type ViewMode = "MultiTileView" | "SeparateView"
export const MeetingRoomAmongUs = () => {
const classes = useStyles();
const animationRef = useRef(0);
const {meetingSession, attendeeId, videoTileStates, videoInputDeviceSetting, audioInputDeviceSetting, audioOutputDeviceSetting,
isOwner, publicIp,
startHMM, sendTerminate, sendStartRecord, sendStopRecord, sendStartShareTileView, sendStopShareTileView, hMMStatus, stateLastUpdate,
currentGameState, sendRegisterAmongUsUserName, updateHMMInfo
} = useAppState()
const [settingDialogOpen, setSettingDialogOpen] = useState(false);
const [leaveDialogOpen, setLeaveDialogOpen] = useState(false);
const [chimeState, setChimeState] = useState<ChimeState>(ChimeStateType.Arena)
const [userName, _setUserName] = useState<string>()
const [ captureStream, setCaptureStream ] = useState<MediaStream>()
const { tenSecondsTaskTrigger } = useScheduler()
const setUserName = (newUserName:string) =>{
_setUserName(newUserName)
}
const [ viewMode, setViewMode ] = useState<ViewMode>("MultiTileView")
const [ debugEnable, setDebugEnable] = useState(false)
const [ screenSize, setScreenSize] = useState<number[]>([640,480])
const targetTilesId = Object.keys(videoTileStates).reduce<string>((sum,cur)=>{return `${sum}-${cur}`},"")
useEffect(()=>{
console.log("UPDATE HMM INFO")
updateHMMInfo()
}, [tenSecondsTaskTrigger])
// initialize auido/video output
useEffect(()=>{
const audioEl = document.getElementById("arena_speaker") as HTMLAudioElement
audioOutputDeviceSetting!.setOutputAudioElement(audioEl)
// const canvasEl = document.getElementById("captureCanvas") as HTMLCanvasElement
// @ts-ignore
// const stream = canvasEl.captureStream() as MediaStream
// videoInputDeviceSetting?.setVideoInput(stream)
// @ts-ignore
document.body.style = 'background: black;';
// /// tmp
// meetingSession?.deviceController.listAudioOutputDevices().then(res=>{
// const devs = res.map(x=>{return x.deviceId})
// const d = document.getElementById("info1") as HTMLDivElement
// d.innerText = devs.reduce((prev,cur)=>{ return `${prev}_${cur}`}, "")
// })
},[]) // eslint-disable-line
// /// fit screen
// useEffect(()=>{
// const header = document.getElementById("header") as HTMLDivElement
// const main = document.getElementById("main") as HTMLDivElement
// const cs = getComputedStyle(main)
// const headerWidth = cs.getPropertyValue("width")
// const headerHeight = cs.getPropertyValue("height")
// // console.log(`---------------- ${headerWidth}, ${headerHeight}`)
// // main.style.height = `${screenHeight - parseInt(headerWidth)}`
// },[screenWidth, screenHeight])
const animate = () => {
const videoEl = document.getElementById("capture") as HTMLVideoElement
const canvasEl = document.getElementById("captureCanvas") as HTMLCanvasElement
const ctx = canvasEl.getContext("2d")!
ctx.drawImage(videoEl, 0, 0, canvasEl.width, canvasEl.height)
animationRef.current = requestAnimationFrame(animate)
};
useEffect(() => {
animationRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(animationRef.current);
}, []) // eslint-disable-line
useEffect(()=>{
// if(!currentGameState.hmmAttendeeId){
// return
// }
if(chimeState.arenaViewScreen){
// hide map
const mapViewComp = document.getElementById("mapView") as HTMLImageElement
mapViewComp.style.display = "none"
const tileviewComp = document.getElementById("tileView") as HTMLVideoElement
tileviewComp.style.display = "block"
meetingSession?.audioVideo.getAllRemoteVideoTiles().forEach((x, index)=>{
if(viewMode==="MultiTileView"){
if(x.state().boundAttendeeId === currentGameState.hmmAttendeeId){
x.unpause()
x.bindVideoElement(tileviewComp)
tileviewComp.play()
console.log("video stream:", tileviewComp.videoWidth, tileviewComp.videoHeight)
}else{
x.pause()
x.bindVideoElement(null)
}
}else{ // SeparateView
const userViewComp = document.getElementById(`userView${index}`) as HTMLVideoElement
x.bindVideoElement(userViewComp)
console.log("video stream:", userViewComp.videoWidth, userViewComp.videoHeight)
userViewComp.play()
if(x.state().boundAttendeeId === currentGameState.hmmAttendeeId){
x.pause()
x.bindVideoElement(null)
}else{
x.unpause()
x.bindVideoElement(userViewComp)
}
}
})
}else{
// show map
const mapViewComp = document.getElementById("mapView") as HTMLImageElement
mapViewComp.style.display = "block"
mapViewComp.src=`/resources/amongus/map/${mapFileNames[currentGameState.map]}`
const tileviewComp = document.getElementById("tileView") as HTMLVideoElement
tileviewComp.style.display = "none"
meetingSession?.audioVideo.getAllRemoteVideoTiles().forEach((x, index)=>{
x.pause()
})
}
},[targetTilesId, currentGameState.hmmAttendeeId, chimeState.arenaViewScreen]) // eslint-disable-line
//// UserName Change
useEffect(()=>{
if(!userName){
return
}
sendRegisterAmongUsUserName(userName, attendeeId!)
},[userName]) // eslint-disable-line
//// Chime State change
useEffect(()=>{
const player = currentGameState.players.find(x=>{return x.attendeeId === attendeeId})
console.log("Find current player:::", player)
console.log("Find current player:::", currentGameState)
console.log("Find current player::GAME STATE:", currentGameState.state)
if(debugEnable){
setChimeState(ChimeStateType.Debug)
return
}
/////// For Arena
if(!player){
// in arena
console.log("Find current player::: 1")
if(currentGameState.state == 2){
setChimeState(ChimeStateType.Discuss_Arena)
return
}else{
setChimeState(ChimeStateType.Arena)
return
}
}
/////// For Field
/// Lobby
if(currentGameState.state == 0){
// in lobby(0)
console.log("Find current player::: 2")
setChimeState(ChimeStateType.Lobby)
return
}
//// Task
if(currentGameState.state == 1){
console.log("Find current player::: 3-1")
// in task
if(player.isDead || player.disconnected){
console.log("Find current player::: 3")
// dead man
setChimeState(ChimeStateType.Task_Dead)
return
}else{
// task
console.log("Find current player::: 4")
setChimeState(ChimeStateType.Task)
return
}
}
//// Discuss
if(currentGameState.state == 2){
//in discussing
if(player.isDead || player.disconnected){
// dead man
console.log("Find current player::: 5")
setChimeState(ChimeStateType.Discuss_Dead)
return
}else{
// discuss
console.log("Find current player::: 6")
setChimeState(ChimeStateType.Discuss)
return
}
}
console.log("Find current player::: 7")
},[currentGameState, debugEnable]) // eslint-disable-line
//// AV Controle
useEffect(()=>{
if(chimeState.arenaMicrophone){
audioInputDeviceSetting!.unmute()
}else{
audioInputDeviceSetting!.mute()
}
},[chimeState.arenaMicrophone]) // eslint-disable-line
useEffect(()=>{
if(chimeState.arenaSpeaker){
audioOutputDeviceSetting?.setAudioOutputEnable(true)
}else{
audioOutputDeviceSetting?.setAudioOutputEnable(false)
}
},[chimeState.arenaSpeaker]) // eslint-disable-line
useEffect(()=>{
if(chimeState.arenaShareScreen){
console.log("ENABLE VIDEO: TRUE")
//////// captureStream can not be kept between sharedDisplay enable and disable. (captureStream changed to default webcam, severe issue)
// if(captureStream){
// videoInputDeviceSetting!.setVideoInput(captureStream).then(()=>{
// videoInputDeviceSetting!.startLocalVideoTile()
// })
// }
// const videoEl = document.getElementById("capture") as HTMLVideoElement
// // @ts-ignore
// const stream = videoEl.captureStream() as MediaStream
// videoInputDeviceSetting!.setVideoInput(stream).then(()=>{
// videoInputDeviceSetting!.startLocalVideoTile()
// })
const canvasEl = document.getElementById("captureCanvas") as HTMLCanvasElement
// @ts-ignore
const stream = canvasEl.captureStream() as MediaStream
videoInputDeviceSetting!.setVideoInput(stream).then(()=>{
videoInputDeviceSetting!.startLocalVideoTile()
})
}else{
console.log("ENABLE VIDEO: FALSE")
videoInputDeviceSetting!.stopLocalVideoTile()
}
},[chimeState.arenaShareScreen]) // eslint-disable-line
//// UserName re-register
useEffect(()=>{
const player = currentGameState.players.find(x=>{return x.name === userName})
if(!player){
// no register target name
return
}
if(player.attendeeId){
if(player.attendeeId === attendeeId){
// already registerd
return
}else{
// register other person at the same name. clear my name.
setUserName("__None__")
return
}
}
if(!player.attendeeId && userName){
// not registerd yet and userName is choosen. register
sendRegisterAmongUsUserName(userName, attendeeId!)
}
},[currentGameState]) // eslint-disable-line
//// Capture add listener
useEffect(()=>{
const videoEl = document.getElementById("capture") as HTMLVideoElement
const listenEvent = (ev: MouseEvent) => {
if(captureStream){
captureStream.getTracks().forEach(x=>{
x.stop()
})
videoEl.srcObject = null
setCaptureStream(undefined)
}else{
meetingSession?.audioVideo.chooseVideoInputQuality(640,480,3,2000)
let displayMediaOptions = {
video: {
cursor: "never",
frameRate: 15,
},
audio: false
};
// @ts-ignore
navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then(stream=>{
videoEl.srcObject = stream
setCaptureStream(stream)
videoEl.play().then(()=>{
})
})
}
}
videoEl.addEventListener("click", listenEvent)
return ()=>{videoEl.removeEventListener("click", listenEvent)}
},[]) // eslint-disable-line
//////////////////////////
/// (1) hmm state
//////////////////////////
/// (1-1) owner
const ownerStateComp = useMemo(()=>{
return (
isOwner?
<>
<Tooltip title={"Your are owner"}>
<EmojiPeopleIcon className={classes.activeState_hmm} fontSize="large"/>
</Tooltip>
</>
:
<>
<Tooltip title={"Your are not owner"}>
<EmojiPeopleIcon className={classes.inactiveState} fontSize="large"/>
</Tooltip>
</>
)
},[isOwner]) // eslint-disable-line
/// (1-2) hmm active
const managerStateComp = useMemo(()=>{
return (
hMMStatus.active?
<>
<Tooltip title={"hmm active"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{sendTerminate()}}>
<SportsEsportsIcon className={classes.activeState_hmm} fontSize="large"/>
</IconButton>
</Tooltip>
</>
:
<>
<Tooltip title={"hmm not active"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{startHMM()}}>
<SportsEsportsIcon className={classes.inactiveState} fontSize="large"/>
</IconButton>
</Tooltip>
</>
)
},[hMMStatus.active]) // eslint-disable-line
/// (1-3) hmm recording
const recordingStateComp = useMemo(()=>{
return (
hMMStatus.recording?
<>
<Tooltip title={"recording"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{sendStopRecord()}}>
<CameraRollIcon className={classes.activeState_hmm} fontSize="large"/>
</IconButton>
</Tooltip>
</>
:
<>
<Tooltip title={"not recording"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{sendStartRecord()}}>
<CameraRollIcon className={classes.inactiveState} fontSize="large"/>
</IconButton>
</Tooltip>
</>
)
},[hMMStatus.recording]) // eslint-disable-line
/// (1-4) share multi tile
const shareTileViewStateComp = useMemo(()=>{
return (
hMMStatus.shareTileView?
<>
<Tooltip title={"share tile view"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{sendStopShareTileView()}}>
<ScreenShareIcon className={classes.activeState_hmm} fontSize="large"/>
</IconButton>
</Tooltip>
</>
:
<>
<Tooltip title={"not share share tile view"}>
<IconButton classes={{root:classes.menuButton}} onClick={()=>{sendStartShareTileView()}}>
<ScreenShareIcon className={classes.inactiveState} fontSize="large"/>
</IconButton>
</Tooltip>
</>
)
},[hMMStatus.shareTileView]) // eslint-disable-line
//// (1-x) lastupdate
const stateLastUpdateTime = useMemo(()=>{
const datetime = new Date(stateLastUpdate);
// const d = datetime.toLocaleDateString()
const t = datetime.toLocaleTimeString()
// return `${d} ${t}`
return `${t}`
},[stateLastUpdate])
//////////////////////////
/// (2) chime state
//////////////////////////
/// (2-1) arena mic state
const arenaMicrophoneComp = useMemo(()=>{
return (
chimeState.arenaMicrophone?
<>
<Tooltip title={"Mic On"}>
<MicIcon className={classes.activeState_arena} fontSize="large"/>
</Tooltip>
</>
:
<>
<Tooltip title={"Mic Off"}>
<MicIcon className={classes.inactiveState} fontSize="large"/>
</Tooltip>
</>
)
},[chimeState.arenaMicrophone]) // eslint-disable-line
/// (2-2) arena speaker state
const arenaSpeakerComp = useMemo(()=>{
return (
chimeState.arenaSpeaker?
<>
<Tooltip title={"Snd On"}>
<VolumeUpIcon className={classes.activeState_arena} fontSize="large"/>
</Tooltip>
</>
:
<>
<Tooltip title={"Snd Off"}>
<VolumeUpIcon className={classes.inactiveState} fontSize="large"/>
</Tooltip>
</>
)
},[chimeState.arenaSpeaker]) // eslint-disable-line
/// (2-3) arena share screen state
const arenaShareScreenComp = useMemo(()=>{
return (
chimeState.arenaShareScreen?
<>
<Tooltip title={"ScreenShare On"}>
<ScreenShareIcon className={classes.activeState_arena} fontSize="large"/>
</Tooltip>
</>
:
<>
<Tooltip title={"ScreenShare Off"}>
<ScreenShareIcon className={classes.inactiveState} fontSize="large"/>
</Tooltip>
</>
)
},[chimeState.arenaShareScreen]) // eslint-disable-line
/// (2-4) arena view screen state
const arenaViewScreenComp = useMemo(()=>{
return (
chimeState.arenaViewScreen?
<>
<Tooltip title={"ScreenShare On"}>
<ViewComfyIcon className={classes.activeState_arena} fontSize="large"/>
</Tooltip>
</>
:
<>
<Tooltip title={"ScreenShare Off"}>
<ViewComfyIcon className={classes.inactiveState} fontSize="large"/>
</Tooltip>
</>
)
},[chimeState.arenaViewScreen]) // eslint-disable-line
// /// (2-5) field mic state
// const fieldMicrophoneComp = useMemo(()=>{
// return (
// chimeState.fieldMicrophone?
// <>
// <Tooltip title={"Mic On"}>
// <MicIcon className={classes.activeState_field} fontSize="large"/>
// </Tooltip>
// </>
// :
// <>
// <Tooltip title={"Mic Off"}>
// <MicIcon className={classes.inactiveState} fontSize="large"/>
// </Tooltip>
// </>
// )
// },[chimeState.fieldMicrophone])
// /// (2-6) field speaker state
// const fieldSpeakerComp = useMemo(()=>{
// return (
// chimeState.fieldSpeaker?
// <>
// <Tooltip title={"Snd On"}>
// <VolumeUpIcon className={classes.activeState_field} fontSize="large"/>
// </Tooltip>
// </>
// :
// <>
// <Tooltip title={"Snd Off"}>
// <VolumeUpIcon className={classes.inactiveState} fontSize="large"/>
// </Tooltip>
// </>
// )
// },[chimeState.fieldSpeaker]) // eslint-disable-line
//// (2-x) game state
const gameStateComp = useMemo(()=>{
return(
<div>
<div>
{STATES[currentGameState.state]}
</div>
<div>
{currentGameState.lobbyCode}@{REGIONS[currentGameState.gameRegion]} {currentGameState.map}
</div>
</div>
)
},[currentGameState.state, currentGameState.gameRegion, currentGameState.lobbyCode, currentGameState.map])
//////////////////////////
/// (3) util
//////////////////////////
/// (3-1) Gear
const gearComp = useMemo(()=>{
return (
<>
<Tooltip title={"config"}>
<IconButton classes={{root:classes.menuButton}}>
<SettingsIcon className={classes.activeState_hmm} fontSize="large" onClick={()=>setSettingDialogOpen(true)}/>
</IconButton>
</Tooltip>
</>
)
},[]) // eslint-disable-line
/// (3-2) Leave
const leaveComp = useMemo(()=>{
return (
<>
<Tooltip title={"leave"}>
<IconButton classes={{root:classes.menuButton}}>
<ExitToAppIcon className={classes.activeState_hmm} fontSize="large" onClick={()=>setLeaveDialogOpen(true)}/>
</IconButton>
</Tooltip>
</>
)
},[]) // eslint-disable-line
//////////////////////////////
/// (4) user chooser
/////////////////////////////
const userChooser = useMemo(()=>{
return(
<FormControl className={classes.formControl} >
<InputLabel className={classes.label}>UserName</InputLabel>
<Select onChange={(e)=>{setUserName(e.target.value! as string)}}
className={classes.select}
value={userName}
defaultValue={userName}
inputProps={{
classes: {
icon: classes.icon,
},
className: classes.input_amongus
}}
>
<MenuItem value="__None__">
<em>__None__</em>
</MenuItem>
<MenuItem disabled value={userName}>
<em>{userName}</em>
</MenuItem>
{currentGameState.players?.map(p => {
return <MenuItem value={p.name} key={p.name}>{p.name}</MenuItem>
})}
</Select>
</FormControl>
)
},[currentGameState.players]) // eslint-disable-line
/////////////////////////////
/// (5) User List
////////////////////////////
const userList = useMemo(()=>{
return(
<div>
{
currentGameState.players.map(x=>{
return(
<div>
{
(x.isDead && x.isDeadDiscovered) || x.disconnected ?
<div><img style={{width:"20%"}} src={ICONS_DEAD[x.color]} alt="dead" ></img>{x.name}/{x.chimeName}</div>
:
<div><img style={{width:"20%"}} src={ICONS_ALIVE[x.color]} alt="alive" ></img>{x.name}/{x.chimeName}</div>
}
</div>
)}
)
}
</div>
)
},[currentGameState])
return (
<div className={classes.root}>
<div id="header" style={{display:"flex", flexDirection:"row"}} >
<div style={{display:"flex", flexDirection:"column"}}>
<div style={{display:"flex"}}>
{ownerStateComp}
{managerStateComp}
{recordingStateComp}
{shareTileViewStateComp}
</div>
<div>
{publicIp?`http://${publicIp}:3000`:""}
</div>
<div>
lastupdate:{stateLastUpdateTime}
</div>
</div>
<span style={{width:"30px"}}/>
<div style={{display:"flex", flexDirection:"column"}}>
<div style={{display:"flex", flexDirection:"row"}}>
<div style={{display:"flex"}}>
{arenaMicrophoneComp}
{arenaSpeakerComp}
{arenaShareScreenComp}
{arenaViewScreenComp}
</div>
<span style={{margin:"3px" }}> </span>
{/* <div style={{display:"flex"}}>
{fieldMicrophoneComp}
{fieldSpeakerComp}
</div> */}
</div>
<div>
{gameStateComp}
</div>
</div>
<span style={{width:"30px"}}/>
<div style={{display:"flex", flexDirection:"column"}}>
<div style={{display:"flex", flexDirection:"row"}}>
<div style={{display:"flex"}}>
{gearComp}
{leaveComp}
</div>
</div>
<div>
</div>
</div>
</div>
<Divider variant="middle" classes={{root:classes.dividerColor }}/>
<div id="main" style={{height:"100%", display:"flex", flexDirection:"row"}}>
<div style={{width:"20%", display:"flex", flexDirection:"column"}}>
{userChooser}
{userList}
</div>
<div style={{width:"65%", height:"100%", display:"flex", flexDirection:"column"}}>
<div style={{height:"20%", display:"flex", flexDirection:"row"}}>
<div style={{width:"25%", height:"100%", textAlign:"right" }}>
click to share your screen
</div>
<div style={{width:"30%", height:"100%", alignItems:"center" }}>
<video width="640" height="480" id="capture" style={{width:"50%", height:"100%", borderStyle:"dashed",borderColor: blueGrey[400]}} />
<canvas width={screenSize[0]} height={screenSize[1]} id="captureCanvas" hidden />
</div>
<div style={{width:"30%", height:"100%", alignItems:"center" }}>
</div>
</div>
<div style={{height:"80%", display:viewMode==="MultiTileView" ? "block":"none" }}>
<div style={{height:"100%", display:"flex", flexDirection:"row" }}>
<video id="tileView" style={{width:"97%", height:"100%", borderStyle:"solid",borderColor: blueGrey[900]}} />
<img id="mapView" style={{width:"97%", height:"100%", borderStyle:"solid",borderColor: blueGrey[900]}} alt="map" />
</div>
</div>
<div>
<audio id="arena_speaker" hidden />
</div>
<div style={{height:"80%", display:viewMode==="SeparateView" ? "block":"none" }}>
<div style={{display:"flex", flexDirection:"row"}}>
<video id="userView0" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView1" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView2" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView3" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
</div>
<div style={{display:"flex", flexDirection:"row"}}>
<video id="userView4" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView5" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView6" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView7" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
</div>
<div style={{display:"flex", flexDirection:"row"}}>
<video id="userView8" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView9" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView10" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView11" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
</div>
<div style={{display:"flex", flexDirection:"row"}}>
<video id="userView12" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView13" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView14" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
<video id="userView15" style={{width:"23%", borderStyle:"solid",borderColor: red[900]}} />
</div>
</div>
</div>
<div style={{width:"10%", height:"100%", display:"flex", flexDirection:"column"}}>
<div id="audiences" style={{height:"40%"}}>
<AudienceList />
</div>
<div id="chat" style={{height:"40%"}}>
<ChatArea />
</div>
<div>
<CreditPanel />
</div>
</div>
</div>
<LeaveMeetingDialog open={leaveDialogOpen} onClose={()=>setLeaveDialogOpen(false)} />
<SettingDialog open={settingDialogOpen} onClose={()=>setSettingDialogOpen(false)}
viewMode={viewMode} setViewMode={setViewMode}
debugEnable={debugEnable} setDebugEnable={setDebugEnable}
screenSize={screenSize} setScreenSize={setScreenSize}
/>
<div id="info1"/>
</div>
);
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/WebSocketApp/helper/WebSocketWhiteBoardClient.ts | import { Logger } from "amazon-chime-sdk-js";
import { Semaphore } from "await-semaphore";
import { WebSocketClient, WebSocketMessage } from "./WebSocketClient";
export const DrawingCmd = {
DRAW:"DRAW",
ERASE:"ERASE",
CLEAR:"CLEAR",
SYNC_SCREEN:"SYNC_SCREEN",
} as const
export type DrawingData = {
drawingCmd: keyof typeof DrawingCmd
startXR: number
startYR: number
endXR: number
endYR: number
stroke: string
lineWidth: number
canvasId?: string
}
const TOPIC_NAME = "WHITEBOARD"
const SEND_INTERVAL_TIME = 1000
const SEND_INTERVAL_NUM = 100
export class WebSocketWhiteBoardClient{
private semaphore = new Semaphore(1);
private drawingDataBuffer:DrawingData[] =[]
private wsClient:WebSocketClient
constructor(attendeeId:string, messagingURLWithQuery:string, logger:Logger, recreate:()=>void){
console.log("WSWBClient constructor1")
this.wsClient = new WebSocketClient(attendeeId, messagingURLWithQuery, logger, recreate)
console.log("WSWBClient constructor2")
this.wsClient.connect()
console.log("WSWBClient constructor3")
this.startMonitor()
}
addEventListener = (f:(wsMessage:WebSocketMessage[]) => void) =>{
this.wsClient.addEventListener(TOPIC_NAME, f)
}
removeEventListener = (f:(wsMessage:WebSocketMessage[])=>void) =>{
this.wsClient.removeEventListener(TOPIC_NAME, f)
}
addDrawindData = (data:DrawingData) => {
// loopback
this.wsClient.loopbackMessage(TOPIC_NAME, [data])
// send
this.semaphore.acquire().then(release=>{
this.drawingDataBuffer.push(data)
if(this.drawingDataBuffer.length > SEND_INTERVAL_NUM){
this.sendDrawingBuffer()
}
release()
})
}
startMonitor = () =>{
// console.log("startMonitor")
this.semaphore.acquire().then(release=>{
if(this.drawingDataBuffer.length>0){
this.sendDrawingBuffer()
}
release()
setTimeout(this.startMonitor, SEND_INTERVAL_TIME)
})
}
// Use this function under semaphore. (startMonitor, addDrawindData are known.)
private sendDrawingBuffer = () => {
this.wsClient.sendMessage(TOPIC_NAME, this.drawingDataBuffer)
this.drawingDataBuffer = []
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/CreditPanel.tsx | import React from 'react';
import { Typography } from '@material-ui/core';
import { useStyles } from './css';
export const CreditPanel = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Typography variant="body1" color="textSecondary">
About us
</Typography>
<Typography variant="body2">
This program is powered by <a href="https://www.flect.co.jp/" rel="noopener noreferrer" target="_blank">FLECT</a>.
<br/>
<a href="https://github.com/w-okada/flect-chime-sdk-demo" rel="noopener noreferrer" target="_blank">github</a>
</Typography>
<div className={classes.lineSpacer} />
<div className={classes.lineSpacer} />
<Typography variant="body1" color="textSecondary">
Acknowledgment
</Typography>
<Typography variant="body2">
This program uses the musics and sound effects from <a href="https://otologic.jp" rel="noopener noreferrer" target="_blank">OtoLogic</a>
</Typography>
<Typography variant="body2">
This program uses the images from <a href="https://www.irasutoya.com/" rel="noopener noreferrer" target="_blank">irasutoya</a>
</Typography>
</div>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/WebSocketApp/useWebSocketWhiteBoard.ts | <filename>frontend3/src/providers/hooks/WebSocketApp/useWebSocketWhiteBoard.ts
import { useEffect, useMemo, useState } from "react"
import { Logger } from "amazon-chime-sdk-js";
import { DrawingData, WebSocketWhiteBoardClient } from "./helper/WebSocketWhiteBoardClient";
import { WebSocketEndpoint } from "../../../BackendConfig";
import { WebSocketMessage } from "./helper/WebSocketClient";
export const DrawingMode = {
DRAW:"DRAW",
ERASE:"ERASE",
DISABLE: "DISABLE"
} as const
type UseWebSocketWhiteBoardProps = {
meetingId:string
attendeeId:string
joinToken:string
logger?:Logger
}
export const useWebSocketWhiteBoard = (props:UseWebSocketWhiteBoardProps) =>{
const [drawingData, setDrawingData] = useState<DrawingData[]>([])
const [lineWidth, setLineWidth] = useState(3)
const [drawingStroke, setDrawingStroke] = useState("#aaaaaaaa")
const [drawingMode, setDrawingMode] = useState<keyof typeof DrawingMode>(DrawingMode.DISABLE)
const [recreateCount, setRecreateCount ] = useState(0)
const recreate = () =>{
console.log("websocket recreate!!!!")
setRecreateCount(recreateCount+1)
}
const WSWBClient = useMemo(()=>{
if(props.meetingId === "" || props.attendeeId === "" || props.joinToken === "" || !props.logger){
console.log("WSWBClient not create!!!")
return null
}else{
console.log("WSWBClient create")
const messagingURLWithQuery = `${WebSocketEndpoint}/Prod?joinToken=${props.joinToken}&meetingId=${props.meetingId}&attendeeId=${props.attendeeId}`
const WSWBClient = new WebSocketWhiteBoardClient(props.attendeeId, messagingURLWithQuery, props.logger, recreate)
return WSWBClient
}
},[props.meetingId, props.attendeeId, props.joinToken, props.logger, recreateCount]) // eslint-disable-line
useEffect(()=>{
const f = (wsMessages:WebSocketMessage[])=>{
const newDrawingData = wsMessages.reduce<DrawingData[]>((sum:any[],cur:WebSocketMessage)=>{return [...sum, ...(cur.data as DrawingData[])]},[])
setDrawingData(newDrawingData)
}
WSWBClient?.addEventListener(f)
return ()=>{WSWBClient?.removeEventListener(f)}
},[WSWBClient, drawingData])
const addDrawingData = WSWBClient?.addDrawindData
return {addDrawingData, drawingData, lineWidth, setLineWidth, drawingStroke, setDrawingStroke, drawingMode, setDrawingMode}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/css.ts | import { createStyles, makeStyles, Theme } from "@material-ui/core";
import { blueGrey, grey } from "@material-ui/core/colors";
const lineSpacerHeihgt = 10
export const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
background:"black",
color:'white',
height:"100%",
widht:"100%",
},
container: {
maxHeight: `calc(100% - 10px)`,
},
title: {
fontSize: 14,
},
button:{
margin: theme.spacing(1)
},
activatedButton: {
margin: theme.spacing(1),
color: "#ee7777"
},
lineSpacer:{
height:lineSpacerHeihgt,
},
margin: {
margin: theme.spacing(1),
},
formControl: {
margin: theme.spacing(1),
width: '100%'
// minWidth: 120,
},
icon: {
fill: blueGrey[300],
},
label: {
color: blueGrey[300],
"&.Mui-focused": {
color: blueGrey[300],
},
},
select: {
'&:before': {
borderColor: blueGrey[300],
color:blueGrey[300],
},
'&:after': {
borderColor: blueGrey[300],
color: blueGrey[300],
}
},
input_amongus: {
color: blueGrey[300],
},
//// Color
activeState_old: {
color: theme.palette.getContrastText(blueGrey[500]),
backgroundColor: blueGrey[500],
margin:3
},
activeState_hmm: {
color: "white",
backgroundColor: "burlywood",
margin:3
},
activeState_arena: {
color: blueGrey[100],
backgroundColor: blueGrey[500],
margin:3
},
activeState_field: {
color: "white",
backgroundColor: "red",
margin:3
},
inactiveState: {
color: theme.palette.getContrastText(grey[500]),
backgroundColor: grey[500],
margin:3
},
menuButton: {
// display: 'inline-block',
padding:0,
margin:0,
border:0,
minHeight: 0,
minWidth: 0,
verticalAlign:"top"
},
dividerColor: {
background: "grey"
}
}),
);
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/ManagerControllerPanel.tsx | <filename>frontend3/src/pages/023_meetingRoom/components/sidebars/ManagerControllerPanel.tsx<gh_stars>0
import React, { useEffect, useMemo,} from 'react';
import { Button, Tooltip, Typography } from '@material-ui/core';
import { useStyles } from './css';
import { useAppState } from '../../../../providers/AppStateProvider';
import EmojiPeopleIcon from '@material-ui/icons/EmojiPeople';
import ScreenShareIcon from '@material-ui/icons/ScreenShare';
import CameraRollIcon from '@material-ui/icons/CameraRoll';
import SportsEsportsIcon from '@material-ui/icons/SportsEsports';
export const ManagerControllerPanel = () => {
const classes = useStyles();
const {ownerId, isOwner, publicIp,
startHMM, sendTerminate, sendStartRecord, sendStopRecord, sendStartShareTileView, sendStopShareTileView, hMMStatus, stateLastUpdate,
currentGameState
} = useAppState()
const ownerStateComp = useMemo(()=>{
return (
isOwner?
<>
<Tooltip title={"Your are owner"}>
<EmojiPeopleIcon className={classes.activeState}/>
</Tooltip>
</>
:
<>
<Tooltip title={"Your are not owner"}>
<EmojiPeopleIcon className={classes.inactiveState}/>
</Tooltip>
</>
)
},[isOwner]) // eslint-disable-line
const managerStateComp = useMemo(()=>{
return (
hMMStatus.active?
<>
<Tooltip title={"hmm active"}>
<SportsEsportsIcon className={classes.activeState}/>
</Tooltip>
</>
:
<>
<Tooltip title={"hmm not active"}>
<SportsEsportsIcon className={classes.inactiveState}/>
</Tooltip>
</>
)
},[hMMStatus.active]) // eslint-disable-line
const recordingStateComp = useMemo(()=>{
return (
hMMStatus.recording?
<>
<Tooltip title={"recording"}>
<CameraRollIcon className={classes.activeState}/>
</Tooltip>
</>
:
<>
<Tooltip title={"not recording"}>
<CameraRollIcon className={classes.inactiveState}/>
</Tooltip>
</>
)
},[hMMStatus.recording]) // eslint-disable-line
const shareTileViewStateComp = useMemo(()=>{
return (
hMMStatus.shareTileView?
<>
<Tooltip title={"share tile view"}>
<ScreenShareIcon className={classes.activeState}/>
</Tooltip>
</>
:
<>
<Tooltip title={"not share share tile view"}>
<ScreenShareIcon className={classes.inactiveState}/>
</Tooltip>
</>
)
},[hMMStatus.shareTileView]) // eslint-disable-line
const stateLastUpdateTime = useMemo(()=>{
const datetime = new Date(stateLastUpdate);
// const d = datetime.toLocaleDateString()
const t = datetime.toLocaleTimeString()
// return `${d} ${t}`
return `${t}`
},[stateLastUpdate])
useEffect(()=>{
console.log(currentGameState)
// console.log("AMONG:", amongUsStates.slice(-1)[0])
},[currentGameState])
return (
<div className={classes.root}>
<Typography variant="body1" color="textSecondary">
Manager
</Typography>
{ownerStateComp}
{managerStateComp}
{recordingStateComp}
{shareTileViewStateComp}
<br/>
lastupdate:{stateLastUpdateTime}
<br/>
<br/>
<Button size="small" className={classes.margin} onClick={()=>{startHMM()}} >
run manager
</Button>
<Button size="small" className={classes.margin} onClick={()=>{ sendTerminate() }}>
stop manager
</Button>
<Button size="small" className={classes.margin} onClick={()=>{sendStartRecord()}}>
start recording
</Button>
<Button size="small" className={classes.margin} onClick={()=>{sendStopRecord()}}>
stop recording
</Button>
<Button size="small" className={classes.margin} onClick={()=>{sendStartShareTileView()}}>
start share tileview
</Button>
<Button size="small" className={classes.margin} onClick={()=>{sendStopShareTileView()}}>
stop share tileview
</Button>
<div>
<br/>
Owner:{ownerId}
<br />
{publicIp? `publicIp ${publicIp}`:""}
</div>
</div>
);
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/200_HeadlessMeetingManager/components/views/RecorderView.tsx | import { useEffect, useMemo } from "react"
import { useAppState } from "../../../../providers/AppStateProvider";
import { VideoTileState } from "amazon-chime-sdk-js";
import { RendererForRecorder } from "../../../023_meetingRoom/components/ScreenView/helper/RendererForRecorder";
export type FocustTarget = "SharedContent" | "Speaker"
type Props = {
width: number
height: number
setActiveRecorderCanvas: (c:HTMLCanvasElement)=>void
setAllRecorderCanvas: (c:HTMLCanvasElement)=>void
};
export const RecorderView = ({ width, height, setActiveRecorderCanvas, setAllRecorderCanvas }: Props) => {
const { videoTileStates, activeSpeakerId, meetingSession, getUserNameByAttendeeIdFromList } = useAppState()
const activeRenderer = useMemo(()=>{return new RendererForRecorder(meetingSession!)},[]) // eslint-disable-line
const allRenderer = useMemo(()=>{return new RendererForRecorder(meetingSession!)},[]) // eslint-disable-line
/// Active Tiles
const contentsTiles = Object.values(videoTileStates).filter(tile=>{return tile.isContent})
const activeSpekerTile = activeSpeakerId && videoTileStates[activeSpeakerId] ? videoTileStates[activeSpeakerId] : null
const activeTiles = (contentsTiles.length > 0 ? contentsTiles : [activeSpekerTile]).filter(tile=>{return tile!==null}) as VideoTileState[]
const activeTilesId = activeTiles.reduce<string>((sum,cur)=>{return `${sum}-${cur.boundAttendeeId}`},"")
/// All Tiles
const allTiles = Object.values(videoTileStates).filter(x=>{return x.localTile===false})
// const allTiles = Object.values(videoTileStates).filter(x=>{x.boundAttendeeId !== attendeeId})
const allTilesId = allTiles.reduce<string>((sum,cur)=>{return `${sum}-${cur.boundAttendeeId}`},"")
//// (1) Setup Renderer, notify canvas to parent
//// (1-1) setup for ActiveRenderer
useEffect(() => {
const activeDstCanvas = document.getElementById("ActiveRecorderCanvas") as HTMLCanvasElement
activeRenderer.init(activeDstCanvas)
activeRenderer.start()
setActiveRecorderCanvas(activeDstCanvas)
return () => {
console.log("destroy renderer", activeRenderer)
activeRenderer.destroy()
}
}, []) // eslint-disable-line
//// (1-2) setup for AllRenderer
useEffect(() => {
const allDstCanvas = document.getElementById("AllRecorderCanvas") as HTMLCanvasElement
allRenderer.init(allDstCanvas)
allRenderer.start()
setAllRecorderCanvas(allDstCanvas)
return () => {
console.log("destroy renderer", activeRenderer)
activeRenderer.destroy()
}
}, []) // eslint-disable-line
//// (2) Set srouce video
//// (a) bind, (b) input into renderer
//// (2-1) for Active Renderer
useEffect(()=>{
console.log("Active CHANGE!", activeTilesId)
const videoElems = [...Array(activeTiles.length)].map((v,i)=>{return document.getElementById(`activeVideo${i}`) as HTMLVideoElement})
const titles:string[] = []
// console.log(videoElems)
activeTiles.forEach((tile,index)=>{
if(tile.tileId){
meetingSession?.audioVideo.bindVideoElement(tile.tileId, videoElems[index])
const name = getUserNameByAttendeeIdFromList(tile.boundAttendeeId!)
titles.push(name)
}
})
activeRenderer.setSrcVideoElements(videoElems)
activeRenderer.setTitles(titles)
},[activeTilesId]) // eslint-disable-line
//// (2-2) for All Renderer
useEffect(()=>{
const videoElems = [...Array(allTiles.length)].map((v,i)=>{return document.getElementById(`video${i}`) as HTMLVideoElement})
// console.log(videoElems)
const titles:string[] = []
allTiles.forEach((tile,index)=>{
if(tile.tileId){
meetingSession?.audioVideo.bindVideoElement(tile.tileId, videoElems[index])
const name = getUserNameByAttendeeIdFromList(tile.boundAttendeeId!)
titles.push(name)
}
})
allRenderer.setSrcVideoElements(videoElems)
allRenderer.setTitles(titles)
},[allTilesId]) // eslint-disable-line
return (
<div style={{ width: width, height: height, position:"relative" }}>
<div style={{ width: "100%", position:"relative"}}>
{/* <canvas width="1920" height="1080" id="ActiveRecorderCanvas" style={{ width: "40%", border: "medium solid #ffaaaa"}} />
<canvas width="1920" height="1080" id="AllRecorderCanvas" style={{ width: "40%", border: "medium solid #ffaaaa"}} /> */}
<canvas width="800" height="600" id="ActiveRecorderCanvas" style={{ width: "40%", border: "medium solid #ffaaaa"}} />
<canvas width="800" height="600" id="AllRecorderCanvas" style={{ width: "40%", border: "medium solid #ffaaaa"}} />
</div>
<div style={{ width: "100%", display:"flex", flexWrap:"wrap" }}>
<video id="activeVideo0" style={{ width: "10%", height:"10%"}}/>
<video id="activeVideo1" style={{ width: "10%", height:"10%"}} />
<video id="activeVideo2" style={{ width: "10%", height:"10%"}} />
<video id="video0" style={{ width: "10%", height:"10%"}} />
<video id="video1" style={{ width: "10%", height:"10%"}} />
<video id="video2" style={{ width: "10%", height:"10%"}} />
<video id="video3" style={{ width: "10%", height:"10%"}} />
<video id="video4" style={{ width: "10%", height:"10%"}} />
<video id="video5" style={{ width: "10%", height:"10%"}} />
<video id="video6" style={{ width: "10%", height:"10%"}} />
<video id="video7" style={{ width: "10%", height:"10%"}} />
<video id="video8" style={{ width: "10%", height:"10%"}} />
<video id="video9" style={{ width: "10%", height:"10%"}} />
<video id="video10" style={{ width: "10%", height:"10%"}} />
<video id="video11" style={{ width: "10%", height:"10%"}} />
<video id="video12" style={{ width: "10%", height:"10%"}} />
<video id="video13" style={{ width: "10%", height:"10%"}} />
<video id="video14" style={{ width: "10%", height:"10%"}} />
<video id="video15" style={{ width: "10%", height:"10%"}} />
<video id="video16" style={{ width: "10%", height:"10%"}} />
<video id="video17" style={{ width: "10%", height:"10%"}} />
<video id="video18" style={{ width: "10%", height:"10%"}} />
</div>
</div>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/observers/TransformObserver.ts | import { DefaultVideoTransformDeviceObserver } from "amazon-chime-sdk-js";
export class DefaultVideoTransformDeviceObserverImpl implements DefaultVideoTransformDeviceObserver {
processingDidStart() {
console.log("process Start!")
}
processingDidFailToStart() {
console.log("process Fail Start!")
}
processingDidStop() {
console.log("process stop!!")
}
processingLatencyTooHigh(latencyMs: number) {
console.log("process latency!!", latencyMs)
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/DrawableVideoTile.tsx | import { VideoTileState } from "amazon-chime-sdk-js";
import { useEffect, useMemo, useState } from "react";
import { useAppState } from "../../../../providers/AppStateProvider";
import { DrawingHelper } from "./helper/DrawingHelper";
type DrawableVideoTileProps = {
tile: VideoTileState,
idPrefix: string, // prefix for HTMLVideoElement and HTMLCanvasElement
idSuffix?: string, // suffix for HTMLVideoElement and HTMLCanvasElement (for feature)
width:number,
height:number
}
export const DrawableVideoTile = (props:DrawableVideoTileProps) =>{
const { meetingSession, addDrawingData, drawingData, lineWidth, drawingStroke, drawingMode } = useAppState()
const drawingHelper = useMemo(()=>{
return new DrawingHelper(`${props.idPrefix}-canvas${props.idSuffix?"#"+props.idSuffix:""}`)
},[]) // eslint-disable-line
const [drawingNeedUpdate, setDrawaingNeedUpdate] = useState(0)
drawingHelper.addDrawingData = addDrawingData
drawingHelper.lineWidth = lineWidth
drawingHelper.drawingStroke = drawingStroke
drawingHelper.drawingMode = drawingMode
const view = useMemo(()=>{
const videoElementId = `${props.idPrefix}-video`
const canvasElementId = `${props.idPrefix}-canvas`
return(
<div style={{width:`${props.width}px`, height:`${props.height}px`}}>
<video id={videoElementId} style={{objectFit:"contain", position:"absolute", height:props.height-2, width:props.width}}/>
<canvas id={canvasElementId} style={{objectFit:"contain", position:"absolute", height:props.height-2, width:props.width}} />
</div>
)
},[props.idPrefix, props.tile, props.width, props.height]) // eslint-disable-line
// Bind and Fit Size
useEffect(()=>{
const videoElementId = `${props.idPrefix}-video`
const videoElement = document.getElementById(videoElementId)! as HTMLVideoElement
// Fit Canvas Size
videoElement.onloadedmetadata = () =>{
console.log("loaded video")
const canvasElementId = `${props.idPrefix}-canvas`
const canvasElement = document.getElementById(canvasElementId)! as HTMLCanvasElement
if(!videoElement || !canvasElement){
console.log("[DrawableVideoTile] no video element or no canvas element")
return
}
canvasElement.width = videoElement.videoWidth
canvasElement.height = videoElement.videoHeight
setDrawaingNeedUpdate(drawingNeedUpdate+1) // above resize delete drawing.
}
// Bind Video
console.log("[DrawableVideoTile] bind view")
if(videoElement && props.tile.tileId){
meetingSession?.audioVideo.bindVideoElement(props.tile.tileId, videoElement)
}else{
console.log("BIND FAILED", videoElementId, videoElement)
}
},[props.idPrefix, props.tile, props.width, props.height]) // eslint-disable-line
// Set Drawing Listeners
useEffect(()=>{
console.log("[DrawableVideoTile] add listeners")
const canvasElementId = `${props.idPrefix}-canvas`
const canvasElement = document.getElementById(canvasElementId)! as HTMLCanvasElement
canvasElement.addEventListener("mousedown", drawingHelper.drawingStart, { passive: false })
canvasElement.addEventListener("mouseup", drawingHelper.drawingEnd, { passive: false })
canvasElement.addEventListener("mouseleave", drawingHelper.drawingEnd, { passive: false })
canvasElement.addEventListener("mousemove", drawingHelper.drawing, { passive: false })
canvasElement.addEventListener("touchstart", drawingHelper.touchStart, { passive: false })
canvasElement.addEventListener("touchend", drawingHelper.touchEnd, { passive: false })
canvasElement.addEventListener("touchmove", drawingHelper.touchMove, { passive: false })
},[]) // eslint-disable-line
// Apply Drawing Data
useEffect(()=>{
console.log("[DrawableVideoTile] apply DrawingData")
const canvasElementId = `${props.idPrefix}-canvas`
const canvasElement = document.getElementById(canvasElementId)! as HTMLCanvasElement
const ctx = canvasElement.getContext("2d")!
ctx.strokeStyle = drawingStroke
ctx.lineWidth = lineWidth
ctx.clearRect(0,0, canvasElement.width, canvasElement.height)
console.log("[DrawableVideoTile] apply DrawingData----", drawingData)
drawingData.forEach((data)=>{
if(data.drawingCmd === "DRAW" && data.canvasId && (data.canvasId.indexOf(canvasElementId) >= 0 || canvasElementId.indexOf(data.canvasId) >= 0 )){
ctx.beginPath();
ctx.moveTo(data.startXR * canvasElement.width, data.startYR * canvasElement.height);
ctx.lineTo(data.endXR * canvasElement.width, data.endYR * canvasElement.height);
ctx.strokeStyle = data.stroke
ctx.lineWidth = data.lineWidth
ctx.stroke();
ctx.closePath();
}else if(data.drawingCmd === "ERASE" && data.canvasId && (data.canvasId.indexOf(canvasElementId) >= 0 || canvasElementId.indexOf(data.canvasId) >= 0 )){
const startX = data.startXR * canvasElement.width - (data.lineWidth/2)
const startY = data.startYR * canvasElement.height - (data.lineWidth/2)
ctx.clearRect(startX, startY, data.lineWidth, data.lineWidth)
}else if(data.drawingCmd === "CLEAR"){
ctx.clearRect(0,0, canvasElement.width, canvasElement.height)
}
})
},[props.idPrefix, props.tile, drawingData, drawingNeedUpdate]) // eslint-disable-line
return(<>{view}</>)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/CustomAccordion.tsx | <gh_stars>0
import React, { ReactNode } from "react"
import MuiAccordionDetails from '@material-ui/core/AccordionDetails';
import MuiAccordion from '@material-ui/core/Accordion';
import MuiAccordionSummary from '@material-ui/core/AccordionSummary';
import { withStyles } from "@material-ui/core/styles";
type Props = {
title: string
children: ReactNode
};
const Accordion = withStyles({
root: {
boxShadow: 'none',
margin: '0px',
'&$expanded': {
margin: '0px',
},
},
expanded: {},
})(MuiAccordion);
const AccordionSummary = withStyles({
root: {
backgroundColor: 'rgba(250, 250, 250)',
margin: '0px',
height: "10px",
'&$expanded': {
height: "0px",
margin: '0px',
},
},
content: {
margin: '0px',
'&$expanded': {
height: "0px",
},
},
})(MuiAccordionSummary);
const AccordionDetails = withStyles((theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiAccordionDetails);
export const CustomAccordion = ({ title, children }: Props) => {
return (
<>
<Accordion square >
{/* <AccordionSummary expandIcon={<ExpandMore />}> */}
<AccordionSummary>
{title}
</AccordionSummary>
<AccordionDetails>
{children}
</AccordionDetails>
</Accordion>
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/ChatArea.tsx | import React, { useMemo, useState } from 'react';
import { Button, TextField, Typography } from '@material-ui/core';
import { useAppState } from '../../../../providers/AppStateProvider';
import { useStyles } from './css';
export const ChatArea = () => {
const classes = useStyles();
const { chatData, sendChatData, getUserNameByAttendeeIdFromList } = useAppState()
const [message, setMessage] = useState("")
const sendMessage = () => {
sendChatData(message)
setMessage("")
}
const chatViewArea = useMemo(()=>{
return(
<div className={classes.messageArea}>
{
chatData.map((d, i) => {
return (
<div key={`mes${i}`} className={classes.message}>
<Typography className={classes.title} color="textSecondary">
{getUserNameByAttendeeIdFromList(d.senderId)}, {new Date(d.createdDate).toLocaleTimeString()}
</Typography>
{(d.data as string).split("\n").map((l,j) => { return <div key={`detail${j}`}>{l}</div> })}
</div>
)
})
}
</div>
)
},[chatData]) // eslint-disable-line
return (
<div className={classes.root}>
<div className={classes.margin}>
{chatViewArea}
</div>
<div>
<TextField
id="outlined-multiline-static"
label="Message"
multiline
rows={2}
value={message}
onChange={(e) => { setMessage(e.target.value) }}
variant="outlined"
/>
</div>
<div className={classes.sendButton}>
<Button variant="outlined" color="primary" size="small" onClick={sendMessage}>
send
</Button>
</div>
</div>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/200_HeadlessMeetingManager/HeadlessMeetingManager.tsx | import React, { useEffect, useState } from "react";
import { useAppState } from "../../providers/AppStateProvider";
import { HMMCmd } from "../../providers/hooks/RealtimeSubscribers/useRealtimeSubscribeHMM";
import { useScheduler } from "../../providers/hooks/useScheduler";
import { LocalLogger } from "../../utils/localLogger";
import { RecorderView } from "./components/views/RecorderView";
import { useRecorder } from "./hooks/useRecorder";
import { useShareTileView } from "./hooks/useShareTileView";
import { useStatusMonitor } from "./hooks/useStatusMonitor";
type InternalStage = "Signining" | "Joining" | "Entering" | "Ready"
type State = {
internalStage: InternalStage,
userName: string | null
}
const logger = new LocalLogger("HeadlessMeetingManager")
const sleep = async(ms:number)=>{
const p = new Promise((resolve) => {
setTimeout(resolve, ms);
});
await p
}
export const HeadlessMeetingManager = () => {
//// Query Parameters
const query = new URLSearchParams(window.location.search);
const meetingName = query.get('meetingName') || null // meeting name is already encoded
const attendeeId = query.get('attendeeId') || null
const uuid = query.get('uuid') || null
const code = query.get('code') || null // OnetimeCode
// const decodedMeetingName = decodeURIComponent(meetingName!)
const { handleSinginWithOnetimeCode, joinMeeting, enterMeeting, attendees, sendHMMStatus, terminateCounter,
audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting, audioOutputList, sendHMMCommand, gameState,
updateGameState} = useAppState()
const [ state, setState] = useState<State>({internalStage:"Signining", userName:null})
const { meetingActive } = useStatusMonitor()
const { isRecording, setActiveCanvas, setAllCanvas, stopRecord } = useRecorder({meetingName:meetingName||"unknown"})
const { isSharingTileView, setTileCanvas } = useShareTileView({meetingName:meetingName||"unknown"})
const { tenSecondsTaskTrigger } = useScheduler()
useEffect (()=>{
console.log("HMM_SEND_STATUS------->",JSON.stringify(gameState))
sendHMMCommand({command:HMMCmd.NOTIFY_AMONGUS_STATUS, data:gameState})
},[gameState]) // eslint-disable-line
const setTileCanvasExport = (canvas:HTMLCanvasElement) => {
setAllCanvas(canvas)
setTileCanvas(canvas)
}
const finalizeMeeting = async() =>{
logger.log("meeting is no active. stop recording...")
await stopRecord()
logger.log("meeting is no active. stop recording...done. sleep 20sec")
await sleep(20 * 1000)
logger.log("meeting is no active. stop recording...done. sleep 20sec done.")
logger.log("terminate event fire")
const event = new CustomEvent('terminate');
document.dispatchEvent(event)
logger.log("terminate event fired")
}
useEffect(()=>{
if(meetingActive===false){
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
}
},[meetingActive]) // eslint-disable-line
useEffect(()=>{
if(terminateCounter>0){
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
}
},[terminateCounter]) // eslint-disable-line
useEffect(()=>{
sendHMMStatus(true, isRecording, isSharingTileView)
},[tenSecondsTaskTrigger]) // eslint-disable-line
useEffect(()=>{
if(state.internalStage === "Signining"){
logger.log("Singining....")
if(!meetingName || !attendeeId || !uuid || !code){
logger.log(`"Exception: Signin error. Information is insufficent meetingName${meetingName}, attendeeId=${attendeeId}, uuid=${uuid}, code=${code}`)
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
return
}
handleSinginWithOnetimeCode(meetingName, attendeeId, uuid, code).then((res)=>{
if(res.result){
setState({...state, userName: res.attendeeName||null, internalStage:"Joining"})
}else{
logger.log("Exception: Signin error, can not sigin. please generate code and retry.", res)
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
}
})
}else if(state.internalStage === "Joining"){
logger.log("Joining....")
joinMeeting(meetingName!, `@Manager[${state.userName!}]`).then(()=>{
setState({...state, internalStage:"Entering"})
}).catch(e=>{
logger.log("joining failed",e)
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
})
}else if(state.internalStage === "Entering"){
logger.log("entering...")
const p1 = audioInputDeviceSetting!.setAudioInput("dummy")
const p2 = videoInputDeviceSetting!.setVideoInput(null)
videoInputDeviceSetting!.setVirtualForegrounEnable(false)
videoInputDeviceSetting!.setVirtualBackgrounEnable(false)
const audioOutput = (audioOutputList && audioOutputList!.length > 0) ? audioOutputList[0].deviceId:null
logger.log("Active Speaker::::::audio", audioOutput?audioOutput:"null")
const p3 = audioOutputDeviceSetting!.setAudioOutput(audioOutput)
// const p3 = audioOutputDeviceSetting!.setAudioOutput(null)
enterMeeting().then(()=>{
Promise.all( [p1, p2, p3] ).then(()=>{
setState({...state, internalStage:"Ready"})
// setStage("HEADLESS_MEETING_MANAGER2")
})
}).catch(e=>{
logger.log("enter meeting failed",e)
finalizeMeeting()
sendHMMStatus(false, isRecording, isSharingTileView)
})
}else if(state.internalStage === "Ready"){
logger.log("ready....")
const audioElement = document.getElementById("for-speaker")! as HTMLAudioElement
audioElement.autoplay=false
audioElement.volume = 0
audioOutputDeviceSetting!.setOutputAudioElement(audioElement)
}
},[state.internalStage]) // eslint-disable-line
return (
<>
<RecorderView height={200} width={500} setActiveRecorderCanvas={setActiveCanvas} setAllRecorderCanvas={setTileCanvasExport}/>
<div>recording:{isRecording?"true":"false"}</div>
<div>ATTTENDEES:{Object.keys(attendees).map(x=>{return `[${x}]`})}</div>
<a id="activeVideoLink">active speaker</a>
<a id="allVideoLink">all speaker</a>
<div>
<audio id="for-speaker" style={{display:"none"}}/>
</div>
<div>
<input id="io_event"/>
<input id="io_data"/>
<button id="io_click" onClick={()=>{
const ev = document.getElementById("io_event") as HTMLInputElement
const data = document.getElementById("io_data") as HTMLInputElement
console.log("RECEIVE DATA:", ev.value)
console.log("RECEIVE DATA:", data.value)
updateGameState(ev.value, data.value)
}} />
</div>
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/RealtimeSubscribers/useRealtimeSubscribeChat.ts |
import { DefaultMeetingSession, DataMessage } from "amazon-chime-sdk-js";
import { useEffect, useMemo, useState } from "react";
import { RealtimeData, RealtimeDataApp} from "./const";
import { v4 } from 'uuid';
type UseRealtimeSubscribeChat = {
meetingSession?:DefaultMeetingSession
attendeeId:string
}
export const useRealtimeSubscribeChat = (props: UseRealtimeSubscribeChat) =>{
const meetingSession = useMemo(()=>{
return props.meetingSession
},[props.meetingSession])
const attendeeId = useMemo(()=>{
return props.attendeeId
},[props.attendeeId])
const [chatData, setChatData] = useState<RealtimeData[]>([])
const sendChatData = (text: string) => {
console.log("chatdata::", attendeeId )
const mess: RealtimeData = {
uuid: v4(),
action: 'sendmessage',
app: RealtimeDataApp.CHAT ,
data: text,
createdDate: new Date().getTime(),
senderId: attendeeId
}
meetingSession?.audioVideo!.realtimeSendDataMessage(RealtimeDataApp.CHAT , JSON.stringify(mess))
setChatData([...chatData, mess])
}
const receiveChatData = (mess: DataMessage) => {
const senderId = mess.senderAttendeeId
const data = JSON.parse(mess.text()) as RealtimeData
data.senderId = senderId
setChatData([...chatData, data])
}
useEffect(() => {
meetingSession?.audioVideo?.realtimeSubscribeToReceiveDataMessage(
RealtimeDataApp.CHAT,
receiveChatData
)
return () => {
meetingSession?.audioVideo?.realtimeUnsubscribeFromReceiveDataMessage(RealtimeDataApp.CHAT)
}
})
return {chatData, sendChatData}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/css.ts | <reponame>diitalk/flect-chime-sdk-demo
import { createStyles, makeStyles, Theme } from "@material-ui/core";
import { deepOrange, grey } from "@material-ui/core/colors";
const lineSpacerHeihgt = 10
export const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
// height: '100%',
height: 400,
width: "100%",
wordWrap: "break-word",
whiteSpace: "normal"
},
container: {
maxHeight: `calc(100% - 10px)`,
},
title: {
fontSize: 14,
},
button:{
margin: theme.spacing(1)
},
activatedButton: {
margin: theme.spacing(1),
color: "#ee7777"
},
lineSpacer:{
height:lineSpacerHeihgt,
},
margin: {
margin: theme.spacing(1),
},
//// Member
table: {
// minWidth: 750,
width: 20
},
visuallyHidden: {
border: 0,
clip: 'rect(0 0 0 0)',
height: 1,
margin: -1,
overflow: 'hidden',
padding: 0,
position: 'absolute',
top: 20,
width: 1,
},
// paper: {
// width: '100%',
// marginBottom: theme.spacing(2),
// },
//// for chat
messageArea:{
height: 280,
width: "100%",
overflow: 'auto'
},
message:{
width: "100%",
textAlign: 'left',
wordWrap: "break-word",
whiteSpace: "normal"
},
sendButton:{
textAlign: 'right',
},
//// for whiteboard
paper: {
width: '100%',
marginBottom: theme.spacing(2),
maxHeight: `calc(100% - 10px)`,
orverflow: 'scroll',
},
selectedColor:{
border: "1px solid",
borderRadius: "4px",
},
color:{
},
//// for BGM
seList:{
height: '70%',
width: "100%",
wordWrap: "break-word",
whiteSpace: "normal",
overflow: "auto"
},
control:{
height: '30%',
width: "100%",
wordWrap: "break-word",
whiteSpace: "normal",
overflow: "auto"
},
volumeControl:{
display:"flex"
},
//// Color
activeState: {
color: theme.palette.getContrastText(deepOrange[500]),
backgroundColor: deepOrange[500],
margin:3
},
inactiveState: {
color: theme.palette.getContrastText(grey[500]),
backgroundColor: grey[500],
margin:3
},
}),
);
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useScheduler.ts | <reponame>diitalk/flect-chime-sdk-demo
import { useEffect, useState } from "react"
export const useScheduler = () =>{
const [ tenSecondsTaskTrigger, setTenSecondsTasksTringer] = useState(0)
const [ thirtyMinutesSecondsTaskTrigger, setThirtyMinutesSecondsTaskTrigger] = useState(0)
useEffect(() => {
setInterval(() => {
setTenSecondsTasksTringer(t => t + 1);
}, 1000 * 10)
},[])
useEffect(() => {
setInterval(() => {
setThirtyMinutesSecondsTaskTrigger(t => t + 1);
}, 1000 * 60 + 30)
},[])
return {tenSecondsTaskTrigger, thirtyMinutesSecondsTaskTrigger}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/GridView.tsx | import { GridList, GridListTile, GridListTileBar, makeStyles, withStyles } from "@material-ui/core";
import React, { useMemo } from "react";
import { useAppState } from "../../../../providers/AppStateProvider";
import { DrawableVideoTile } from "./DrawableVideoTile";
const GridListTileBar2 = withStyles({
root: {
height: 15,
},
title: {
fontSize:10,
},
})(GridListTileBar);
const useStyles = makeStyles((theme) => ({
gridList: {
width: '100%',
},
videoTile:{
width:'100%',
height:'100%',
},
videoTileActive:{
width:'100%',
height:'100%',
},
videoTileBar:{
},
videoTileBarActive:{
backgroundColor:"#ee7777"
}
}));
type Props = {
excludeSharedContent: boolean
width:number
height:number
};
type VideoState = "ENABLED" | "PAUSED" | "NOT_SHARE"
export const GridView = ({ excludeSharedContent, width, height}: Props) => {
const classes = useStyles()
const { attendees, videoTileStates, activeSpeakerId, getUserNameByAttendeeIdFromList } = useAppState()
let targetTiles = Object.values(videoTileStates).filter(tile =>{
return attendees[tile.boundAttendeeId!].isVideoPaused === false
})
if(excludeSharedContent){
targetTiles = targetTiles.filter(tile =>{return tile.isContent !== true})
}
// rendering flag
const targetIds = targetTiles.reduce<string>((ids,cur)=>{return `${ids}_${cur.boundAttendeeId}`},"")
const targetNames = Object.values(attendees).reduce<string>((names,cur)=>{return `${names}_${cur.name}`},"")
const targetVideoStates:VideoState[] = Object.values(attendees).map(x=>{
if(!videoTileStates[x.attendeeId]){
return "NOT_SHARE"
}
if(x.isVideoPaused){
return "PAUSED"
}else{
return "ENABLED"
}
})
const targetVideoStatesString = targetVideoStates.reduce<string>((states, cur)=>{return `${states}_${cur}`}, "")
const cols = Math.min(Math.ceil(Math.sqrt(targetTiles.length)), 5)
const rows = Math.ceil(targetTiles.length / cols)
const grid = useMemo(()=>{
return(
<GridList cellHeight='auto' className={classes.gridList} cols={ cols }>
{targetTiles.map((tile) => {
const idPrefix = `drawable-videotile-${tile.boundAttendeeId}`
return (
<GridListTile key={tile.boundAttendeeId} cols={1}>
<DrawableVideoTile key={idPrefix} idPrefix={idPrefix} idSuffix="GridView" tile={tile} width={width/cols} height={height/rows}/>
<GridListTileBar2 style={{background:tile.boundAttendeeId === activeSpeakerId?"#ee7777cc":"#777777cc"}} title={getUserNameByAttendeeIdFromList(tile.boundAttendeeId?tile.boundAttendeeId:"")} />
</GridListTile>
)
})}
</GridList>
)
},[targetIds, targetNames, targetVideoStatesString]) // eslint-disable-line
return (
<>
{grid}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/components/CreditPanel.tsx | import React, { useMemo } from 'react';
export const CreditPanel = () => {
const credit = useMemo(()=>{
return(
<div style={{display:"flex", flexDirection:"column"}}>
<div>
Powered by <a href="https://www.flect.co.jp/" rel="noopener noreferrer" target="_blank">FLECT</a>.
</div>
<div>
<a href="https://github.com/w-okada/flect-chime-sdk-demo" rel="noopener noreferrer" target="_blank">github</a>
</div>
</div>
)
},[])
return (
<>
<div style={{color:"burlywood"}}>
Credit
</div>
<div style={{marginLeft:"15pt"}}>
{credit}
</div>
</>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useWindowSizeChange.ts | import { useEffect, useState } from "react";
const getWidth = () =>document.documentElement.clientWidth || document.body.clientWidth;
const getHeight = () => document.documentElement.clientHeight || document.body.clientHeight;
export const useWindowSizeChangeListener = () =>{
const [screenWidth, setScreenWidth] = useState(getWidth())
const [screenHeight, setScreenHeight ] = useState(getHeight())
useEffect(()=>{
const resizeListener = () => {
setScreenWidth(getWidth())
setScreenHeight(getHeight())
};
window.addEventListener('resize', resizeListener)
return () => {
window.removeEventListener('resize', resizeListener)
}
},[])
return {screenWidth, screenHeight}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/WhiteboardPanel.tsx | <reponame>diitalk/flect-chime-sdk-demo
import { Button, Slider, Tooltip, Typography } from "@material-ui/core";
import React from "react";
import { DrawingData } from "../../../../providers/hooks/WebSocketApp/helper/WebSocketWhiteBoardClient";
import {FiberManualRecord, RadioButtonUnchecked } from '@material-ui/icons'
import { useAppState } from "../../../../providers/AppStateProvider";
import { useStyles } from "./css";
const colors = [
'red',
'orange',
'olive',
'green',
'teal',
'blue',
'violet',
'purple',
'pink',
'brown',
'grey',
'black',
]
export const WhiteboardPanel = () => {
const classes = useStyles();
const {setDrawingStroke, setDrawingMode, setLineWidth, drawingMode, drawingStroke, lineWidth, addDrawingData} = useAppState()
return (
<div className={classes.root}>
<Typography className={classes.title} color="textSecondary">
This feature can be used currently only in 'Feature View'.
</Typography>
<Typography className={classes.title} color="textSecondary">
Color and Erase
</Typography>
{colors.map((color) => (
<Tooltip title={color} key={color} >
<FiberManualRecord className={drawingMode==="DRAW" &&drawingStroke===color?classes.selectedColor:classes.color} style={{color:color}} onClick={()=>{
setDrawingStroke(color)
setDrawingMode("DRAW")
}}/>
</Tooltip>
))}
<span className={classes.margin} />
<Tooltip title="erase" >
<RadioButtonUnchecked className={drawingMode==="ERASE"?classes.selectedColor:classes.color} style={{color:"black"}} onClick={()=>{
setDrawingMode("ERASE")
}}/>
</Tooltip>
<div className={classes.volumeControl}>
linewidth
<div className={classes.margin} />
<Slider value={lineWidth} onChange={(e,v)=>{setLineWidth( Array.isArray(v) ? v[0] : v)}} min={1} max={20} step={1} />
<div className={classes.margin} />
</div>
<Button variant="outlined" size="small" color="primary" className={classes.margin} onClick={() => {
const drawingData: DrawingData = {
drawingCmd: "CLEAR",
startXR: 0,
startYR: 0,
endXR: 0,
endYR: 0,
stroke: "black",
lineWidth: 2
}
if(addDrawingData){
addDrawingData(drawingData)
}else{
console.log("[WhiteboardPanel] addDrawingData is undefined",addDrawingData)
}
}}>
Clear
</Button>
</div>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/FullScreenView.tsx | <filename>frontend3/src/pages/023_meetingRoom/components/ScreenView/FullScreenView.tsx
import React, { useMemo } from "react";
import { useAppState } from "../../../../providers/AppStateProvider";
import { FocustTarget, PictureInPictureType } from "./const";
import { DrawableVideoTile } from "./DrawableVideoTile";
type FullScreenProps = {
pictureInPicture: PictureInPictureType
focusTarget: FocustTarget
width:number
height:number
};
export const FullScreenView = ({ pictureInPicture, focusTarget, width, height}: FullScreenProps) => {
// const classes = useStyles()
const { videoTileStates, activeSpeakerId } = useAppState()
const contentsTiles = Object.values(videoTileStates).filter(tile=>{return tile.isContent})
const activeSpekerTile = activeSpeakerId && videoTileStates[activeSpeakerId] ? videoTileStates[activeSpeakerId] : null
const targetTiles = contentsTiles.length > 0 ? contentsTiles : [activeSpekerTile]
const targetTile1 = targetTiles[0] ? targetTiles[0] : null
const targetTile2 = targetTiles[1] ? targetTiles[1] : null
const view = useMemo(()=>{
const targetTiles = [targetTile1, targetTile2].filter(tile => tile != null)
const contentWidth = width/targetTiles.length
console.log("[VideoTileFeatureView] render view")
return(
<div style={{display:"flex", flexWrap:"nowrap", width:`${width}px`, height:`${height}px`, objectFit:"contain", position:"absolute"}}>
{targetTiles.map((tile,index)=>{
if(!tile){
return <div key={index}>no share contets, no active speaker</div>
}
const idPrefix = `drawable-videotile-${tile.boundAttendeeId}`
return <DrawableVideoTile key={idPrefix} idPrefix={idPrefix} tile={tile} width={contentWidth} height={height}/>
})}
</div>
)
},[targetTile1, targetTile2, width, height])
return(<>{view}</>)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/observers/DeviceChangeObserverImpl.ts | import { DeviceChangeObserver } from "amazon-chime-sdk-js"
export class DeviceChangeObserverImpl implements DeviceChangeObserver {
audioInputsChanged(_freshAudioInputDeviceList: MediaDeviceInfo[]): void {
console.log("audioInputsChanged", _freshAudioInputDeviceList)
//this.populateAudioInputList();
}
audioOutputsChanged(_freshAudioOutputDeviceList: MediaDeviceInfo[]): void {
console.log("audioOutputsChanged", _freshAudioOutputDeviceList)
//this.populateAudioOutputList();
}
videoInputsChanged(_freshVideoInputDeviceList: MediaDeviceInfo[]): void {
console.log("videoInputsChanged", _freshVideoInputDeviceList)
//this.populateVideoInputList();
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/api/api.ts | <filename>frontend3/src/api/api.ts
import { BASE_URL } from '../Config'
import { LocalLogger } from '../utils/localLogger'
const logger = new LocalLogger("API")
type CreateMeetingRequest = {
meetingName: string
region: string
}
type JoinMeetingRequest = {
meetingName: string
attendeeName: string
}
type EndMeetingRequest = {
}
/**
* 1. Create meeting
* @param meetingName
* @param region
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const createMeeting = async (meetingName: string, region: string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ created: boolean, meetingName: string, meetingId: string }> =>{
const url = `${BASE_URL}meetings`
const request: CreateMeetingRequest = {
meetingName: encodeURIComponent(meetingName),
region: region,
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
});
const data = await response.json();
const { created, meetingId } = data;
logger.log("createMeeting", data)
return { created, meetingId, meetingName };
}
/**
* 2. Join Meeting
* @param meetingName
* @param userName
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const joinMeeting = async (meetingName: string, userName: string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ MeetingName: string, Meeting: any, Attendee: any, code?: string }> => { // 公式でもMeetingとAttendeeはanyで定義されている。
const url = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees`
const attendeeName = userName // TODO:
const request:JoinMeetingRequest = {
meetingName: encodeURIComponent(meetingName),
attendeeName: encodeURIComponent(attendeeName),
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
if (data === null) {
throw new Error(`Server error: Join Meeting Failed`);
}
return data;
}
/**
* 3. end meeting
* @param meetingName
* @param userName
* @param userId
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const endMeeting = async (meetingName: string, idToken: string, accessToken: string, refreshToken: string) => {
const encodedMeetingName = encodeURIComponent(meetingName)
const url = `${BASE_URL}meetings/${encodedMeetingName}`
const request:EndMeetingRequest ={}
const requestBody = JSON.stringify(request)
const response = await fetch(url,{
method: 'DELETE',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
});
if (!response.ok) {
throw new Error('Server error ending meeting');
}
}
/**
* 4. get user info
* @param meetingName
* @param attendeeId
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const getUserNameByAttendeeId = async (meetingName: string, attendeeId: string, idToken: string, accessToken: string, refreshToken: string) => {
const attendeeUrl = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees/${encodeURIComponent(attendeeId)}`
const res = await fetch(attendeeUrl, {
method: 'GET',
headers: {
"Authorization": idToken,
"X-Flect-Access-Token": accessToken
}
});
if (!res.ok) {
throw new Error('Invalid server response');
}
const data = await res.json();
console.log("getUserNameByAttendeeId", data)
return {
name: decodeURIComponent(data.AttendeeName),
result: data.result
};
}
/**
* 5. List attendees *** maybe return attendee history. not current attendee???***
* @param meetingName
* @param attendeeId
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const getAttendeeList = async (meetingName: string, idToken: string, accessToken: string, refreshToken: string) => {
const attendeeUrl = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees`
const res = await fetch(attendeeUrl, {
method: 'GET',
headers: {
"Authorization": idToken,
"X-Flect-Access-Token": accessToken
}
});
if (!res.ok) {
throw new Error('Invalid server response');
}
const data = await res.json();
console.log(data)
return {
name: decodeURIComponent(data.UserName),
result: data.result
};
}
/**
* 6. generateOnetimeCode
* @param meetingName
* @param attendeeId
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const generateOnetimeCode = async (meetingName: string, attendeeId: string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ uuid: string, code: string, ontimecodeExpireDate:number }> => {
const url = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees/${encodeURIComponent(attendeeId)}/operations/generate-onetime-code`
const request = {
meetingName: encodeURIComponent(meetingName),
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
if (data === null) {
throw new Error(`Server error: Join Meeting Failed`);
}
return data;
}
export type OnetimeCodeInfo = {
uuid: string,
codes: string[],
status:string,
meetingName:string,
attendeeId:string,
}
/**
* 7. singinWithOnetimeCodeRequest
* @param meetingName
* @param attendeeId
* @param uuid
*/
export const singinWithOnetimeCodeRequest = async (meetingName:string, attendeeId:string, uuid:string):
Promise<OnetimeCodeInfo> => {
const url = `${BASE_URL}operations/onetime-code-signin-request`
const request = {
uuid:uuid,
meetingName: meetingName,
attendeeId: attendeeId,
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
);
const data = await response.json();
console.log("[singinWithOnetimeCodeRequest]",data)
if (data === null) {
throw new Error(`Server error: Join Meeting Failed`);
}
return data;
}
export type OnetimeCodeSigninResult = {
result:boolean,
idToken?:string,
accessToken?:string,
attendeeName?: string,
}
/**
* 8, singinWithOnetimeCode
* @param meetingName
* @param attendeeId
* @param uuid
* @param code
*/
export const singinWithOnetimeCode = async (meetingName:string, attendeeId:string, uuid:string, code:string):
Promise<OnetimeCodeSigninResult> => {
const url = `${BASE_URL}operations/onetime-code-signin`
const request = {
uuid:uuid,
meetingName: meetingName,
attendeeId: attendeeId,
code: code,
}
const requestBody = JSON.stringify(request)
try{
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const data = await response.json();
console.log("[singinWithOnetimeCode]",data)
if (data === null) {
throw new Error(`Server error: Join Meeting Failed`);
}
return data;
}catch(exception){
console.log("[onetimecode] exception:", exception.message)
console.log("[onetimecode] exception: ", JSON.stringify(exception.message))
}
return {
result:false,
idToken:"",
accessToken:"",
attendeeName: "",
}
}
/**
* 9. startManager
* @param meetingName
* @param attendeeId
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const startManager = async (meetingName: string, attendeeId: string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ code: string, url:string }> => {
const url = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees/${encodeURIComponent(attendeeId)}/operations/start-manager`
const request = {
meetingName: encodeURIComponent(meetingName),
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
console.log("START MANAGER:", data)
if (data === null) {
throw new Error(`Server error: startManager failed`);
}
return data;
}
/**
* 10. getMeetingInfo
* @param meetingName
* @param idToken
* @param accessToken
* @param refreshToken
*/
export const getMeetingInfo = async(meetingName: string, idToken: string, accessToken: string, refreshToken: string) => {
const url = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}`
const response = await fetch(url, {
method: 'GET',
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
console.log("getMeetingInfo res:", data)
if (data === null) {
throw new Error(`Server error: get meeting info failed`);
}
return data;
}
/**
* x1. getManagerInfo
* @param meetingName
* @param attendeeId
* @param uuid
* @param code
*/
export const getManagerInfo = async (meetingName: string, attendeeId: string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ code: string, publicIp:string, lastStatus:string, desiredStatus:string}> => {
const url = `${BASE_URL}meetings/${encodeURIComponent(meetingName)}/attendees/${encodeURIComponent(attendeeId)}/operations/get-manager-info`
const request = {
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
console.log("[getManagerInfo]",data)
return data;
}
/**
* x1. get presigned url
* @param meetingName
* @param attendeeId
* @param uuid
* @param code
*/
export const getPresignedURL = async (key:string, idToken: string, accessToken: string, refreshToken: string):
Promise<{ result:string, url: string, fields:{[key:string]:string} }> => {
const url = `${BASE_URL}operations/generate-s3-presigned-url`
const request = {
key: key
}
const requestBody = JSON.stringify(request)
const response = await fetch(url, {
method: 'POST',
body: requestBody,
headers: {
"Authorization": idToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-Flect-Access-Token": accessToken
}
}
);
const data = await response.json();
console.log("[getPresignedURL]",data)
return data;
}
// /**
// * x1. update among us service
// * @param meetingName
// * @param attendeeId
// * @param uuid
// * @param code
// */
// export const updateAmongUsService = async (desiredCount:number):
// Promise<OnetimeCodeSigninResult> => {
// const url = `${BASE_URL}operations/update-amongus-service`
// const request = {
// desiredCount:desiredCount
// }
// const requestBody = JSON.stringify(request)
// const response = await fetch(url, {
// method: 'POST',
// body: requestBody,
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json',
// }
// }
// );
// const data = await response.json();
// console.log("[updateAmongUsService]",data)
// return data;
// }
// /**
// * x1. update among us service
// * @param meetingName
// * @param attendeeId
// * @param uuid
// * @param code
// */
// export const listAmongUsService = async ():
// Promise<OnetimeCodeSigninResult> => {
// const url = `${BASE_URL}operations/list-amongus-service`
// const request = {
// }
// const requestBody = JSON.stringify(request)
// const response = await fetch(url, {
// method: 'POST',
// body: requestBody,
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json',
// }
// }
// );
// const data = await response.json();
// console.log("[updateAmongUsService]",data)
// return data;
// }
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/AttendeesTable.tsx | <reponame>diitalk/flect-chime-sdk-demo<filename>frontend3/src/pages/023_meetingRoom/components/sidebars/AttendeesTable.tsx
import React, { useMemo } from 'react';
import { useAppState } from '../../../../providers/AppStateProvider';
import { useStyles } from './css';
import { IconButton, Tooltip } from '@material-ui/core';
import VideocamIcon from '@material-ui/icons/Videocam';
import VideocamOffIcon from '@material-ui/icons/VideocamOff';
// type Order = 'asc' | 'desc';
// const descendingComparator = <T extends {}>(a: T, b: T, orderBy: keyof T) => {
// if (b[orderBy] < a[orderBy]) {
// return -1;
// }
// if (b[orderBy] > a[orderBy]) {
// return 1;
// }
// return 0;
// }
// function getComparator<Key extends keyof any>(
// order: Order,
// orderBy: Key,
// ): (a: { [key in Key]: number | string | boolean | HTMLVideoElement | null }, b: { [key in Key]: number | string | boolean | HTMLVideoElement | null }) => number {
// if(order === 'desc'){
// return (a, b) => descendingComparator(a, b, orderBy)
// }else{
// return (a, b) => -descendingComparator(a, b, orderBy)
// }
// }
// function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) {
// const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
// stabilizedThis.sort((a, b) => {
// const order = comparator(a[0], b[0]);
// if (order !== 0) return order;
// return a[1] - b[1];
// });
// return stabilizedThis.map((el) => el[0]);
// }
// interface HeadCell {
// disablePadding: boolean;
// id: keyof AttendeeState;
// label: string;
// numeric: boolean;
// }
// const headCells: HeadCell[] = [
// { id: 'name', numeric: false, disablePadding: true, label: 'userName' },
// { id: 'muted', numeric: false, disablePadding: true, label: 'mute' },
// ];
// interface EnhancedTableProps {
// onRequestSort: (property: keyof AttendeeState) => void;
// order: Order;
// orderBy: string;
// }
// const EnhancedTableHead = (props: EnhancedTableProps) => {
// const classes = useStyles();
// const { order, orderBy, onRequestSort } = props;
// const createSortHandler = (property: keyof AttendeeState) => {
// return (event: React.MouseEvent<unknown>) => { onRequestSort(property); }
// };
// const header = useMemo(() => {
// return (
// <TableHead>
// <TableRow>
// {headCells.map((headCell) => (
// <TableCell
// key={headCell.id}
// align={headCell.numeric ? 'right' : 'left'}
// padding={headCell.disablePadding ? 'none' : 'default'}
// sortDirection={orderBy === headCell.id ? order : false}
// >
// <TableSortLabel
// active={orderBy === headCell.id}
// direction={orderBy === headCell.id ? order : 'asc'}
// onClick={createSortHandler(headCell.id)}
// >
// {headCell.label}
// {orderBy === headCell.id ? (
// <span className={classes.visuallyHidden}>
// {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
// </span>
// ) : null}
// </TableSortLabel>
// </TableCell>
// ))}
// </TableRow>
// </TableHead>
// )
// }, [orderBy, order, createSortHandler]) // eslint-disable-line
// return <>{header}</>;
// }
// export const AttendeesTable_old = () => {
// const classes = useStyles();
// const {attendees} = useAppState()
// const [order, setOrder] = React.useState<Order>('asc');
// const [orderBy, setOrderBy] = React.useState<keyof AttendeeState>('name');
// const [rowsPerPage] = React.useState(400);
// const handleRequestSort = (property: keyof AttendeeState)=>{
// if(orderBy === property){
// setOrder(order === 'asc' ? 'desc' : 'asc');
// }else{
// setOrderBy(property)
// }
// }
// const table = useMemo(()=>{
// return(
// <TableContainer className={classes.container}>
// <Table stickyHeader className={classes.table} size='small'>
// <EnhancedTableHead order={order} orderBy={orderBy} onRequestSort={handleRequestSort} />
// <TableBody>
// {stableSort(Object.values(attendees), getComparator(order, orderBy))
// .slice(0, rowsPerPage)
// .map((row, index) => {
// const labelId = `enhanced-table-checkbox-${index}`;
// return (
// <TableRow
// hover
// role="checkbox"
// tabIndex={-1}
// key={row.attendeeId}
// >
// <TableCell component="th" id={labelId} scope="row" padding="none">
// {row.name.length > 10 ?
// row.name.substring(0, 10) + "... "
// :
// row.name
// }
// </TableCell>
// <TableCell component="th" id={labelId} scope="row" padding="none">
// {row.muted}
// </TableCell>
// </TableRow>
// );
// })}
// </TableBody>
// </Table>
// </TableContainer>
// )
// },[attendees, order, orderBy]) // eslint-disable-line
// return (
// <div className={classes.root}>
// {table}
// </div>
// );
// }
type VideoState = "ENABLED" | "PAUSED" | "NOT_SHARE"
export const AttendeesTable = () => {
const classes = useStyles()
const {attendees, videoTileStates, setPauseVideo} = useAppState()
const targetIds = Object.values(videoTileStates).reduce<string>((ids,cur)=>{return `${ids}_${cur.boundAttendeeId}`},"")
const targetNames = Object.values(attendees).reduce<string>((names,cur)=>{return `${names}_${cur.name}`},"")
const targetVideoStates:VideoState[] = Object.values(attendees).map(x=>{
if(!videoTileStates[x.attendeeId]){
return "NOT_SHARE"
}
if(x.isVideoPaused){
return "PAUSED"
}else{
return "ENABLED"
}
})
const targetVideoStatesString = targetVideoStates.reduce<string>((states, cur)=>{return `${states}_${cur}`}, "")
const audienceList = useMemo(()=>{
const l = Object.values(attendees).map((x, index)=>{
let videoStateComp
switch(targetVideoStates[index]){
case "ENABLED":
videoStateComp = (
<Tooltip title={`click to pause`}>
<IconButton style={{width: "20px", height:"20px"}} onClick={ ()=>{setPauseVideo(x.attendeeId, true)} } >
<VideocamIcon></VideocamIcon>
</IconButton>
</Tooltip>
)
break
case "PAUSED":
videoStateComp = (
<Tooltip title={`click to play`}>
<IconButton style={{width: "20px", height:"20px"}} onClick={ ()=>{setPauseVideo(x.attendeeId, false)} } >
<VideocamOffIcon ></VideocamOffIcon>
</IconButton>
</Tooltip>
)
break
case "NOT_SHARE":
videoStateComp = <></>
break
}
return(
<>
<div style={{display:"flex", flexDirection:"row"}}>
<Tooltip title={`${x.attendeeId}`}>
<div>
{x.name}
</div>
</Tooltip>
<div>
{videoStateComp}
</div>
</div>
</>
)
})
return(
<div style={{display:"flex", flexDirection:"column"}}>
{l}
</div>
)
},[targetIds, targetNames, targetVideoStatesString])
return(
<>
<div style={{marginLeft:"15pt"}}>
{audienceList}
</div>
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/WebSocketApp/helper/WebSocketClient.ts | <reponame>diitalk/flect-chime-sdk-demo
import { DefaultWebSocketAdapter, Logger, WebSocketAdapter, WebSocketReadyState } from "amazon-chime-sdk-js";
export type WebSocketMessage = {
action: string
topic: string
senderId: string
data: any
}
const listener:{[topic:string]:((wsMessages:WebSocketMessage[])=>void)[]} = {}
const wsMessages:{[topic:string]:WebSocketMessage[]} = {}
export class WebSocketClient{
//// CHANGE: This class is no more SINGLETON. Other WSS URL can be used.
// private static _instance:WebSocketClient
// public static getInstance(attendeeId:string, messagingURLWithQuery:string, logger:Logger){
// if(!this._instance){
// this._instance = new WebSocketClient(attendeeId, messagingURLWithQuery, logger)
// }
// return this._instance
// }
// private wsMessages:{[topic:string]:WebSocketMessage[]} = {}
// private wsMessages:{[topic:string]:WebSocketMessage[]} = {}
private attendeeId:string
private messagingURLWithQuery:string
private logger:Logger
private websocketAdapter:WebSocketAdapter|null = null
private recreate:()=>void
constructor(attendeeId:string, messagingURLWithQuery:string, logger:Logger, recreate:()=>void){
console.log("NEW WEBSOCKET CLIENT")
this.attendeeId = attendeeId
this.messagingURLWithQuery = messagingURLWithQuery
this.logger = logger
this.recreate = recreate
}
connect = () =>{
this.websocketAdapter = new DefaultWebSocketAdapter(this.logger)
this.websocketAdapter.create(
this.messagingURLWithQuery,
[]
)
this.websocketAdapter.addEventListener('message', this.receiveMessage)
this.websocketAdapter.addEventListener('close', this.reconnect)
// this.websocketAdapter.addEventListener('error', this.reconnect)
console.log("WebSocket Created!!", this.websocketAdapter, (new Date()).toLocaleTimeString())
}
// private listener:{[topic:string]:((wsMessages:WebSocketMessage[])=>void)[]} = {}
// addEventListener = (topic:string, f:(wsMessages:WebSocketMessage[])=>void) =>{
// if(!this.listener[topic]){
// this.listener[topic] = []
// }
// this.listener[topic].push(f)
// // console.log("Listener", this.listener)
// }
// removeEventListener = (topic:string, f:(wsMessages:WebSocketMessage[])=>void) =>{
// if(this.listener[topic]){
// this.listener[topic] = this.listener[topic].filter(x=>x!==f)
// }
// }
addEventListener = (topic:string, f:(wsMessages:WebSocketMessage[])=>void) =>{
if(!listener[topic]){
listener[topic] = []
}
listener[topic].push(f)
// console.log("Listener", this.listener)
}
removeEventListener = (topic:string, f:(wsMessages:WebSocketMessage[])=>void) =>{
if(listener[topic]){
listener[topic] = listener[topic].filter(x=>x!==f)
}
}
reconnect = (e:Event) => {
// setTimeout(()=>{
console.log("reconnecting... ", e, (new Date()).toLocaleTimeString())
this.recreate()
// this.websocketAdapter = new DefaultWebSocketAdapter(this.logger)
// this.websocketAdapter!.create(
// this.messagingURLWithQuery,
// []
// )
// this.websocketAdapter!.addEventListener('message', this.receiveMessage)
// this.websocketAdapter!.addEventListener('close', this.reconnect)
// },1*1000)
}
receiveMessage = (e:Event) => {
// console.log("receive message", this.listener)
console.log("receive message", listener)
const event = e as MessageEvent
const message = JSON.parse(event.data) as WebSocketMessage
// specify topic name
const topic = message.topic
this.updateWSMessageData(topic, message)
}
updateWSMessageData = (topic:string, wsMessage:WebSocketMessage) =>{
// update buffer
if(!wsMessages[topic]){
wsMessages[topic] = []
}
wsMessages[topic] = [...wsMessages[topic], wsMessage ]
// notify
// if(this.listener[topic]){
// this.listener[topic].forEach(messageReceived=>{
// messageReceived(this.wsMessages[topic])
// })
// }
if(listener[topic]){
listener[topic].forEach(messageReceived=>{
messageReceived(wsMessages[topic])
})
}
}
sendMessage = (topic:string,data:any) =>{
const mess:WebSocketMessage = {
action : 'sendmessage',
senderId: this.attendeeId,
topic: topic,
data: data
}
const message = JSON.stringify(mess)
try{
if(this.websocketAdapter?.readyState() === WebSocketReadyState.Open || this.websocketAdapter?.readyState() === WebSocketReadyState.Connecting){
const res = this.websocketAdapter!.send(message)
console.log("send data(ws):", message.length, "sending result:", res)
}else{
throw("adapter is not open")
}
}catch(excpetion){
console.log("send data(ws) Exception:", message.length, excpetion)
this.recreate()
}
}
loopbackMessage = (topic:string,data:any) =>{
const mess:WebSocketMessage = {
action : 'sendmessage',
senderId: this.attendeeId,
topic: topic,
data: data
}
this.updateWSMessageData(topic, mess)
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/RealtimeSubscribers/useRealtimeSubscribeHMM.ts |
import { DefaultMeetingSession, DataMessage } from "amazon-chime-sdk-js";
import { useEffect, useMemo, useState } from "react";
import { RealtimeData, RealtimeDataApp} from "./const";
import { v4 } from 'uuid';
import { LocalLogger } from "../../../utils/localLogger";
import { getManagerInfo, startManager } from "../../../api/api";
import { GameState, useAmongUs } from "./useAmongUs";
export const HMMCmd = {
START_RECORD : "START_RECORD",
STOP_RECORD : "STOP_RECORD",
// START_RECORD_TILEVIEW : "START_RECORD_TILEVIEW",
// STOP_RECORD_TILEVIEW : "STOP_RECORD_TILEVIEW",
START_SHARE_TILEVIEW : "START_SHARE_TILEVIEW",
STOP_SHARE_TILEVIEW : "STOP_SHARE_TILEVIEW",
TERMINATE : "TERMINATE",
NOTIFY_STATUS : "NOTIFY_STATUS",
NOTIFY_AMONGUS_STATUS: "NOTIFY_AMONGUS_STATUS",
REGISTER_AMONGUS_USER_NAME:"REGISTER_AMONGUS_USER_NAME",
} as const
export type HMMStatus = {
active: boolean
recording: boolean
shareTileView: boolean
}
export type AmongUsStatus = {
event: string,
data: string
}
export type HMMMessage = {
command: keyof typeof HMMCmd,
data?: any
}
type UseRealtimeSubscribeHMMProps = {
meetingSession?:DefaultMeetingSession
attendeeId:string
meetingName?: string
idToken?: string
accessToken?: string
refreshToken?: string
}
const logger = new LocalLogger("useRealtimeSubscribeHMM")
export const useRealtimeSubscribeHMM = (props: UseRealtimeSubscribeHMMProps) =>{
const meetingSession = useMemo(()=>{
return props.meetingSession
},[props.meetingSession])
const attendeeId = useMemo(()=>{
return props.attendeeId
},[props.attendeeId])
const [ hMMCommandData, setHMMComandData] = useState<RealtimeData[]>([])
const [ publicIp, setPublicIp] = useState<string>("")
const [ startRecordingCounter, setStartRecordingCounter] = useState(0)
const [ stopRecordingCounter, setStopRecordingCounter] = useState(0)
const [ startShareTileViewCounter, setStartShareTileViewCounter ] = useState(0)
const [ stopShareTileViewCounter, setSopShareTileViewCounter ] = useState(0)
const [ terminateCounter, setTerminateCounter] = useState(0)
const { gameState, updateGameState, registerUserName } = useAmongUs({
meetingName:props.meetingName,
attendeeId:props.attendeeId,
idToken:props.idToken,
accessToken:props.accessToken,
refreshToken:props.refreshToken}) // for hmm
const [ currentGameState, setCurrentGameState ] = useState<GameState>(gameState) // for each client
const [ hMMStatus, setHMMStatus] = useState<HMMStatus>({
active:false,
recording:false,
shareTileView:false,
})
const [ stateLastUpdate, setStateLastUpdate] = useState(new Date().getTime())
const startHMM = async () =>{
const res = await startManager(props.meetingName!, attendeeId!, props.idToken!, props.accessToken!, props.refreshToken!)
console.log("startHMM RES:",res)
setHMMComandData([])
}
const updateHMMInfo = async () =>{
const res = await getManagerInfo(props.meetingName!, attendeeId!, props.idToken!, props.accessToken!, props.refreshToken!)
const publicIp = res.publicIp
const lastStatus = res. lastStatus
setPublicIp(publicIp)
}
const sendStartRecord = () => {
sendHMMCommand( {command: HMMCmd.START_RECORD} )
}
const sendStopRecord = () => {
sendHMMCommand( {command: HMMCmd.STOP_RECORD} )
}
const sendStartShareTileView = () => {
sendHMMCommand( {command: HMMCmd.START_SHARE_TILEVIEW} )
}
const sendStopShareTileView = () => {
sendHMMCommand( {command: HMMCmd.STOP_SHARE_TILEVIEW} )
}
const sendTerminate = () =>{
sendHMMCommand( {command: HMMCmd.TERMINATE} )
}
const sendHMMStatus = (active:boolean, recording:boolean, shareTileView:boolean) =>{
const status:HMMStatus = {
active,
recording,
shareTileView
}
sendHMMCommand({command:HMMCmd.NOTIFY_STATUS, data:status})
}
// const sendAmongUsStatus = (event:string, data:string) =>{
// const status:AmongUsStatus = {
// event,
// data
// }
// console.log(`AMONGUS SEND STATUS: ${event}, ${data}`)
// sendHMMCommand({command:HMMCmd.NOTIFY_AMONGUS_STATUS, data:status})
// }
const sendHMMCommand = (mess: HMMMessage) => {
logger.log(`sendCommand: ${attendeeId}`)
const reatimeData: RealtimeData = {
uuid: v4(),
action: 'sendmessage',
app: RealtimeDataApp.HMM,
data: mess,
createdDate: new Date().getTime(),
senderId: attendeeId
}
meetingSession?.audioVideo!.realtimeSendDataMessage(RealtimeDataApp.HMM , JSON.stringify(reatimeData))
}
const sendRegisterAmongUsUserName = (userName:string, attendeeId:string) =>{
sendHMMCommand({command:HMMCmd.REGISTER_AMONGUS_USER_NAME, data:[userName, attendeeId]})
}
const receiveData = (dataMessage: DataMessage) => {
const senderId = dataMessage.senderAttendeeId
const data = JSON.parse(dataMessage.text()) as RealtimeData
data.senderId = senderId
logger.log(data)
if(hMMCommandData.length === 0){
updateHMMInfo()
}
const mess = data.data as HMMMessage
console.log("RECEIVE REALTIME DATA1 ", mess.command)
switch(mess.command){
case "START_RECORD":
// setRecordingEnable(true)
console.log("RECEIVE REALTIME DATA1", mess)
setStartRecordingCounter(startRecordingCounter+1)
break
case "STOP_RECORD":
console.log("RECEIVE REALTIME DATA2 STOP RECORDER", mess)
// setRecordingEnable(false)
setStopRecordingCounter(stopRecordingCounter+1)
break
case "START_SHARE_TILEVIEW":
console.log("RECEIVE REALTIME DATA3", mess)
// setShareTileViewEnable(true)
setStartShareTileViewCounter(startShareTileViewCounter+1)
break
case "STOP_SHARE_TILEVIEW":
console.log("RECEIVE REALTIME DATA4", mess)
// setShareTileViewEnable(false)
setSopShareTileViewCounter(stopShareTileViewCounter+1)
break
case "TERMINATE":
//setTerminateTriggerd(true)
console.log("RECEIVE REALTIME DATA4", mess)
setTerminateCounter(terminateCounter+1)
break
case "NOTIFY_STATUS":
const status = mess.data as HMMStatus
setHMMStatus(status)
setStateLastUpdate(new Date().getTime())
break
case "NOTIFY_AMONGUS_STATUS": // handle by client
const gameState = mess.data as GameState
console.log("RECEIVE REALTIME DATA2 ", JSON.stringify(gameState))
setCurrentGameState(gameState)
break
case "REGISTER_AMONGUS_USER_NAME": // handle by hmm
const [userName, attendeeId] = mess.data as string[]
console.log("RECEIVE REALTIME DATA2 ", userName, attendeeId)
/// As registerUserName in client, gameState remain initial state, so ignored this update process.
registerUserName(userName, attendeeId)
break
}
setHMMComandData([...hMMCommandData, data])
}
useEffect(() => {
meetingSession?.audioVideo?.realtimeSubscribeToReceiveDataMessage(
RealtimeDataApp.HMM,
receiveData
)
return () => {
meetingSession?.audioVideo?.realtimeUnsubscribeFromReceiveDataMessage(RealtimeDataApp.HMM)
}
})
return {
sendHMMCommand, hMMCommandData, startHMM, updateHMMInfo, publicIp,
sendStartRecord, sendStopRecord, sendStartShareTileView, sendStopShareTileView, sendTerminate, sendHMMStatus, sendRegisterAmongUsUserName,
startRecordingCounter, stopRecordingCounter, startShareTileViewCounter, stopShareTileViewCounter, terminateCounter, hMMStatus, stateLastUpdate,
updateGameState, currentGameState, gameState
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/helper/RendererForRecorder.ts | <filename>frontend3/src/pages/023_meetingRoom/components/ScreenView/helper/RendererForRecorder.ts
import { blueGrey } from "@material-ui/core/colors"
import { MeetingSession } from "amazon-chime-sdk-js"
export class RendererForRecorder {
meetingSession: MeetingSession
alive = true
private dstCanvas:HTMLCanvasElement | null = null
private srcVideos:HTMLVideoElement[] | null = null
private cols = 0
private rows = 0
private maxWidth = 0
private maxHeight = 0
private videoPositions:number[][] = []
private titles:string[] = []
constructor(meetingSession: MeetingSession) {
this.meetingSession = meetingSession
}
init(dstCanvas:HTMLCanvasElement){
this.dstCanvas = dstCanvas
}
start() {
this.alive = true
this.renderVideos()
}
setSrcVideoElements(srcVideos:HTMLVideoElement[]){
this.srcVideos = srcVideos
const videoNum = this.srcVideos.length
// Decide offset and size of each video here
//// Max Size
this.cols = Math.ceil(Math.sqrt(videoNum))
this.rows = Math.ceil(videoNum / this.cols)
this.maxWidth = this.dstCanvas ? this.dstCanvas.width / this.cols : 0
this.maxHeight = this.dstCanvas ? this.dstCanvas.height / this.rows : 0
// //// FitSize
// this.videoPositions = this.srcVideos.map((video, index) =>{
// let rate
// // if(video.videoWidth / video.videoHeight > this.dstCanvas!.width / this.dstCanvas!.height){
// if(video.videoWidth / this.maxWidth > video.videoHeight / this.maxHeight){
// rate = this.maxWidth / video.videoWidth
// }else{
// rate = this.maxHeight / video.videoHeight
// }
// const w = video.videoWidth * rate
// const h = video.videoHeight * rate
// const offset_x_per_area = (this.maxWidth - w) / 2
// const offset_y_per_area = (this.maxHeight - h) / 2
// const global_offset_x = (index % this.cols) * this.maxWidth + offset_x_per_area
// const global_offset_y = Math.floor(index / this.cols) * this.maxHeight + offset_y_per_area
// return [Math.ceil(global_offset_x), Math.ceil(global_offset_y), Math.ceil(w), Math.ceil(h)]
// })
}
setTitles(titles:string[]){
this.titles=titles
}
destroy() {
console.log("destroy renderer!!")
this.alive = false
}
focusVideoElements: HTMLVideoElement[] = []
private renderVideos = () => {
if(!this.dstCanvas){
requestAnimationFrame(() => { this.renderVideos() })
return
}else if(!this.srcVideos || this.srcVideos.length === 0){
const date = new Date();
const utc = date.toUTCString();
const ctx = this.dstCanvas!.getContext("2d")!
ctx.clearRect(0,0,this.dstCanvas!.width,this.dstCanvas!.height)
ctx.fillStyle="#ffffff"
const fontsize = Math.floor(this.dstCanvas!.height / 15)
ctx.font = `${fontsize}px Arial`
ctx.fillText(`${utc}`, this.dstCanvas!.width / 10 , (this.dstCanvas!.height / 10) * 2)
ctx.fillText(`There is no active speaker or no shared contents.`, this.dstCanvas!.width / 10 , (this.dstCanvas!.height / 10) * 3)
requestAnimationFrame(() => { this.renderVideos() })
return
}
const ctx = this.dstCanvas!.getContext("2d")!
ctx.fillStyle="#000000"
ctx.clearRect(0,0,this.dstCanvas!.width,this.dstCanvas!.height)
ctx.fillRect(0,0,this.dstCanvas!.width,this.dstCanvas!.height)
// this.srcVideos.forEach((video,index)=>{
// let rate
// if(video.videoWidth / this.maxWidth > video.videoHeight / this.maxHeight){
// rate = this.maxWidth / video.videoWidth
// }else{
// rate = this.maxHeight / video.videoHeight
// }
// const w = video.videoWidth * rate
// const h = video.videoHeight * rate
// const offset_x_per_area = (this.maxWidth - w) / 2
// const offset_y_per_area = (this.maxHeight - h) / 2
// const global_offset_x = (index % this.cols) * this.maxWidth + offset_x_per_area
// const global_offset_y = Math.floor(index / this.cols) * this.maxHeight + offset_y_per_area
// const position = [Math.ceil(global_offset_x), Math.ceil(global_offset_y), Math.ceil(w), Math.ceil(h)]
// // console.log(">>>>>>>>>>>>>>>",video, position)
// ctx.drawImage(video, position[0], position[1], position[2], position[3])
// if(this.titles[index]){
// let title = this.titles[index]
// ctx.textAlign='left'
// ctx.textBaseline='top'
// const fontsize = Math.ceil(Math.floor(h/ 10))
// ctx.font = `${fontsize}px Arial`
// if(title.length > 10){
// title = title.substring(0,10)
// }
// const textWidth = ctx.measureText(title).width
// ctx.fillStyle="#ffffff99"
// const textAreaposition = [position[0]+5, position[1] + position[3] - fontsize - 5, textWidth, fontsize]
// ctx.fillRect(textAreaposition[0], textAreaposition[1], textAreaposition[2], textAreaposition[3])
// ctx.fillStyle=blueGrey[900]
// ctx.fillText(title, position[0]+5, position[1] + position[3] - fontsize - 5)
// }else{
// let title = "NO TITLE"
// ctx.fillStyle=blueGrey[900]
// const fontsize = Math.ceil(Math.floor(h/ 10))
// ctx.font = `${fontsize}px Arial`
// ctx.fillText(title, position[0]+5, position[1] + position[3] - fontsize - 5)
// }
// })
const promises = this.srcVideos.map((video,index)=>{
const p = new Promise<void>((resolve,reject)=>{
let rate
if(video.videoWidth / this.maxWidth > video.videoHeight / this.maxHeight){
rate = this.maxWidth / video.videoWidth
}else{
rate = this.maxHeight / video.videoHeight
}
const w = video.videoWidth * rate
const h = video.videoHeight * rate
const offset_x_per_area = (this.maxWidth - w) / 2
const offset_y_per_area = (this.maxHeight - h) / 2
const global_offset_x = (index % this.cols) * this.maxWidth + offset_x_per_area
const global_offset_y = Math.floor(index / this.cols) * this.maxHeight + offset_y_per_area
const position = [Math.ceil(global_offset_x), Math.ceil(global_offset_y), Math.ceil(w), Math.ceil(h)]
// console.log(">>>>>>>>>>>>>>>",video, position)
ctx.drawImage(video, position[0], position[1], position[2], position[3])
if(this.titles[index]){
let title = this.titles[index]
ctx.textAlign='left'
ctx.textBaseline='top'
const fontsize = Math.ceil(Math.floor(h/ 10))
ctx.font = `${fontsize}px Arial`
if(title.length > 10){
title = title.substring(0,10)
}
const textWidth = ctx.measureText(title).width
ctx.fillStyle="#ffffff99"
const textAreaposition = [position[0]+5, position[1] + position[3] - fontsize - 5, textWidth, fontsize]
ctx.fillRect(textAreaposition[0], textAreaposition[1], textAreaposition[2], textAreaposition[3])
ctx.fillStyle=blueGrey[900]
ctx.fillText(title, position[0]+5, position[1] + position[3] - fontsize - 5)
}else{
let title = "NO TITLE"
ctx.fillStyle=blueGrey[900]
const fontsize = Math.ceil(Math.floor(h/ 10))
ctx.font = `${fontsize}px Arial`
ctx.fillText(title, position[0]+5, position[1] + position[3] - fontsize - 5)
}
resolve()
})
return p
})
Promise.all(promises).then(()=>{
if (this.alive) {
// console.log("[Recoerder View] request next frame")
requestAnimationFrame(() => { this.renderVideos() })
// setTimeout(this.renderVideos, 50)
} else {
console.log("[Recoerder View] stop request next frame")
}
})
// if (this.alive) {
// // console.log("[Recoerder View] request next frame")
// requestAnimationFrame(() => { this.renderVideos() })
// // setTimeout(this.renderVideos, 50)
// } else {
// console.log("[Recoerder View] stop request next frame")
// }
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/helper/DrawingHelper.ts | <reponame>diitalk/flect-chime-sdk-demo<gh_stars>0
import { DrawingData } from "../../../../../providers/hooks/WebSocketApp/helper/WebSocketWhiteBoardClient"
import { DrawingMode } from "../../../../../providers/hooks/WebSocketApp/useWebSocketWhiteBoard"
const THROTTLE_MSEC = 20
export class DrawingHelper{
private inDrawing = false
private previousPosition = [0, 0]
private lastSendingTime = 0
private _drawingStroke = ""
private _lineWidth = 3
private _drawingMode:keyof typeof DrawingMode = "DISABLE"
set drawingStroke(val:string){this._drawingStroke = val}
set lineWidth(val:number){this._lineWidth = val}
set drawingMode(val:keyof typeof DrawingMode){this._drawingMode = val}
private canvasId
constructor(canvasId:string){
this.canvasId = canvasId
}
addDrawingData: ((data: DrawingData) => void) | undefined = (data:DrawingData)=>{}
drawingStart = (e: MouseEvent) =>{
this.inDrawing = true
this.previousPosition = [e.offsetX, e.offsetY]
}
drawingEnd = (e: MouseEvent) => {
this.inDrawing = false
}
drawing = (e: MouseEvent) => {
if (Date.now() - this.lastSendingTime < THROTTLE_MSEC) {
return
}
if (this.inDrawing) {
const startX = this.previousPosition[0]
const startY = this.previousPosition[1]
const endX = e.offsetX
const endY = e.offsetY
const drawingData = this.generateDrawingData(e, startX, startY, endX, endY)
this.lastSendingTime = Date.now()
this.previousPosition = [e.offsetX, e.offsetY]
this.addDrawingData!(drawingData)
}
}
private generateDrawingData = (e:MouseEvent|TouchEvent, startX: number, startY: number, endX: number, endY: number) => {
const source = e.target as HTMLCanvasElement
const cs = getComputedStyle(source)
const width = parseInt(cs.getPropertyValue("width"))
const height = parseInt(cs.getPropertyValue("height"))
const rateX = width / source.width
const rateY = height / source.height
let drawingData: DrawingData
if(rateX > rateY){ // widthにあまりがある
const trueWidth = source.width * rateY
const trueHeight = source.height * rateY
const restW = (width - trueWidth) / 2
const startXR = (startX - restW) / trueWidth
const startYR = startY / trueHeight
const endXR = (endX - restW) / trueWidth
const endYR = endY / trueHeight
drawingData = {
drawingCmd: this._drawingMode === "DRAW" ? "DRAW" : "ERASE" ,
startXR: startXR,
startYR: startYR,
endXR: endXR,
endYR: endYR,
stroke: this._drawingStroke,
lineWidth: this._lineWidth,
canvasId: this.canvasId
}
}else{ // heightにあまりがある
const trueWidth = source.width * rateX
const trueHeight = source.height * rateX
const restH = (height - trueHeight) / 2
const startXR = startX / trueWidth
const startYR = (startY - restH) / trueHeight
const endXR = endX / trueWidth
const endYR = (endY - restH) / trueHeight
drawingData = {
drawingCmd: this._drawingMode === "DRAW" ? "DRAW" : "ERASE" ,
startXR: startXR,
startYR: startYR,
endXR: endXR,
endYR: endYR,
stroke: this._drawingStroke,
lineWidth: this._lineWidth,
canvasId: this.canvasId
}
}
return drawingData
}
touchStart = (e: TouchEvent) => {
this.inDrawing = true
const source = e.target as HTMLCanvasElement
const x = e.changedTouches[0].clientX - source.getBoundingClientRect().left
const y = e.changedTouches[0].clientY - source.getBoundingClientRect().top
this.previousPosition = [x, y]
}
touchEnd = (e: TouchEvent) => {
this.inDrawing = false
}
touchMove = (e: TouchEvent) => {
e.preventDefault();
const source = e.target as HTMLCanvasElement
if (Date.now() - this.lastSendingTime < THROTTLE_MSEC) {
return
}
if (this.inDrawing) {
const startX = this.previousPosition[0]
const startY = this.previousPosition[1]
const endX = e.changedTouches[0].clientX - source.getBoundingClientRect().left
const endY = e.changedTouches[0].clientY - source.getBoundingClientRect().top
const drawingData = this.generateDrawingData(e, startX, startY, endX, endY)
this.lastSendingTime = Date.now()
this.previousPosition = [endX, endY]
this.addDrawingData!(drawingData)
}
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/RealtimeSubscribers/const.ts | <reponame>diitalk/flect-chime-sdk-demo
type RealtimeDataAction = "sendmessage"
export const RealtimeDataApp = {
CHAT:"CHAT",
WHITEBOARD:"WHITEBOARD",
HMM: "HMM" //HEADLESS_MEETING_MANAGER
} as const
export type RealtimeData = {
uuid : string
senderId : string // for remember the sender. (copied from DataMessage to RealtimeData)
createdDate : number
action : RealtimeDataAction
app : keyof typeof RealtimeDataApp
data : any
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/FeatureEnabler.tsx | import { IconButton, Tooltip } from "@material-ui/core"
import {ScreenShare, StopScreenShare} from '@material-ui/icons'
import React, { useMemo } from "react"
import clsx from 'clsx';
import { useStyles } from "../../css";
type FeatureType = "ShareScreen"
type FeatureEnablerProps = {
type: FeatureType
enable:boolean
setEnable:(val:boolean)=>void
}
export const FeatureEnabler = (props:FeatureEnablerProps) =>{
const classes = useStyles()
const icon = useMemo(()=>{
const index = props.enable? 0 : 1
switch(props.type){
case "ShareScreen":
return [<StopScreenShare />, <ScreenShare />][index]
}
},[props.enable, props.type])
const tooltip = useMemo(()=>{
const index = props.enable? 0 : 1
switch(props.type){
case "ShareScreen":
return ["Stop Screen Share", "Start Screen Share"][index]
}
},[props.enable, props.type])
const enabler = useMemo(()=>{
return(
<Tooltip title={tooltip}>
<IconButton color="inherit" className={clsx(classes.menuButton)} onClick={()=>{props.setEnable(!props.enable)}}>
{icon}
</IconButton>
</Tooltip>
)
},[props.enable, props.type]) // eslint-disable-line
return(
<>
{enabler}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/SwitchButtons.tsx | import { IconButton, makeStyles, Tooltip } from "@material-ui/core"
import { Stop, ViewCompact, ViewComfy} from '@material-ui/icons'
import React, { useMemo } from "react"
// import { useStyles } from "../../css";
const toolbarHeight = 20
export const useStyles = makeStyles((theme) => ({
menuButton: {
width: toolbarHeight, height: toolbarHeight,
},
menuButtonActive: {
width: toolbarHeight, height: toolbarHeight,
color: "#ee7777"
},
}));
type SwitchButtonsType = "ScreenView"
export type ScreenType = "FullView" | "FeatureView" | "GridView"
type SwitchButtonsProps = {
type: SwitchButtonsType
selected: ScreenType | "" // "" is placeholder
onClick:(val:ScreenType | "")=>void
}
export const SwitchButtons = (props: SwitchButtonsProps) =>{
const classes = useStyles()
const switchLabelArray:ScreenType[] = useMemo(()=>{
switch(props.type){
case "ScreenView":
return ["FullView", "FeatureView", "GridView"]
}
},[props.type, props.selected]) // eslint-disable-line
const selectedIndex = useMemo(()=>{
return switchLabelArray.findIndex(x => {return x===props.selected})
},[props.type, props.selected]) // eslint-disable-line
const icons = useMemo(()=>{
switch(props.type){
case "ScreenView":
return [<Stop/>, <ViewCompact/>, <ViewComfy/>]
}
},[props.type, props.selected]) // eslint-disable-line
const tooltips = useMemo(()=>{
switch(props.type){
case "ScreenView":
return ["Full Screen", "Feature View", "Grid View"]
}
},[props.type, props.selected]) // eslint-disable-line
const enabler = useMemo(()=>{
return icons.map((val,index) =>{
return (
<Tooltip key={`tooltip_${index}`} title={tooltips[index]}>
<IconButton color="inherit" className={index === selectedIndex ? classes.menuButtonActive : classes.menuButton} onClick={(e)=>{props.onClick(switchLabelArray[index])}}>
{/* <IconButton color="inherit" style={{color: "#ee7777"}} onClick={(e)=>{props.onClick(switchLabelArray[index])}}> */}
{icons[index]}
</IconButton>
</Tooltip>
)
})
},[props.type, props.selected]) // eslint-disable-line
return(
<>
{enabler}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/AppStateProvider.tsx | <gh_stars>0
import React, { useContext, useState } from "react";
import { ReactNode } from "react";
import { AttendeeState } from "./helper/ChimeClient";
import { useCredentials } from "./hooks/useCredentials";
import { useMeetingState } from "./hooks/useMeetingState";
import { MessageType, useMessageState } from "./hooks/useMessageState";
import { STAGE, useStageManager } from "./hooks/useStageManager";
import { useWindowSizeChangeListener } from "./hooks/useWindowSizeChange";
import { DefaultMeetingSession, VideoTileState } from "amazon-chime-sdk-js";
import { useDeviceState } from "./hooks/useDeviceState";
import { DeviceInfo } from "../utils";
import { AudioInputDeviceSetting } from "./helper/AudioInputDeviceSetting";
import { VideoInputDeviceSetting } from "./helper/VideoInputDeviceSetting";
import { AudioOutputDeviceSetting } from "./helper/AudioOutputDeviceSetting";
import { useRealtimeSubscribeChat } from "./hooks/RealtimeSubscribers/useRealtimeSubscribeChat";
import { RealtimeData } from "./hooks/RealtimeSubscribers/const";
import { DrawingMode, useWebSocketWhiteBoard } from "./hooks/WebSocketApp/useWebSocketWhiteBoard";
import { DrawingData } from "./hooks/WebSocketApp/helper/WebSocketWhiteBoardClient";
import { Recorder } from "./helper/Recorder";
import { OnetimeCodeInfo, OnetimeCodeSigninResult } from "../api/api";
import { HMMMessage, HMMStatus, useRealtimeSubscribeHMM } from "./hooks/RealtimeSubscribers/useRealtimeSubscribeHMM";
import { awsConfiguration, DEFAULT_PASSWORD, DEFAULT_USERID } from "../Config";
import { GameState } from "./hooks/RealtimeSubscribers/useAmongUs";
type Props = {
children: ReactNode;
};
type APP_MODE = "chime" | "amongus"
interface AppStateValue {
mode: APP_MODE,
/** For Credential */
userId?: string,
password?: string,
idToken?: string,
accessToken?: string,
refreshToken?: string,
handleSignIn: (inputUserId: string, inputPassword: string) => Promise<void>
handleSignUp: (inputUserId: string, inputPassword: string) => Promise<void>
handleVerify: (inputUserId: string, inputVerifyCode: string) => Promise<void>
handleResendVerification: (inputUserId: string) => Promise<void>
handleSendVerificationCodeForChangePassword: (inputUserId: string) => Promise<void>
handleNewPassword: (inputUserId: string, inputVerifycode: string, inputPassword: string) => Promise<void>
handleSignOut: (inputUserId: string) => Promise<void>
onetimeCodeInfo: OnetimeCodeInfo | null,
handleSinginWithOnetimeCodeRequest: (meetingName: string, attendeeId: string, uuid: string) => Promise<OnetimeCodeInfo>,
handleSinginWithOnetimeCode: (meetingName: string, attendeeId: string, uuid: string, code: string) => Promise<OnetimeCodeSigninResult>
// handleSinginWithOnetimeCodeRequest_dummy: (meetingName: string, attendeeId: string, uuid: string) => Promise<OnetimeCodeInfo>,
/** For MeetingState */
meetingName?:string,
userName?:string,
attendeeId?:string,
attendees: {[attendeeId: string]: AttendeeState}
videoTileStates: {[attendeeId: string]: VideoTileState}
createMeeting: (meetingName: string, userName: string, region: string) => Promise<{created: boolean, meetingName: string, meetingId: string}>
joinMeeting: (meetingName: string, userName: string) => Promise<void>
enterMeeting: () => Promise<void>
leaveMeeting: () => Promise<void>
startShareScreen: () => Promise<void>
stopShareScreen: () => Promise<void>
getUserNameByAttendeeIdFromList: (attendeeId: string) => string
meetingSession: DefaultMeetingSession | undefined
activeRecorder: Recorder
allRecorder: Recorder
audioInputDeviceSetting: AudioInputDeviceSetting | undefined
videoInputDeviceSetting: VideoInputDeviceSetting | undefined
audioOutputDeviceSetting: AudioOutputDeviceSetting | undefined
isShareContent:boolean
activeSpeakerId:string|null
countAttendees:()=>void
updateMeetingInfo: ()=>void
ownerId:string
isOwner:boolean
setPauseVideo: (attendeeId: string, pause: boolean) => void
/** For Device State */
audioInputList: DeviceInfo[] | null
videoInputList: DeviceInfo[] | null
audioOutputList: DeviceInfo[] | null
reloadDevices: () => void
/** For Chat */
chatData: RealtimeData[],
sendChatData: (text: string) => void,
/** For HMM(Headless Meeting Manager) */
sendHMMCommand: (mess: HMMMessage) => void,
hMMCommandData: RealtimeData[],
startHMM:()=>void,
updateHMMInfo:()=>void,
publicIp:string,
sendStartRecord:()=>void,
sendStopRecord:()=>void,
sendStartShareTileView:()=>void,
sendStopShareTileView:()=>void,
sendTerminate:()=>void,
sendHMMStatus:(active: boolean, recording: boolean, shareTileView: boolean)=>void,
sendRegisterAmongUsUserName: (userName: string, attendeeId: string) => void
// recordingEnable: boolean,
// shareTileViewEnable: boolean,
// terminateTriggerd: boolean,
startRecordingCounter:number,
stopRecordingCounter:number,
startShareTileViewCounter:number,
stopShareTileViewCounter:number,
terminateCounter:number,
hMMStatus: HMMStatus,
stateLastUpdate: number,
updateGameState: (ev: string, data: string) => void
currentGameState: GameState
gameState: GameState
/** For WhiteBoard */
addDrawingData: ((data: DrawingData) => void) | undefined
drawingData: DrawingData[]
lineWidth: number
setLineWidth: (val:number) => void,
drawingStroke: string
setDrawingStroke: (val:string) => void,
drawingMode: keyof typeof DrawingMode
setDrawingMode: (val: keyof typeof DrawingMode) => void
screenWidth: number
screenHeight: number
/** For StageManager */
stage:STAGE,
setStage: (stage:STAGE) => void
/** For Message*/
messageActive: boolean,
messageType: MessageType,
messageTitle: string,
messageDetail: string[],
setMessage: (type: MessageType, title: string, detail: string[]) => void,
resolveMessage: () => void,
// /** For Scheduler*/
// tenSecondsTaskTrigger:number,
// uploadFileToS3: (key: string, data: Uint8Array) => Promise<void>
}
const AppStateContext = React.createContext<AppStateValue | null>(null);
export const useAppState = (): AppStateValue => {
const state = useContext(AppStateContext);
if (!state) {
throw new Error('useAppState must be used within AppStateProvider');
}
return state;
}
const query = new URLSearchParams(window.location.search);
export const AppStateProvider = ({ children }: Props) => {
const {
userId, password, idToken, accessToken, refreshToken,
handleSignIn,
handleSignUp,
handleVerify,
handleResendVerification,
handleSendVerificationCodeForChangePassword,
handleNewPassword,
handleSignOut,
onetimeCodeInfo,
handleSinginWithOnetimeCodeRequest,
handleSinginWithOnetimeCode,
// handleSinginWithOnetimeCodeRequest_dummy,
} = useCredentials({
UserPoolId: awsConfiguration.userPoolId,
ClientId: awsConfiguration.clientId,
DefaultUserId: DEFAULT_USERID,
DefaultPassword: <PASSWORD>,
})
const { meetingName, meetingId, joinToken, userName, attendeeId, attendees, videoTileStates,
createMeeting, joinMeeting, enterMeeting, leaveMeeting,
startShareScreen, stopShareScreen, getUserNameByAttendeeIdFromList,
meetingSession, activeRecorder, allRecorder, audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting, isShareContent, activeSpeakerId,countAttendees,
updateMeetingInfo, ownerId, isOwner, setPauseVideo
} = useMeetingState({userId, idToken, accessToken, refreshToken,})
const { audioInputList, videoInputList, audioOutputList, reloadDevices } = useDeviceState()
const { screenWidth, screenHeight} = useWindowSizeChangeListener()
const { stage, setStage } = useStageManager({
initialStage:query.get("stage") as STAGE|null,
})
const { messageActive, messageType, messageTitle, messageDetail, setMessage, resolveMessage } = useMessageState()
const { chatData, sendChatData} = useRealtimeSubscribeChat({meetingSession, attendeeId})
const { sendHMMCommand, hMMCommandData, startHMM, updateHMMInfo, publicIp,
sendStartRecord, sendStopRecord, sendStartShareTileView, sendStopShareTileView, sendTerminate, sendHMMStatus, sendRegisterAmongUsUserName,
startRecordingCounter, stopRecordingCounter, startShareTileViewCounter, stopShareTileViewCounter, terminateCounter, hMMStatus, stateLastUpdate,
updateGameState, currentGameState, gameState
} = useRealtimeSubscribeHMM({meetingSession, attendeeId, meetingName, idToken, accessToken, refreshToken})
const logger = meetingSession?.logger
const { addDrawingData, drawingData, lineWidth, setLineWidth, drawingStroke, setDrawingStroke, drawingMode, setDrawingMode } = useWebSocketWhiteBoard({meetingId, attendeeId, joinToken, logger})
const [ mode, setMode ] = useState(query.get("mode") as APP_MODE| "chime" ) // eslint-disable-line
// const { tenSecondsTaskTrigger } = useScheduler()
// const { uploadFileToS3 } = useS3FileUploader({idToken, accessToken, refreshToken})
const providerValue = {
mode,
/** For Credential */
userId,
password,
idToken,
accessToken,
refreshToken,
handleSignIn,
handleSignUp,
handleVerify,
handleResendVerification,
handleSendVerificationCodeForChangePassword,
handleNewPassword,
handleSignOut,
onetimeCodeInfo,
handleSinginWithOnetimeCodeRequest,
handleSinginWithOnetimeCode,
// handleSinginWithOnetimeCodeRequest_dummy,
/** For MeetingState */
meetingName,
userName,
attendeeId,
attendees,
videoTileStates,
createMeeting,
joinMeeting,
enterMeeting,
leaveMeeting,
startShareScreen,
stopShareScreen,
getUserNameByAttendeeIdFromList,
meetingSession,
activeRecorder,
allRecorder,
audioInputDeviceSetting,
videoInputDeviceSetting,
audioOutputDeviceSetting,
isShareContent,
activeSpeakerId,
countAttendees,
updateMeetingInfo,
ownerId,
isOwner,
setPauseVideo,
/** For Device State */
audioInputList,
videoInputList,
audioOutputList,
reloadDevices,
screenWidth,
screenHeight,
/** For Chat */
chatData,
sendChatData,
/** For HMM(Headless Meeting Manager) */
sendHMMCommand,
hMMCommandData,
startHMM,
updateHMMInfo,
publicIp,
sendStartRecord,
sendStopRecord,
sendStartShareTileView,
sendStopShareTileView,
sendTerminate,
sendHMMStatus,
sendRegisterAmongUsUserName,
updateGameState,
currentGameState,
gameState,
// recordingEnable,
// shareTileViewEnable,
// terminateTriggerd,
startRecordingCounter,
stopRecordingCounter,
startShareTileViewCounter,
stopShareTileViewCounter,
terminateCounter,
hMMStatus,
stateLastUpdate,
/** For StageManager */
stage,
setStage,
/** For WhiteBoard */
addDrawingData,
drawingData,
lineWidth,
setLineWidth,
drawingStroke,
setDrawingStroke,
drawingMode,
setDrawingMode,
/** For Message*/
messageActive,
messageType,
messageTitle,
messageDetail,
setMessage,
resolveMessage,
// /** For Scheduler */
// tenSecondsTaskTrigger,
// uploadFileToS3,
};
return (
<AppStateContext.Provider value={providerValue} >
{children}
</AppStateContext.Provider>
)
}
|
diitalk/flect-chime-sdk-demo | backend/lib/manager/recording/src/index.ts | <filename>backend/lib/manager/recording/src/index.ts<gh_stars>0
import puppeteer, { Page } from 'puppeteer';
import http from 'http'
import * as io from "socket.io";
import AsyncLock from "async-lock"
import * as os from 'os'
import * as fs from 'fs'
import * as aws from 'aws-sdk'
// var lock = new AsyncLock({timeout: 1000 * 30 });
var lock = new AsyncLock();
var finalize = false;
let page:Page;
let hostname = '0.0.0.0';
let port = 3000;
let protocol = 'http';
const server = http.createServer({}, async (request, response) => {
console.log(`${request.method} ${request.url} BEGIN`);
})
server.listen(port, hostname, () => {
console.log(`${hostname}:${port}`)
});
var io_server = new io.Server(server, {
allowEIO3: true
})
const now = () => new Date().toISOString().substr(14, 9);
const sleep = async (ms:number) => {
const p = new Promise<void>((resolve,reject) => {
setTimeout(()=>{
console.log("SLEEP RESOLVED!")
resolve()
}, ms);
});
await p
}
type PlayerState = {
name:string
isDead:boolean
isDeadDiscovered:boolean
disconnected:boolean
color:number
action:number
attendeeId?:string
chimeName?:string
}
type GameState = {
hmmAttendeeId:string
state:number
lobbyCode:string
gameRegion:number
map:number
connectCode:string
players:PlayerState[]
}
const initialState:GameState = {
hmmAttendeeId:"",
state:3,
lobbyCode:"",
gameRegion:0,
map:0,
connectCode:"",
players: [],
}
let gameState:GameState = {...initialState, players:[]}
io_server.on('connection', client => {
///////////////////////////////////////////////////////
// handle socket io event start
///////////////////////////////////////////////////////
//@ts-ignore
client.on('connectCode', (connectCode) => {
lock.acquire('io_on', async () => {
console.log("AMONG: [connectCode]", connectCode)
//@ts-ignore
client.connectCode = connectCode;
gameState = {...initialState, players:[]}
return 'Successful';
}, (error, result) => {
if(error) {
console.log(now(), 'Connect Failure : ', error);
}
else {
console.log(now(), 'Connect Success : ', result);
}
})
});
//@ts-ignore
client.on('lobby', (data) => {
lock.acquire('io_on', async () => {
console.log("AMONG: [lobby]", data)
const lobbyData = JSON.parse(data)
gameState.lobbyCode = lobbyData.LobbyCode
gameState.gameRegion = lobbyData.Region
gameState.map = lobbyData.Map
// request data ID
// enum GameDataType{
// GameState = 1,
// Players = 2,
// LobbyCode = 4
// }
client.emit("requestdata", 2)
return 'Successful';
},(error, result) => {
if(error) {
console.log(now(), 'Lobby Failure : ', error);
}
else {
console.log(now(), 'Lobby Success : ', result);
}
})
})
//@ts-ignore
client.on('state', (index) => {
lock.acquire('io_on', async () => {
console.log("AMONG: [state]", index)
if(index == 0 || index == 3){ // Lobby(0),Menu(3)
gameState.players = []
}
// if(index == 2){// discussion update player status
if(index == 2){// discussion update discovered status
// client.emit("requestdata", 2)
gameState.players.forEach(x=>{
if(x.isDead){
x.isDeadDiscovered = true
}
})
}
gameState.state = index
return 'Successful';
},(error, result) => {
if(error) {
console.log(now(), 'State Failure : ', error);
}
else {
console.log(now(), 'State Success : ', result);
}
})
});
//@ts-ignore
client.on('player', (data) => {
lock.acquire('io_on', async() => {
console.log("AMONG: [player]", data)
//// change to realtime update
// if(gameState.state == 1){ // tasks, skip update player status
// return
// }
const playerData = JSON.parse(data)
const otherPlayers = gameState.players.filter(x=>{return x.name !== playerData.Name}) // list up not target players
let targetPlayers = gameState.players.filter(x=>{return x.name === playerData.Name}) // target players
if(targetPlayers.length == 0){ // target players not found.
const newPlayer = {
name: playerData.Name,
isDead: playerData.IsDead,
isDeadDiscovered:false,
disconnected: playerData.Disconnected,
action: parseInt(playerData.Action),
color: parseInt(playerData.Color)
}
targetPlayers.push(newPlayer)
}else{
targetPlayers[0].name = playerData.Name
targetPlayers[0].isDead = playerData.IsDead
// keep isDeadDiscovered state
targetPlayers[0].disconnected = playerData.Disconnected
targetPlayers[0].action = parseInt(playerData.Action)
targetPlayers[0].color = parseInt(playerData.Color)
if(targetPlayers[0].action == 6){ // When user is purged, the user status is discovered immidiately
targetPlayers[0].isDeadDiscovered = true
}
}
if(parseInt(playerData.Action) !== 1){ // when action is leave, not add the new player(= delete the user)
otherPlayers.push(...targetPlayers)
}
gameState.players = otherPlayers
return 'Successful';
},(error, result) => {
if(error) {
console.log(now(), 'Player Failure : ', error);
}
else {
console.log(now(), 'Player Success : ', result);
}
})
});
//@ts-ignore
client.on('disconnect', () => {
lock.acquire('io_on', async() => {
console.log("AMONG: [disconnect]")
gameState.players = []
return 'Successful';
},(error, result) => {
if(error) {
console.log(now(), 'Disconnect Failure : ', error);
}
else {
console.log(now(), 'Disconnect Success : ', result);
}
})
});
///////////////////////////////////////////////////////
// handle socket io event end
///////////////////////////////////////////////////////
});
const uploadGameState = (_finalize:boolean) =>{
// console.log("upload game state1-1[cpu]", os.cpus())
// console.log("upload game state1-2[total mem]", os.totalmem())
// console.log("upload game state1-3[free mem]", os.freemem())
if(page){
console.log(`upload game state ${_finalize}, ${finalize}`)
lock.acquire('io_on', async () => {
// @ts-ignore
await page.$eval('#io_data', (el, value) => el.value = value, JSON.stringify(gameState));
await page.click("#io_click")
return 'Successful';
},(error, result) => {
if(error) {
console.log(now(), 'Upload game state Failure : ', error);
}
else {
console.log(now(), 'Upload game state Success : ', result);
}
if(_finalize){
}else{
setTimeout(()=>{
uploadGameState(finalize)
}, 1000 * 2)
}
})
}else{
setTimeout(()=>{
uploadGameState(finalize)
}, 1000 * 2)
}
}
uploadGameState(finalize)
const args = process.argv.slice(2);
const meetingURL = args[0]
const bucketName = args[1]
const browserWidth = args[1];
const browserHeight = args[2];
console.log(`meetingURL: ${meetingURL}, bucketName:${bucketName}, width:${browserWidth}, height:${browserHeight}`);
const downloadPath = './download';
puppeteer.launch({
headless: false,
executablePath: '/usr/bin/google-chrome-stable',
ignoreHTTPSErrors: true,
ignoreDefaultArgs: ['--mute-audio'],
args: [
'--enable-usermedia-screen-capturing',
'--allow-http-screen-capture',
'--auto-select-desktop-capture-source=pickme',
'--autoplay-policy=no-user-gesture-required',
'--no-sandbox',
'--disable-setuid-sandbox',
'--use-fake-ui-for-media-stream',
'--use-fake-device-for-media-stream',
]
}).then(async(browser)=>{
page = await browser.newPage();
page.on(`console`, msg => {
for (let i = 0; i < msg.args().length; ++i) {
console.log(`${i}: ${msg.args()[i]}`);
}
});
await page.exposeFunction('onCustomEvent', async(e:any) => {
console.log(`!!!!!!! Event Fired!!! !!!!!! ${e.type} fired`, e.detail || '');
const s3 = new aws.S3({ params: { Bucket: bucketName } });
let promises:Promise<any>[] = []
switch (e.type) {
case "terminate":
console.log("TERMINATE----------------!")
console.log("wait 20sec for download process")
await sleep(1000 * 20)
console.log("wait 20sec for download process done")
try{
io_server.disconnectSockets();
}catch(exception){
console.log(`io_server disconnecting exception ..., ${exception}`)
}
try{
server.close();
}catch(exception){
console.log(`server closing exception ..., ${exception}`)
}
finalize = true
console.log(`Terminating,,, finalize3 flag:${finalize}`)
try{
fs.readdirSync(downloadPath).forEach(file => {
const filePath = `${downloadPath}/${file}`
console.log("FILE:::", filePath)
let params:aws.S3.PutObjectRequest = {
Bucket: bucketName,
Key: `recording/${file}`
};
params.Body = fs.readFileSync(filePath);
const p = s3.putObject(params, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
}).promise();
promises.push(p)
});
}catch(exception){
console.log(`file upload to s3 exception ..., ${exception}`)
}
await Promise.all(promises)
console.log(`Terminating,,, done`)
try{
browser.close();
}catch(exception){
console.log(`browser closing exception ..., ${exception}`)
}
break
case "uploadVideo":
console.log("uploadVideo----------------!")
console.log("wait 20sec for upload process")
await sleep(1000 * 20)
console.log("wait 20sec for upload process done")
fs.readdirSync(downloadPath).forEach(file => {
const filePath = `${downloadPath}/${file}`
console.log("FILE:::", filePath)
let params:aws.S3.PutObjectRequest = {
Bucket: bucketName,
Key: `recording/${file}`
};
params.Body = fs.readFileSync(filePath);
const p = s3.putObject(params, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
}).promise();
promises.push(p)
});
console.log("uploadVideo----------------! done!")
break
}
});
function listenFor() {
return page.evaluateOnNewDocument(() => {
document.addEventListener('terminate', e => {
// @ts-ignore
window.onCustomEvent({ type: 'terminate', detail: e.detail });
});
document.addEventListener('uploadVideo', e => {
// @ts-ignore
window.onCustomEvent({ type: 'uploadVideo', detail: e.detail });
})
});
}
await listenFor();
await page.goto(meetingURL)
// @ts-ignore
await page._client.send('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: downloadPath
});
})
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/Title.tsx | import { Typography } from "@material-ui/core"
import React, { useMemo } from "react"
import { useStyles } from "../../css";
type TitleProps = {
title:string
}
export const Title = (props:TitleProps) =>{
const classes = useStyles()
const title = useMemo(()=>{
return(
<Typography color="inherit" noWrap className={classes.title}>
{props.title}
</Typography>
)
},[]) // eslint-disable-line
return(
<>
{title}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/helper/Recorder.ts | import {FFmpeg, createFFmpeg, fetchFile} from "@ffmpeg/ffmpeg"
// import * as AWS from "aws-sdk";
// const bucketName = "f-backendstack-dev-bucket"
// const s3 = new AWS.S3({ params: { Bucket: bucketName } });
export class Recorder{
isRecording = false
chunks: Blob[] = []
recorder:MediaRecorder|null = null
ffmpeg:FFmpeg|null = createFFmpeg({log:true})
startRecording = (stream:MediaStream) => {
console.log("[Recorder] recorder start!!!!!!!!!!!!!!!!!")
const options = {
mimeType : 'video/webm;codecs=h264,opus'
};
this.chunks = []
this.recorder = new MediaRecorder(stream, options)
this.recorder.ondataavailable = (e:BlobEvent) => {
console.log("ondataavailable datasize", e.data.size)
this.chunks!.push(e.data)
}
this.recorder!.start(1000)
this.isRecording=true
}
stopRecording = () => {
console.log("[Recorder] recorder stop!!!!!!!!!!!!!!!!!")
this.recorder?.stop()
this.isRecording=false
}
getDataURL = () => {
return URL.createObjectURL(new Blob(this.chunks,{type:"video/wbem"}))
}
// I don't know why, but it doesn't work well....
// getMp4URL = async () =>{
// console.log("[Recorder] recorder mp4!!!!!!!!!!!!!!!!!")
// const name = 'record.webm'
// const outName = 'out.mp4'
// if(this.ffmpeg!.isLoaded() === false){
// await this.ffmpeg!.load()
// this.ffmpeg!.setProgress(({ ratio }) => {
// console.log("progress:", ratio);
// });
// }
// // @ts-ignore
// this.ffmpeg.FS('writeFile', name, await fetchFile(new Blob(this.chunks)));
// await this.ffmpeg!.run('-i', name, '-c', 'copy', outName);
// const data = this.ffmpeg!.FS('readFile', outName)
// return URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
// }
toMp4 = async (outfileName?:string): Promise<Uint8Array> => {
console.log("[Recorder] recorder mp4!!!!!!!!!!!!!!!!!")
const name = 'record.webm'
let outName = 'out.mp4'
if(outfileName){
outName = outfileName
}
const a = document.createElement("a")
a.download = outName
if(this.ffmpeg!.isLoaded() === false){
await this.ffmpeg!.load()
this.ffmpeg!.setProgress(({ ratio }) => {
console.log("progress:", ratio);
});
}
// @ts-ignore
this.ffmpeg.FS('writeFile', name, await fetchFile(new Blob(this.chunks)));
console.log("FFMPEG START!")
await this.ffmpeg!.run('-i', name, '-c', 'copy', outName);
const data = this.ffmpeg!.FS('readFile', outName)
a.href = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
a.click()
console.log("FFMPEG DONE!")
return data
// var params = {
// Body: URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' })),
// Bucket: bucketName,
// Key: outName,
// };
// s3.putObject(params, function(err, data) {
// if (err) console.log("S3Upload::::f ", err, err.stack); // an error occurred
// else console.log("S3Upload::::s ", data); // successful response
// /// Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1...!?
// })
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/css.ts | import { makeStyles } from "@material-ui/core";
const lineSpacerHeihgt = 10
const toolbarHeight = 20
const drawerWidth = 240;
export const bufferHeight = 20
export const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
width:'100%',
height:'100%',
overflowX:'hidden',
overflowY:'hidden',
},
////////////////
// ToolBar
////////////////
appBar: {
zIndex: theme.zIndex.drawer + 1,
// transition: theme.transitions.create(['width', 'margin'], {
// easing: theme.transitions.easing.sharp,
// duration: theme.transitions.duration.leavingScreen,
// }),
height: toolbarHeight
},
toolbar: {
height: toolbarHeight,
display: "flex",
justifyContent: "space-between"
},
toolbarInnnerBox: {
height: toolbarHeight,
display: "flex",
justifyContent: "space-between"
},
menuSpacer: {
width: toolbarHeight, height: toolbarHeight,
},
menuButton: {
width: toolbarHeight, height: toolbarHeight,
},
menuButtonActive: {
width: toolbarHeight, height: toolbarHeight,
color: "#ee7777"
},
title: {
flexGrow: 1,
alignSelf:"center"
},
appBarSpacer: {
height: toolbarHeight
},
////////////////
// SideBar
////////////////
drawerPaper: {
// marginLeft: drawerWidth,
position: 'relative',
whiteSpace: 'nowrap',
width: drawerWidth,
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
drawerPaperClose: {
overflowX: 'hidden',
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
// width: theme.spacing(3),
[theme.breakpoints.up('xs')]: {
// width: theme.spacing(0),
width: 0,
},
},
toolbarIcon: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
////////////////
// Main
////////////////
content: {
flexGrow: 1,
// width: `calc(100%-drawerWidth)`,
// height: "100%",
// height: `calc(100%-toolbarHeight)`,
// width: 'auto',
// height: 'auto',
// overflow:'auto',
overflow:'hidden',
},
////////////////////
// dialog
////////////////////
form: {
width: '100%',
marginTop: theme.spacing(1),
},
formControl: {
margin: theme.spacing(1),
width: '100%'
// minWidth: 120,
},
lineSpacer:{
height:lineSpacerHeihgt,
},
}));
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/DrawerOpener.tsx | import { Button, Tooltip } from "@material-ui/core"
import {ChevronLeft, ChevronRight} from '@material-ui/icons'
import React, { useMemo } from "react"
import clsx from 'clsx';
import { useStyles } from "../../css";
type DrawerOpenerProps = {
open:boolean
setOpen:(val:boolean)=>void
}
export const DrawerOpener = (props:DrawerOpenerProps) =>{
const classes = useStyles()
const opener = useMemo(()=>{
return(
props.open?
<Tooltip title="Drawer Close">
<Button color="inherit" className={clsx(classes.menuButton)} startIcon={<ChevronLeft />} id="close-drawer" onClick={()=>{props.setOpen(false)}}>
menu
</Button>
</Tooltip>
:
<Tooltip title="Drawer Open">
<Button color="inherit" className={clsx(classes.menuButton)} endIcon={<ChevronRight /> } id="open-drawer" onClick={()=>{props.setOpen(true)}}>
menu
</Button>
</Tooltip>
)
},[props.open]) // eslint-disable-line
return(
<>
{opener}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/200_HeadlessMeetingManager/hooks/useShareTileView.ts | import { useEffect, useState } from "react"
import { useAppState } from "../../../providers/AppStateProvider"
type UseRecorderProps = {
meetingName : string
}
const framerate = 8
export const useShareTileView = (props:UseRecorderProps) =>{
const { startShareTileViewCounter, stopShareTileViewCounter, videoInputDeviceSetting } = useAppState()
const [ tileCanvas, setTileCanvas ] = useState<HTMLCanvasElement>()
const [ isSharingTileView, setIsSharingTileView] = useState(false)
const startSharingTileView = async () =>{
if(!tileCanvas){
console.log("START SHARE TILE VIEW::: failed! canvas is null", tileCanvas)
return
}
if(isSharingTileView){
console.log("START SHARE TILE VIEW::: failed! already sharing")
return
}
// @ts-ignore
const videoStream = tileCanvas.captureStream(framerate) as MediaStream
await videoInputDeviceSetting!.setVideoInput(videoStream)
videoInputDeviceSetting!.startLocalVideoTile()
setIsSharingTileView(true)
return
}
const stopSharingTileView = async () =>{
if(!isSharingTileView){
console.log("STOP SHARING::: failed! sharing is not started")
return
}
await videoInputDeviceSetting!.setVideoInput(null)
videoInputDeviceSetting!.stopLocalVideoTile()
setIsSharingTileView(false)
}
useEffect(()=>{
console.log("START SHARING:::", startShareTileViewCounter, stopShareTileViewCounter)
startSharingTileView()
},[startShareTileViewCounter]) // eslint-disable-line
useEffect(()=>{
console.log("STOP SHARING:::", startShareTileViewCounter, stopShareTileViewCounter)
stopSharingTileView()
},[stopShareTileViewCounter]) // eslint-disable-line
return {isSharingTileView, setTileCanvas, stopSharingTileView}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useCredentials.ts | <gh_stars>0
import { useEffect, useMemo, useState } from "react"
import { CognitoUser, AuthenticationDetails, CognitoUserPool, CognitoUserAttribute } from 'amazon-cognito-identity-js';
import { OnetimeCodeInfo, singinWithOnetimeCode, singinWithOnetimeCodeRequest } from "../../api/api";
import { useScheduler } from "./useScheduler";
type UseCredentialsProps = {
UserPoolId: string
ClientId: string
DefaultUserId?: string
DefaultPassword?: string
}
type UseCredentialsStates = {
userId?: string
password?: string
idToken?: string
accessToken?: string
refreshToken?: string
}
export const useCredentials = (props:UseCredentialsProps) => {
const userPool = useMemo(()=>{
return new CognitoUserPool({
UserPoolId: props.UserPoolId,
ClientId: props.ClientId
})
},[])// eslint-disable-line
const [ state, setState] = useState<UseCredentialsStates>({
userId: props.DefaultUserId,
password: <PASSWORD>.<PASSWORD>,
})
const [onetimeCodeInfo, setOnetimeCodeInfo] = useState<OnetimeCodeInfo|null>(null)
const { thirtyMinutesSecondsTaskTrigger } = useScheduler()
// (1) Sign in
const handleSignIn = async (inputUserId: string, inputPassword: string)=> {
const authenticationDetails = new AuthenticationDetails({
Username: inputUserId,
Password: <PASSWORD>
})
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
const p = new Promise<void>((resolve, reject)=>{
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
const accessToken = result.getAccessToken().getJwtToken()
const idToken = result.getIdToken().getJwtToken()
const refreshToken = result.getRefreshToken().getToken()
setState( {...state, userId:inputUserId, idToken:idToken, accessToken:accessToken, refreshToken:refreshToken})
resolve()
},
onFailure: (err) => {
console.log("signin error:", err)
reject(err)
}
})
})
return p
}
// (2) Sign up
const handleSignUp = async (inputUserId: string, inputPassword: string) => {
const attributeList = [
new CognitoUserAttribute({
Name: 'email',
Value: inputUserId
})
]
const p = new Promise<void>((resolve, reject)=>{
userPool.signUp(inputUserId, inputPassword, attributeList, [], (err, result) => {
if (err) {
reject(err)
return
}
resolve()
})
})
return p
}
// (3) Verify Code
const handleVerify = async (inputUserId: string, inputVerifyCode: string):Promise<void> => {
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
const p = new Promise<void>((resolve, reject)=>{
cognitoUser.confirmRegistration(inputVerifyCode, true, (err: any) => {
if (err) {
reject(err)
return
}
resolve()
})
})
return p
}
// (4) Resend Verify Code
const handleResendVerification = async (inputUserId: string)=> {
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
const p = new Promise<void>((resolve, reject)=>{
cognitoUser.resendConfirmationCode((err: any) => {
if (err) {
reject(err)
return
}
resolve()
})
})
return p
}
// (5) Forgot Password
const handleSendVerificationCodeForChangePassword = async (inputUserId: string) => {
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
const p = new Promise<void>((resolve, reject)=>{
cognitoUser.forgotPassword({
onSuccess: (data) => {
resolve()
},
onFailure: (err) => {
reject(err)
}
})
})
return p
}
// (6) New Password
const handleNewPassword = async (inputUserId: string, inputVerifycode: string, inputPassword: string) => {
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
const p = new Promise<void>((resolve, reject)=>{
cognitoUser.confirmPassword(inputVerifycode, inputPassword, {
onSuccess: () => {
resolve()
},
onFailure: (err) => {
reject(err)
}
})
})
return p
}
// (7) refresh token // not implemented. (hard to handle multiuser of one user id)
useEffect(()=>{
if(thirtyMinutesSecondsTaskTrigger===0){
return
}
},[thirtyMinutesSecondsTaskTrigger])
// (x) Sign out
const handleSignOut = async (inputUserId: string) => {
const cognitoUser = new CognitoUser({
Username: inputUserId,
Pool: userPool
})
cognitoUser.signOut()
setState( {...state, userId:"", password:"", idToken:"", accessToken:"", refreshToken:""})
}
///////////////////
/// Ontime Code signin
///////////////
// (a-1) Signin request
const handleSinginWithOnetimeCodeRequest = async (meetingName:string, attendeeId:string, uuid:string) =>{
const res = await singinWithOnetimeCodeRequest(meetingName, attendeeId, uuid)
setOnetimeCodeInfo(res)
return res
}
// (a-2) Signin
const handleSinginWithOnetimeCode = async (meetingName:string, attendeeId:string, uuid:string, code:string) =>{
console.log("Active Speaker::::::: one timecode signin")
const res = await singinWithOnetimeCode(meetingName, attendeeId, uuid, code)
console.log("Active Speaker::::::: one time code res:", res)
setState( {...state, userId:"-", idToken:res.idToken, accessToken:res.accessToken, refreshToken:"-"})
return res
}
// // (a-1) Signin request
// const handleSinginWithOnetimeCodeRequest_dummy = async (meetingName:string, attendeeId:string, uuid:string) =>{
// // const res = await singinWithOnetimeCodeRequest(meetingName, attendeeId, uuid)
// const res: OnetimeCodeInfo = {
// uuid: "",
// codes: [],
// status:"",
// meetingName:"",
// attendeeId:"",
// }
// setOnetimeCodeInfo(res)
// return res
// }
return {
...state,
handleSignIn,
handleSignUp,
handleVerify,
handleResendVerification,
handleSendVerificationCodeForChangePassword,
handleNewPassword,
handleSignOut,
onetimeCodeInfo,
handleSinginWithOnetimeCodeRequest,
handleSinginWithOnetimeCode,
// handleSinginWithOnetimeCodeRequest_dummy,
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/dialog/SettingDialog.tsx | <filename>frontend3/src/pages/023_meetingRoom/components/dialog/SettingDialog.tsx
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControl, InputLabel, MenuItem, Select, Typography } from "@material-ui/core"
import React, { useState } from "react"
import { useAppState } from "../../../../providers/AppStateProvider"
import { useStyles } from "../../css"
import { DefaultDeviceController } from "amazon-chime-sdk-js";
type SettingDialogProps={
open:boolean,
onClose:()=>void
}
export const SettingDialog = (props:SettingDialogProps) =>{
const classes = useStyles()
const {audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting, audioInputList, videoInputList, audioOutputList,
} = useAppState()
const [guiCounter, setGuiCounter] = useState(0)
const onInputVideoChange = async (e: any) => {
//// for input movie experiment [start]
const videoElem = document.getElementById("for-input-movie")! as HTMLVideoElement
videoElem.pause()
videoElem.srcObject=null
videoElem.src=""
//// for input movie experiment [end]
if (e.target.value === "None") {
await videoInputDeviceSetting!.setVideoInput(null)
videoInputDeviceSetting!.stopLocalVideoTile()
setGuiCounter(guiCounter+1)
} else if (e.target.value === "File") {
// fileInputRef.current!.click()
} else {
await videoInputDeviceSetting!.setVideoInput(e.target.value)
videoInputDeviceSetting!.startLocalVideoTile()
setGuiCounter(guiCounter+1)
}
}
// const setInputMovieFile = (path:string, fileType:string) =>{
const setInputMovieFile = (noise:boolean) =>{
const input = document.createElement("input")
input.type = "file"
input.onchange = (e: any) => {
const path = URL.createObjectURL(e.target.files[0]);
const fileType = e.target.files[0].type
console.log(path, fileType)
if(fileType.startsWith("video")){
const videoElem = document.getElementById("for-input-movie")! as HTMLVideoElement
videoElem.pause()
videoElem.srcObject=null
videoElem.onloadeddata = async (e) =>{
// @ts-ignore
const mediaStream = videoElem.captureStream() as MediaStream
/////// Generate AudioInput Source
const stream = new MediaStream();
if(mediaStream.getAudioTracks().length>0){
mediaStream.getAudioTracks().forEach(t=>{
console.log("AUDIO TRACK",t)
stream.addTrack(t)
})
console.log("AUDIO ",stream)
// audioInputDeviceSetting!.setAudioInput(mediaStream)
}else{
console.log("NO AUDIO TRACK")
// audioInputDeviceSetting!.setAudioInput(null)
}
const audioContext = DefaultDeviceController.getAudioContext();
const sourceNode = audioContext.createMediaStreamSource(stream);
const outputNode = audioContext.createMediaStreamDestination();
sourceNode.connect(outputNode)
if(noise){
const outputNodeForMix = audioContext.createMediaStreamDestination();
const gainNode = audioContext.createGain();
gainNode.gain.value = 0.1;
gainNode.connect(outputNodeForMix);
const oscillatorNode = audioContext.createOscillator();
oscillatorNode.frequency.value = 440;
oscillatorNode.connect(gainNode);
oscillatorNode.start();
audioInputDeviceSetting!.setBackgroundMusic(outputNodeForMix.stream)
}
audioInputDeviceSetting!.setAudioInput(outputNode.stream)
/////// Generate VideoInput Source
if(mediaStream.getVideoTracks().length>0){
const stream = new MediaStream();
mediaStream.getVideoTracks().forEach(t=>{
stream.addTrack(t)
})
await videoInputDeviceSetting!.setVideoInput(mediaStream)
videoInputDeviceSetting!.startLocalVideoTile()
await videoInputDeviceSetting!.setVirtualBackgrounEnable(true)
await videoInputDeviceSetting!.setVirtualBackgroundSegmentationType("None")
}else{
await videoInputDeviceSetting!.setVideoInput(null)
videoInputDeviceSetting!.stopLocalVideoTile()
}
}
videoElem.src=path
videoElem.currentTime=0
videoElem.autoplay=true
videoElem.play()
}else{
console.log("not supported filetype", fileType)
}
}
input.click()
}
const onVirtualBGChange = async (e: any) => {
if (e.target.value === "None") {
videoInputDeviceSetting!.setVirtualBackgrounEnable(false)
videoInputDeviceSetting!.setVirtualBackgroundSegmentationType("None")
setGuiCounter(guiCounter+1)
} else {
videoInputDeviceSetting!.setVirtualBackgrounEnable(true)
videoInputDeviceSetting!.setVirtualBackgroundSegmentationType(e.target.value)
setGuiCounter(guiCounter+1)
}
}
const setBackgroundImage = () =>{
const input = document.createElement("input")
input.type = "file"
input.onchange = (e: any) => {
const path = URL.createObjectURL(e.target.files[0]);
const fileType = e.target.files[0].type
console.log(path, fileType)
if(fileType.startsWith("image")){
videoInputDeviceSetting!.setBackgroundImagePath(path)
}else{
console.log("not supported filetype", fileType)
}
}
input.click()
}
const onInputAudioChange = async (e: any) => {
//// for input movie experiment [start]
const videoElem = document.getElementById("for-input-movie")! as HTMLVideoElement
videoElem.pause()
videoElem.srcObject=null
videoElem.src=""
//// for input movie experiment [end]
if (e.target.value === "None") {
await audioInputDeviceSetting!.setAudioInput(null)
setGuiCounter(guiCounter+1)
} else {
await audioInputDeviceSetting!.setAudioInput(e.target.value)
setGuiCounter(guiCounter+1)
}
}
const onSuppressionChange = async (e:any) =>{
if (e.target.value === "None") {
await audioInputDeviceSetting!.setAudioSuppressionEnable(false)
setGuiCounter(guiCounter+1)
} else {
await audioInputDeviceSetting!.setAudioSuppressionEnable(true)
await audioInputDeviceSetting!.setVoiceFocusSpec({variant:e.target.value})
setGuiCounter(guiCounter+1)
}
}
const onOutputAudioChange = async (e: any) => {
if (e.target.value === "None") {
await audioOutputDeviceSetting!.setAudioOutput(null)
setGuiCounter(guiCounter+1)
} else {
await audioOutputDeviceSetting!.setAudioOutput(e.target.value)
setGuiCounter(guiCounter+1)
}
}
return(
<div>
<Dialog disableBackdropClick disableEscapeKeyDown scroll="paper" open={props.open} onClose={props.onClose} >
<DialogTitle>
<Typography gutterBottom>
Settings
</Typography>
</DialogTitle>
<DialogContent>
<Typography variant="h5" gutterBottom>
Devices and Effects
</Typography>
<form className={classes.form} noValidate>
<FormControl className={classes.formControl} >
<InputLabel>Camera</InputLabel>
<Select onChange={onInputVideoChange} value={videoInputDeviceSetting!.videoInput}>
<MenuItem disabled value="Video">
<em>Video</em>
</MenuItem>
{videoInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<div style={{display:"flex"}}>
<FormControl className={classes.formControl} >
<InputLabel>Virtual Background</InputLabel>
<Select onChange={onVirtualBGChange} value={videoInputDeviceSetting!.virtualBackgroundSegmentationType} >
<MenuItem disabled value="Video">
<em>VirtualBG</em>
</MenuItem>
<MenuItem value="None">
<em>None</em>
</MenuItem>
<MenuItem value="BodyPix">
<em>BodyPix</em>
</MenuItem>
<MenuItem value="GoogleMeet">
<em>GoogleMeet</em>
</MenuItem>
<MenuItem value="GoogleMeetTFLite">
<em>GoogleMeetTFLite</em>
</MenuItem>
</Select>
</FormControl>
{/* <Button variant="outlined" color="primary" onClick={()=>{bgFileInputRef.current!.click()}} size="small" > */}
<Button variant="outlined" color="primary" onClick={setBackgroundImage} size="small" >
<Typography variant="caption">
background image
</Typography>
</Button>
</div>
<FormControl className={classes.formControl} >
<InputLabel>Microhpone</InputLabel>
<Select onChange={onInputAudioChange} value={audioInputDeviceSetting!.audioInput} >
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{audioInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Noise Suppression</InputLabel>
<Select onChange={onSuppressionChange} value={audioInputDeviceSetting!.audioSuppressionEnable ? audioInputDeviceSetting!.voiceFocusSpec?.variant: "None" } >
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{["None", "auto", "c100", "c50", "c20", "c10"].map(val => {
return <MenuItem value={val} key={val}>{val}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel>Speaker</InputLabel>
<Select onChange={onOutputAudioChange} value={audioOutputDeviceSetting!.audioOutput} >
<MenuItem disabled value="Video">
<em>Speaker</em>
</MenuItem>
{audioOutputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId} >{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<div className={classes.lineSpacer} />
<div className={classes.lineSpacer} />
<Divider />
<Typography variant="h5">
Experimentals
</Typography>
<div style={{display:"flex"}}>
<div style={{width:"50%"}}>
<Typography variant="body1" >
Movie Input
</Typography>
<Typography variant="body2" >
Input movie instead of the camera.
When you use this featurem, camera device and microhpone device, virtual background are not choosen.
</Typography>
</div>
<div style={{width:"50%"}}>
<Button variant="outlined" color="primary" onClick={()=>{
setInputMovieFile(false)
// inputMovieFileInputRef.current!.click()
// exp_setNoise(false)
}}>
choose movie file
</Button>
<Button variant="outlined" color="primary" onClick={()=>{
setInputMovieFile(false)
// inputMovieFileInputRef.current!.click()
// exp_setNoise(true)
}}>
choose movie file (add noise)
</Button>
</div>
</div>
</form>
</DialogContent>
<DialogActions>
<Button onClick={props.onClose} color="primary">
Ok
</Button>
</DialogActions>
</Dialog>
<video id="for-input-movie" loop hidden />
</div>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/000_common/MessageDialg.tsx | <gh_stars>0
import { Avatar, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, makeStyles } from "@material-ui/core";
import React from "react";
import { ErrorOutline, Info} from "@material-ui/icons";
import { useAppState } from "../../providers/AppStateProvider";
const useStyles = makeStyles((theme) => ({
avatarForInformation: {
marginTop: theme.spacing(2),
backgroundColor: theme.palette.primary.main,
margin: "auto",
},
avatarForException: {
marginTop: theme.spacing(2),
backgroundColor: theme.palette.secondary.main,
margin: "auto",
},
}));
export const MessageDialog = () =>{
const { messageActive, messageType, messageTitle, messageDetail, resolveMessage } = useAppState()
const classes = useStyles();
return(
<>
{messageActive && (
<>
<Dialog open={messageActive} onClose={resolveMessage}>
{
messageType==="Info"?
<Avatar className={classes.avatarForInformation}>
<Info />
</Avatar>
:
<Avatar className={classes.avatarForException}>
<ErrorOutline />
</Avatar>
}
<DialogTitle >
{messageTitle }
</DialogTitle>
<DialogContent>
{
messageDetail.map((d,i)=>{
return(
<DialogContentText key={i}>
{d}
</DialogContentText>
)
})}
</DialogContent>
<DialogActions>
<Button onClick={resolveMessage} color="primary">
OK
</Button>
</DialogActions>
</Dialog>
</>
)}
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/022_waitingRoom/WaitingRoomAmongUs.tsx | <filename>frontend3/src/pages/022_waitingRoom/WaitingRoomAmongUs.tsx<gh_stars>0
import { Avatar, Box, Button, CircularProgress, Container, CssBaseline, FormControl, Grid, InputLabel, Link, makeStyles, MenuItem, Select, Typography } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { useAppState } from "../../providers/AppStateProvider";
import { MeetingRoom } from '@material-ui/icons'
import { Copyright } from "../000_common/Copyright";
import { DeviceInfo } from "../../utils";
const useStyles = makeStyles((theme) => ({
root: {
background: 'white',
},
root_amongus: {
background: 'black'
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.primary.main,
},
form: {
width: '100%',
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
margin: {
margin: theme.spacing(1),
},
input: {
color: 'black',
},
input_amongus: {
color: 'blue',
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
select: {
'&:before': {
borderColor: "blue",
color:"blue",
},
'&:after': {
borderColor: "blue",
color:"blue",
}
},
icon: {
fill: "blue",
},
label: {
color: "blue",
"&.Mui-focused": {
color: "blue",
},
},
}));
export const WaitingRoomAmongUs = () => {
const classes = useStyles()
const { mode, userId, userName, meetingName, audioInputList, audioOutputList,
audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting,
setStage, handleSignOut, reloadDevices, enterMeeting} = useAppState()
const [isLoading, setIsLoading] = useState(false)
//// Default Device ID
const defaultDeiceId = (deviceList: DeviceInfo[] | null) => {
if(!deviceList){
return "None"
}
const defaultDevice = deviceList.find(dev=>{return dev.deviceId !== "default"})
return defaultDevice ? defaultDevice.deviceId : "None"
}
const defaultAudioInputDevice = defaultDeiceId(audioInputList)
const defaultAudioOutputDevice = defaultDeiceId(audioOutputList)
const [audioInputDeviceId, setAudioInputDeviceId] = useState(defaultAudioInputDevice)
const [audioOutputDeviceId, setAudioOutputDeviceId] = useState(defaultAudioOutputDevice)
const onReloadDeviceClicked = () =>{
reloadDevices()
}
const onEnterClicked = () => {
setIsLoading(true)
enterMeeting().then(()=>{
setIsLoading(false)
videoInputDeviceSetting!.startLocalVideoTile()
setStage("MEETING_ROOM")
}).catch(e=>{
setIsLoading(false)
console.log(e)
})
}
useEffect(() => {
const videoEl = document.getElementById("camera-preview") as HTMLVideoElement
videoInputDeviceSetting!.setPreviewVideoElement(videoEl)
videoInputDeviceSetting!.setVirtualBackgroundSegmentationType("None").then(()=>{})
videoInputDeviceSetting!.setVideoInput(null).then(()=>{
videoInputDeviceSetting!.stopPreview()
})
videoInputDeviceSetting!.setVirtualForegrounEnable(false)
videoInputDeviceSetting!.setVirtualBackgrounEnable(false)
},[])// eslint-disable-line
useEffect(()=>{
if (audioInputDeviceId === "None") {
audioInputDeviceSetting!.setAudioInput(null)
} else {
audioInputDeviceSetting!.setAudioInput(audioInputDeviceId)
}
},[audioInputDeviceId])// eslint-disable-line
useEffect(()=>{
if (audioOutputDeviceId === "None") {
audioOutputDeviceSetting!.setAudioOutput(null)
} else {
audioOutputDeviceSetting!.setAudioOutput(audioOutputDeviceId)
}
},[audioOutputDeviceId]) // eslint-disable-line
return (
<Container maxWidth="xs" className={mode === "amongus" ? classes.root_amongus : classes.root}>
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<MeetingRoom />
</Avatar>
<Typography variant="h4" color={mode === "amongus" ? "secondary":"primary"} >
Waiting Meeting
</Typography>
<Typography color={mode === "amongus" ? "secondary":"primary"} >
You will join room <br />
(user:{userName}, room:{meetingName}) <br />
Setup your devices.
</Typography>
<form className={classes.form} noValidate>
<Button
fullWidth
variant="outlined"
color="primary"
onClick={onReloadDeviceClicked}
>
reload device list
</Button>
<FormControl className={classes.formControl} >
<InputLabel className={classes.label}>Microhpone</InputLabel>
<Select onChange={(e)=>{setAudioInputDeviceId(e.target.value! as string)}}
defaultValue={audioInputDeviceId}
className={classes.select}
inputProps={{
classes: {
icon: classes.icon,
},
className: classes.input_amongus
}}
>
<MenuItem disabled value="Video">
<em>Microphone</em>
</MenuItem>
{audioInputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId}>{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<FormControl className={classes.formControl} >
<InputLabel className={classes.label}>Speaker</InputLabel>
<Select onChange={(e)=>{setAudioOutputDeviceId(e.target.value! as string)}}
defaultValue={audioOutputDeviceId}
className={classes.select}
inputProps={{
classes: {
icon: classes.icon,
},
className: classes.input_amongus
}}
>
<MenuItem disabled value="Video">
<em>Speaker</em>
</MenuItem>
{audioOutputList?.map(dev => {
return <MenuItem value={dev.deviceId} key={dev.deviceId} >{dev.label}</MenuItem>
})}
</Select>
</FormControl>
<Grid container direction="column" alignItems="center" >
{
isLoading ?
<CircularProgress />
:
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onEnterClicked}
id="submit"
>
Enter
</Button>
}
</Grid>
<Grid container direction="column" >
<Grid item xs>
<Link onClick={(e: any) => { setStage("ENTRANCE") }}>
Go Back
</Link>
</Grid>
<Grid item xs>
<Link onClick={(e: any) => { handleSignOut(userId!); setStage("SIGNIN") }}>
Sign out
</Link>
</Grid>
</Grid>
<Box mt={8}>
<Copyright />
</Box>
</form>
</div>
</Container>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/021_createMeetingRoom/index.tsx | <filename>frontend3/src/pages/021_createMeetingRoom/index.tsx
import { Avatar, Box, Button, CircularProgress, Container, CssBaseline, FormControl, Grid, InputLabel, Link, makeStyles, MenuItem, Select, TextField, Typography, withStyles } from '@material-ui/core';
import { MeetingRoom } from '@material-ui/icons'
import React, { useState } from 'react';
import { AVAILABLE_AWS_REGIONS, DEFAULT_REGION } from '../../constants';
import { useAppState } from '../../providers/AppStateProvider';
import { Copyright } from '../000_common/Copyright';
const useStyles = makeStyles((theme) => ({
root: {
background: 'white',
},
root_amongus: {
background: 'black'
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.primary.main,
},
form: {
width: '100%',
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
margin: {
margin: theme.spacing(1),
},
input: {
color: 'black',
},
input_amongus: {
color: 'blue'
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
}));
const CustomTextField = withStyles({
root: {
'& input:valid + fieldset': {
borderColor: 'blue',
borderWidth: 1,
},
'& input:invalid + fieldset': {
borderColor: 'blue',
borderWidth: 1,
},
'& input:valid:focus + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:valid:hover + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:invalid:hover + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
color: 'blue'
// padding: '4px !important',
},
'& label.Mui-focused': {
color: 'blue',
},
'& label.MuiInputLabel-root': {
color: 'blue',
},
},
})(TextField);
export const CreateMeetingRoom = () => {
const classes = useStyles();
const { userId, handleSignOut, setStage, setMessage, createMeeting, mode} = useAppState()
const [meetingName, setMeetingName] = useState("")
const [region, setRegion] = useState(DEFAULT_REGION)
const [isLoading, setIsLoading] = useState(false)
const onCreateMeetingClicked = () => {
setIsLoading(true)
createMeeting(meetingName || "", "", region).then(()=>{
setMessage("Info", "Room created", [`room created, please join.`] )
setIsLoading(false)
setStage("ENTRANCE")
}).catch((e:any)=>{
setMessage("Exception", "Creating meeting room failed", [`room(${e.meetingName}) exist?: ${!e.created}`] )
setIsLoading(false)
})
}
return (
<Container maxWidth="xs" className={mode === "amongus" ? classes.root_amongus : classes.root}>
<CssBaseline />
<div className={classes.paper} style={{overflow:'auto'}}>
<Avatar className={classes.avatar}>
<MeetingRoom />
</Avatar>
<Typography variant="h4" color={mode === "amongus" ? "secondary":"primary"} >
Create Meeting
</Typography>
<form className={classes.form}>
<CustomTextField
required
variant="outlined"
margin="normal"
fullWidth
id="MeetingName"
name="MeetingName"
label="MeetingName"
autoFocus
value={meetingName}
onChange={(e) => setMeetingName(e.target.value)}
InputProps={{
className: mode === "amongus" ? classes.input_amongus : classes.input,
}}
/>
<Grid container direction="column" alignItems="center" >
<FormControl className={classes.formControl} >
<InputLabel>Region</InputLabel>
<Select value={region} onChange={(e: any) => setRegion(e.target.value)}>
<MenuItem disabled value="Video">
<em>Region</em>
</MenuItem>
{Object.keys(AVAILABLE_AWS_REGIONS).map(key => {
return <MenuItem value={key} key={key} >{AVAILABLE_AWS_REGIONS[key]}</MenuItem>
})}
</Select>
</FormControl>
{
isLoading ?
<CircularProgress />
:
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onCreateMeetingClicked}
>
Create Meeting
</Button>
}
</Grid>
<Grid container direction="column" >
<Grid item xs>
<Link onClick={(e: any) => { setStage("ENTRANCE") }}>
Join Room
</Link>
</Grid>
<Grid item xs>
<Link onClick={(e: any) => { handleSignOut(userId!); setStage("SIGNIN") }}>
Sign out
</Link>
</Grid>
</Grid>
<Box mt={8}>
<Copyright />
</Box>
</form>
</div>
</Container>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/utils/localLogger.ts |
export class LocalLogger{
private module
constructor(module:string){
this.module = module
}
log = (...strs:any[]) =>{
console.log(`[${this.module}]`, ...strs)
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/200_HeadlessMeetingManager/hooks/useStatusMonitor.ts | import { useEffect, useState } from "react"
import { useAppState } from "../../../providers/AppStateProvider"
import { useScheduler } from "../../../providers/hooks/useScheduler"
export const useStatusMonitor = () =>{
const { tenSecondsTaskTrigger } = useScheduler()
const { attendees, attendeeId, meetingSession } = useAppState()
const [ meetingActive, setMeetingActive ] = useState(true)
const [ noAttendeesCount, setNoAttendeesCount] = useState(0)
useEffect(()=>{
if(!attendeeId){ // not yet ready
return
}
//// exclude hmm and shared contents
let meetingActive = true
const pureAttendees = Object.keys(attendees).filter(x =>{return x.indexOf(attendeeId) < 0})
if(pureAttendees.length > 0){
meetingActive = true
}else{
meetingActive = false
}
console.log("meetingActive1:", meetingActive, pureAttendees)
const attendeeList = pureAttendees.reduce((prev,cur)=>{return prev+"_____"+cur}, "")
console.log(`meetingActive2:${attendeeList}`)
console.log(`meetingActive3:${meetingSession?.audioVideo.hasStartedLocalVideoTile()?"started":"stop"}`)
if(meetingActive){
setNoAttendeesCount(0)
}else{
setNoAttendeesCount(noAttendeesCount + 1)
console.log(`meetingActive checker count: ${noAttendeesCount}`)
if(noAttendeesCount > 5){
setMeetingActive(false)
}
}
},[tenSecondsTaskTrigger]) // eslint-disable-line
return {meetingActive}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useMeetingState.ts | import { useEffect, useMemo, useState } from "react"
import { VideoTileState } from "amazon-chime-sdk-js";
import { AttendeeState, ChimeClient } from "../helper/ChimeClient";
import { Recorder } from "../helper/Recorder";
import { getMeetingInfo } from "../../api/api";
import { useScheduler } from "./useScheduler";
import * as api from '../../api/api'
type UseMeetingStateProps = {
userId?: string,
idToken?: string,
accessToken?: string,
refreshToken?: string
}
export const useMeetingState = (props:UseMeetingStateProps) => {
const [stateCounter, setStateCounter] = useState(0) // Used for notifying chimeClient internal change.
const [userName, setUserName] = useState("")
const [meetingName, setMeetingName] = useState("")
const [meetingId, setMeetingId] = useState("")
const [joinToken, setJoinToken] = useState("")
const [attendees, setAttendees] = useState<{ [attendeeId: string]: AttendeeState }>({})
const [videoTileStates, setVideoTileStates] = useState<{ [attendeeId: string]: VideoTileState }>({})
const [isShareContent, setIsShareContent] = useState(false)
const [activeSpeakerId, setActiveSpeakerId] = useState<string|null>(null)
const [attendeeId, setAttendeeId] = useState<string>("")
const [ownerId, setOwnerId] = useState("")
const [isOwner, setIsOwner] = useState(false)
const chimeClient = useMemo(()=>{return new ChimeClient()},[])
const {tenSecondsTaskTrigger} = useScheduler()
// For Recorder
const activeRecorder = useMemo(()=>{return new Recorder()},[])
const allRecorder = useMemo(()=>{return new Recorder()},[])
if(props.userId && props.idToken && props.accessToken && props.refreshToken){
chimeClient.init(props.userId, props.idToken, props.accessToken, props.refreshToken)
chimeClient.userNameUpdated = (val:string) => {setUserName(val)}
chimeClient.meetingNameUpdated = (val:string) => {setMeetingName(val)}
chimeClient.meetingIdUpdated = (val:string) => {setMeetingId(val)}
chimeClient.joinTokenUpdated = (val:string) => {setJoinToken(val)}
chimeClient.attendeesUpdated = (val:{ [attendeeId: string]: AttendeeState } ) => {setAttendees({...val})}
chimeClient.videoTileStatesUpdated = (val:{ [attendeeId: string]: VideoTileState } ) => {setVideoTileStates({...val})}
chimeClient.isShareContentUpdated = (val:boolean) =>{setIsShareContent(val)}
chimeClient.activeSpeakerIdUpdated = (val:string|null)=>{
console.log("[ActiveSpeaker] update", val)
setActiveSpeakerId(val)
}
chimeClient.attendeeIdUpdated = (val:string) =>{setAttendeeId(val)}
}
const createMeeting = chimeClient.createMeeting
// const joinMeeting = chimeClient.joinMeeting
const joinMeeting = async (meetingName: string, userName: string) => {
await chimeClient.joinMeeting(meetingName, userName)
setStateCounter(stateCounter + 1 )
}
const enterMeeting = async () => {
await chimeClient.enterMeeting()
updateMeetingInfo()
setStateCounter(stateCounter + 1 )
}
const leaveMeeting = async() =>{
await chimeClient.leaveMeeting()
setStateCounter(stateCounter + 1 )
}
const countAttendees = chimeClient.countAttendees
const meetingSession = chimeClient._meetingSession
const audioInputDeviceSetting = chimeClient._audioInputDeviceSetting
const videoInputDeviceSetting = chimeClient._videoInputDeviceSetting
const audioOutputDeviceSetting = chimeClient._audioOutputDeviceSetting
////////////////////////
// Features
///////////////////////
const startShareScreen = async () => {
try{
// @ts-ignore https://github.com/microsoft/TypeScript/issues/31821
const media = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true } )
chimeClient.startShareContent(media)
}catch(e){
console.log(e)
}
}
const stopShareScreen = async () => {
chimeClient.stopShareContent()
}
////////////////////////
// Util
///////////////////////
const getUserNameByAttendeeIdFromList = (attendeeId: string) => {
return attendees[attendeeId] ? attendees[attendeeId].name : attendeeId
}
const updateMeetingInfo = async () =>{
const meetingInfo = await getMeetingInfo(meetingName, props.idToken!, props.accessToken!, props.refreshToken!)
const ownerId = meetingInfo.Metadata.OwnerId
console.log(meetingInfo)
console.log("new ownerId", ownerId)
setOwnerId(ownerId)
setIsOwner(props.userId === ownerId)
}
const setPauseVideo = (attendeeId:string, pause:boolean) =>{
console.log("SET PAUSE VIDEO", attendeeId, pause)
chimeClient.setPauseVideo(attendeeId, pause)
}
///////////////////////////
/// for recovery
///////////////////////////
//// Retrieve attendee name
useEffect(()=>{
(async() => {
let updated = false
for(let x of Object.values(attendees)){
if(x.name === x.attendeeId){
try{
const res = await api.getUserNameByAttendeeId(meetingName, x.attendeeId, props.idToken!, props.accessToken!, props.refreshToken!)
x.name = res.name
updated = true
}catch(exception){
console.log(`username update failed ${x.attendeeId}`)
}
}
}
if(updated){
setAttendees({...attendees})
}
})()
},[tenSecondsTaskTrigger]) // eslint-disable-line
return { meetingName, meetingId, joinToken, attendeeId, userName, attendees, videoTileStates,
meetingSession, activeRecorder, allRecorder, audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting,
isShareContent, activeSpeakerId,
createMeeting, joinMeeting, enterMeeting, leaveMeeting,
startShareScreen, stopShareScreen,
getUserNameByAttendeeIdFromList,
countAttendees,
updateMeetingInfo, ownerId, isOwner,
setPauseVideo,
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/000_common/Copyright.tsx | import React, { useMemo } from "react";
import { Typography, Link } from '@material-ui/core'
export const Copyright = () => {
const copyright = useMemo(()=>{
return (
<Typography color="textSecondary" align="center">
Copyright ©
<Link color="inherit" href="https://www.flect.co.jp/">
FLECT, Co., Ltd.
</Link>{' '}
{new Date().getFullYear()}
</Typography>
);
},[])
return <>{copyright}</>
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/DialogOpener.tsx | <filename>frontend3/src/pages/023_meetingRoom/components/appbars/DialogOpener.tsx
import { IconButton, Tooltip } from "@material-ui/core"
import {Settings, ExitToApp} from '@material-ui/icons'
import React, { useMemo } from "react"
import clsx from 'clsx';
import { useStyles } from "../../css";
type DialogType = "Setting" | "LeaveMeeting"
type DialogOpenerProps = {
type: DialogType
onClick:()=>void
}
export const DialogOpener = (props:DialogOpenerProps) =>{
const classes = useStyles()
const icon = useMemo(()=>{
switch(props.type){
case "Setting":
return <Settings />
case "LeaveMeeting":
return <ExitToApp />
}
},[props.type])
const tooltip = useMemo(()=>{
switch(props.type){
case "Setting":
return "Setting"
case "LeaveMeeting":
return "Leave Meeting"
}
},[props.type])
const enabler = useMemo(()=>{
return(
<Tooltip title={tooltip}>
<IconButton color="inherit" className={clsx(classes.menuButton)} onClick={props.onClick}>
{icon}
</IconButton>
</Tooltip>
)
},[props.type]) // eslint-disable-line
return(
<>
{enabler}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/RealtimeSubscribers/useAmongUs.ts | <filename>frontend3/src/providers/hooks/RealtimeSubscribers/useAmongUs.ts
import { useState } from "react"
import { getUserNameByAttendeeId } from "../../../api/api"
export const STATES = [
'LOBBY', // 0
'TASKS', // 1
'DISCUSSION', // 2
'MENU' // 3
]
export const REGIONS = [
'North America',
'Asia',
'Europe'
]
export const ACTIONS = [
'JOIN', // 0
'LEAVE', // 1
'KILL', // 2
'COLOR_CHANGE', // 3
'FORCE_UPDATE', // 4
'DISCONNECT', // 5
'EXILE' // 6
]
export const COLORS = [
'red',
'blue',
'green',
'pink',
'orange',
'yellow',
'black',
'white',
'purple',
'brown',
'cyan',
'lime',
'maroon',
'rose',
'banana',
'tan',
'sunset',
]
export const ICONS_ALIVE = COLORS.map(x=>{
return `resources/amongus/${x}.png`
})
export const ICONS_DEAD = COLORS.map(x=>{
return `resources/amongus/${x}_dead.png`
})
// public enum PlayMap {
// Skeld = 0,
// Mira = 1,
// Polus = 2,
// dlekS = 3,
// Airship = 4,
// }
type PlayerState = {
name:string
isDead:boolean
isDeadDiscovered:boolean
disconnected:boolean
color:number
action:number
attendeeId?:string
chimeName?:string
}
export type GameState = {
hmmAttendeeId:string
state:number
lobbyCode:string
gameRegion:number
map:number
connectCode:string
players:PlayerState[]
}
const initialState:GameState = {
hmmAttendeeId:"",
state:3,
lobbyCode:"",
gameRegion:0,
map:0,
connectCode:"",
players: [],
}
type UseAmongUsProps = {
attendeeId:string
meetingName?: string
idToken?: string
accessToken?: string
refreshToken?: string
}
export const useAmongUs = (props:UseAmongUsProps) =>{
const [ gameState, setGameState] = useState(initialState)
const updateGameState = (ev:string, data:string) => {
const newGameState = JSON.parse(data) as GameState
newGameState.hmmAttendeeId = props.attendeeId
// Copy user name
gameState.players.forEach(x =>{
if(x.attendeeId){
const newPlayer = newGameState.players.find(y=>{return x.name === y.name})
if(newPlayer){
newPlayer.attendeeId = x.attendeeId
newPlayer.chimeName = x.chimeName
}
}
})
// // update isDead discvoered
// if(newGameState.state == 2){ // When state is Discussion, isDead state can be discovered
// newGameState.players.forEach(x=>{
// if(x.isDead){
// x.isDeadDiscovered = true
// }
// })
// }
// // update purged
// if(newGameState.state == 1 && gameState.state == 2){ // When state is changed from Discussion to Tasks, purged state can be discovered
// newGameState.players.forEach(x=>{
// if(x.isDead){
// x.isDeadDiscovered = true
// }
// })
// }
setGameState(newGameState)
}
const registerUserName = async (userName:string, attendeeId:string) =>{
const unregisterTarget = gameState.players.find(x=>{return x.attendeeId === attendeeId})
if(unregisterTarget){
unregisterTarget.attendeeId = undefined
unregisterTarget.chimeName = undefined
}
const targetPlayer = gameState.players.find(x=>{return x.name === userName})
if(!targetPlayer){
console.log(`user ${userName} is not found`)
setGameState({...gameState})
return
}
if(targetPlayer.attendeeId){
console.log(`${targetPlayer.name} is already registered as ${targetPlayer.attendeeId}`)
setGameState({...gameState})
return
}
targetPlayer.attendeeId = attendeeId
targetPlayer.chimeName = (await getUserNameByAttendeeId(props.meetingName!, attendeeId, props.idToken!, props.accessToken!, props.refreshToken!)).name
console.log(`${targetPlayer.name} is registaerd as ${targetPlayer.attendeeId}`)
setGameState({...gameState})
}
return {gameState, updateGameState, registerUserName}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/hooks/useStageManager.ts | import { useState } from "react"
type UseStageManagerProps = {
initialStage : STAGE | null,
}
export type STAGE = "SIGNIN" | "SIGNUP" | "VERIFY" | "REQUEST_NEW_PASSWORD" | "NEW_PASSWORD"
| "ENTRANCE" | "CREATE_MEETING_ROOM" | "WAITING_ROOM" | "MEETING_ROOM"
| "MEETING_MANAGER_SIGNIN" | "MEETING_MANAGER"
| "HEADLESS_MEETING_MANAGER" | "HEADLESS_MEETING_MANAGER2"
| "MEETING_MANAGER_SIGNIN3" | "MEETING_MANAGER3"
export const useStageManager = (props:UseStageManagerProps) =>{
const [stage, setStage] = useState<STAGE>(props.initialStage||"SIGNIN")
return {stage, setStage}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/providers/helper/AudioOutputDeviceSetting.ts | import { MeetingSession } from "amazon-chime-sdk-js"
export class AudioOutputDeviceSetting{
private meetingSession:MeetingSession
audioOutput:string|null = null
audioOutputEnable:boolean = true
outputAudioElement:HTMLAudioElement|null=null
constructor(meetingSession:MeetingSession){
this.meetingSession = meetingSession
}
///////////////
// AudioOutput
///////////////
private setAudioOutputCommon = async (device: string|null, enable:boolean) => {
/// no use audio output
if(device===null || enable===false){
console.log("[DeviceSetting] AudioOutput is null or disabled.")
await this.meetingSession.audioVideo.chooseAudioOutputDevice(null)
return
}
/// for standard audio output
console.log("[DeviceSetting] Change AudioOutput.")
try{
await this.meetingSession.audioVideo.chooseAudioOutputDevice(device)
}catch(excpetion){
console.log(`[DeviceSetting] Change AudioOutput is failed:${excpetion}`)
}
}
setAudioOutput = async (val: string | null) => {
this.audioOutput = val
await this.setAudioOutputCommon(this.audioOutput, this.audioOutputEnable)
this.setRelationToAudioElement()
}
setAudioOutputEnable = async (val:boolean) => {
this.audioOutputEnable = val
await this.setAudioOutputCommon(this.audioOutput, this.audioOutputEnable)
this.setRelationToAudioElement()
}
setOutputAudioElement = (val:HTMLAudioElement) =>{
this.outputAudioElement = val
this.setRelationToAudioElement()
}
private setRelationToAudioElement = () => {
if(this.audioOutputEnable && this.audioOutput){
this.bindOutputAudioElement()
}else{
this.unbindOutputAudioElement()
}
}
private bindOutputAudioElement = async() =>{
if(this.outputAudioElement){
await this.meetingSession.audioVideo.bindAudioElement(this.outputAudioElement)
}else{
console.log("[DeviceSetting] OutputAudioElement is not set for bind.")
}
}
private unbindOutputAudioElement = () =>{
this.meetingSession.audioVideo.unbindAudioElement()
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/RecorderPanel.tsx | import React, { useMemo, useState } from 'react';
import { Button, CircularProgress, Tooltip, Typography } from '@material-ui/core';
import { Pause, FiberManualRecord } from '@material-ui/icons'
import { useStyles } from './css';
import { useAppState } from '../../../../providers/AppStateProvider';
import { DefaultDeviceController } from 'amazon-chime-sdk-js';
import { RecorderView } from '../ScreenView/RecorderView';
export const RecorderPanel = () => {
const classes = useStyles();
const { activeRecorder, audioInputDeviceSetting } = useAppState()
const [recorderCanvas, setRecorderCanvas] = useState<HTMLCanvasElement|null>(null)
const [ isEncoding, setIsEncoding ] = useState(false)
const [ isRecording, setIsRecording ] = useState(false)
const handleOnClickStartRecord = async() =>{
setIsRecording(true)
const stream = new MediaStream();
const audioElem = document.getElementById("for-speaker") as HTMLAudioElement
// @ts-ignore
const audioStream = audioElem.captureStream() as MediaStream
let localAudioStream = audioInputDeviceSetting?.audioInputForRecord
if(typeof localAudioStream === "string"){
localAudioStream = await navigator.mediaDevices.getUserMedia({audio:{deviceId:localAudioStream}})
}
const audioContext = DefaultDeviceController.getAudioContext();
const outputNode = audioContext.createMediaStreamDestination();
const sourceNode1 = audioContext.createMediaStreamSource(audioStream);
sourceNode1.connect(outputNode)
if(localAudioStream){
const sourceNode2 = audioContext.createMediaStreamSource(localAudioStream as MediaStream);
sourceNode2.connect(outputNode)
}
// @ts-ignore
const videoStream = recorderCanvas.captureStream() as MediaStream
[outputNode.stream, videoStream].forEach(s=>{
s?.getTracks().forEach(t=>{
console.log("added tracks:", t)
stream.addTrack(t)
})
});
activeRecorder?.startRecording(stream)
}
const handleOnClickStopRecord = async() =>{
activeRecorder?.stopRecording()
setIsEncoding(true)
await activeRecorder?.toMp4()
console.log("---------------------------------------------------- 1")
setIsEncoding(false)
console.log("---------------------------------------------------- 2")
setIsRecording(false)
console.log("---------------------------------------------------- 3")
}
const startButton = useMemo(()=>{
return isRecording === false && isEncoding === false ?
(
<Tooltip title={activeRecorder?.isRecording?"stop recording":"start recording"}>
<Button
size="small"
variant="outlined"
className={activeRecorder?.isRecording ? classes.activatedButton : classes.button}
startIcon={<FiberManualRecord />}
onClick={handleOnClickStartRecord}
id="recorder-start"
>
Rec.
</Button>
</Tooltip>
)
:
(
<Tooltip title={activeRecorder?.isRecording?"stop recording":"start recording"}>
<Button
size="small"
variant="outlined"
className={activeRecorder?.isRecording ? classes.activatedButton : classes.button}
startIcon={<FiberManualRecord />}
id="recorder-start"
>
Rec.
</Button>
</Tooltip>
)
},[isRecording, isEncoding, recorderCanvas]) // eslint-disable-line
const stopButton = useMemo(()=>{
if(isRecording === false && isEncoding === false){
return <Tooltip title={activeRecorder?.isRecording?"stop recording":"start recording"}>
<Button
size="small"
variant="outlined"
className={classes.button}
startIcon={<Pause />}
disabled
id="recorder-stop"
>
Stop
</Button>
</Tooltip>
}else if(isRecording === true && isEncoding === false){
return <Tooltip title={activeRecorder?.isRecording?"stop recording":"start recording"}>
<Button
size="small"
variant="outlined"
className={classes.button}
startIcon={<Pause />}
onClick={handleOnClickStopRecord}
id="recorder-stop"
>
Stop
</Button>
</Tooltip>
}else if(isRecording === true && isEncoding === true){
return <CircularProgress />
}
},[isRecording, isEncoding, recorderCanvas]) // eslint-disable-line
return (
<div className={classes.root}>
<Typography className={classes.title} color="textSecondary">
Push REC button to start recording. Push STOP button to end recording and download file.
Note: Please confirm the screen below shows the movie you want to record.
Depends on the browser or its version, you should display the screen below in order to update image on the screen below.
</Typography>
{startButton}
{stopButton}
<RecorderView height={200} width={200} setRecorderCanvas={setRecorderCanvas}/>
</div>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/providers/helper/ChimeClient.ts |
import { ConsoleLogger, DefaultActiveSpeakerPolicy, DefaultDeviceController, DefaultMeetingSession, LogLevel, MeetingSessionConfiguration, VideoTileState } from "amazon-chime-sdk-js";
import * as api from '../../api/api'
import AudioVideoObserverTemplate from "../observers/AudioVideoObserver";
import { DeviceChangeObserverImpl } from "../observers/DeviceChangeObserverImpl";
import { AudioInputDeviceSetting } from "./AudioInputDeviceSetting";
import { AudioOutputDeviceSetting } from "./AudioOutputDeviceSetting";
import { VideoInputDeviceSetting } from "./VideoInputDeviceSetting";
export type AttendeeState = {
attendeeId: string
name: string
active: boolean
score: number // active score
volume: number // volume
muted: boolean
paused: boolean
signalStrength: number
isSharedContent: boolean
ownerId: string
isVideoPaused:boolean
}
export class ChimeClient {
private userId?: string
private idToken?: string
private accessToken?: string
private refreshToken?: string
init = (userId: string, idToken: string, accessToken: string, refreshToken: string) => {
this.userId = userId
this.idToken = idToken
this.accessToken = accessToken
this.refreshToken = refreshToken
}
private userName?:string // Note: update with accessor for update listener
private attendeeId?:string
private meetingName?:string // Note: update with accessor for update listener
private meetingId?:string // Note: update with accessor for update listener
private joinToken?:string
private attendees: { [attendeeId: string]: AttendeeState } = {} // Note: update with accessor for update listener
private videoTileStates: { [attendeeId: string]: VideoTileState } = {} // Note: update with accessor for update listener
private isShareContent:boolean = false
private activeSpeakerId:string|null = null
userNameUpdated: (val:string)=>void = (val:string) => {}
attendeeIdUpdated: (val:string)=>void = (val:string) => {}
meetingNameUpdated: (val:string)=>void = (val:string) => {}
meetingIdUpdated: (val:string)=>void = (val:string) => {}
joinTokenUpdated: (val:string)=>void = (val:string) => {}
attendeesUpdated: (val:{ [attendeeId: string]: AttendeeState } )=>void = () =>{}
videoTileStatesUpdated: (val:{ [attendeeId: string]: VideoTileState } )=>void = () =>{}
isShareContentUpdated : (val:boolean)=>void = () =>{}
activeSpeakerIdUpdated: (val:string|null) => void = () =>{}
set _meetingName(val:string){
this.meetingName=val
this.meetingNameUpdated(val)
}
set _meetingId(val:string){
this.meetingId=val
this.meetingIdUpdated(val)
}
set _joinToken(val:string){
this.joinToken = val
this.joinTokenUpdated(val)
}
set _userName(val:string){
this.userName = val
this.userNameUpdated(val)
}
set _attendeeId(val:string){
this.attendeeId = val
this.attendeeIdUpdated(val)
}
get _attendees():{ [attendeeId: string]: AttendeeState }{
return this.attendees
}
set _attendees(val:{ [attendeeId: string]: AttendeeState }){
this.attendees = val
this.attendeesUpdated(val)
}
get _videoTileStates():{ [attendeeId: string]: VideoTileState }{
return this.videoTileStates
}
set _videoTileStates(val:{ [attendeeId: string]: VideoTileState } ){
this.videoTileStates = val
this.videoTileStatesUpdated(val)
}
get _isShareContent():boolean{
return this.isShareContent
}
set _isShareContent(val:boolean){
this.isShareContent = val
this.isShareContentUpdated(val)
}
set _activeSpeakerId(val:string|null){
this.activeSpeakerId = val
this.activeSpeakerIdUpdated(val)
}
private meetingSession?: DefaultMeetingSession
private audioInputDeviceSetting?: AudioInputDeviceSetting
private videoInputDeviceSetting?: VideoInputDeviceSetting
private audioOutputDeviceSetting?: AudioOutputDeviceSetting
get _meetingSession():DefaultMeetingSession | undefined{
return this.meetingSession
}
get _audioInputDeviceSetting():AudioInputDeviceSetting | undefined{
return this.audioInputDeviceSetting
}
get _videoInputDeviceSetting():VideoInputDeviceSetting | undefined{
return this.videoInputDeviceSetting
}
get _audioOutputDeviceSetting():AudioOutputDeviceSetting | undefined{
return this.audioOutputDeviceSetting
}
///////////////////////////////////////////
// Feature Management
///////////////////////////////////////////
startShareContent = async (media:MediaStream) =>{
await this.meetingSession!.audioVideo.startContentShare(media)
this._isShareContent = true
}
stopShareContent = async () =>{
await this.meetingSession!.audioVideo.stopContentShare()
this._isShareContent = false
}
///////////////////////////////////////////
// Meeting Management
///////////////////////////////////////////
/**
* Create Meeting Room
* @param meetingName
* @param userName
* @param region
*/
createMeeting = async (meetingName: string, userName: string, region: string) => {
const res = await api.createMeeting(meetingName, region, this.idToken!, this.accessToken!, this.refreshToken!)
if (!res.created) {
console.log("[createMeeting] meeting create failed", res)
throw new Error(`Meeting Create Failed`)
}
return res
}
/**
* Join Meeting Room
* @param meetingName
* @param userName
*/
joinMeeting = async (meetingName: string, userName: string) => {
if (meetingName === "") {
throw new Error("Meeting name is invalid")
}
if (userName === "") {
throw new Error("Username is invalid")
}
const joinInfo = await api.joinMeeting(meetingName, userName, this.idToken!, this.accessToken!, this.refreshToken!)
console.log("JoinInfo:", joinInfo)
if (joinInfo['code']) {
throw new Error("Failed to join")
}
const meetingInfo = joinInfo.Meeting
const attendeeInfo = joinInfo.Attendee
console.log("[Join Meeting] ", meetingInfo, attendeeInfo)
this._meetingName = meetingName
this._meetingId = meetingInfo.MeetingId
this._joinToken = attendeeInfo.JoinToken
this._userName = userName
this._attendeeId = attendeeInfo.AttendeeId
// (1) creating meeting session
//// (1-1) creating configuration
const configuration = new MeetingSessionConfiguration(meetingInfo, attendeeInfo)
//// (1-2) creating logger
const logger = new ConsoleLogger('MeetingLogs', LogLevel.OFF)
//// (1-3) creating device controller
const deviceController = new DefaultDeviceController(logger, {
enableWebAudio: true,
})
const deviceChangeObserver = new DeviceChangeObserverImpl()
deviceController.addDeviceChangeObserver(deviceChangeObserver)
//// (1-4) create meeting session
this.meetingSession = new DefaultMeetingSession(configuration, logger, deviceController)
//// (1-5) create AudioVideoObserver
const audioVideoOserver = new AudioVideoObserverTemplate()
audioVideoOserver.videoTileDidUpdate = (tileState: VideoTileState) => {
if (!tileState.boundAttendeeId) {
console.log("[AudioVideoObserver] updated tile have no boundAttendeeID", tileState)
return
}
if (!this.videoTileStates[tileState.boundAttendeeId]) {
console.log("[AudioVideoObserver] new tile added", tileState)
this.videoTileStates[tileState.boundAttendeeId] = tileState
this._videoTileStates = this.videoTileStates
return
}
console.log("[AudioVideoObserver] no change?", tileState)
}
audioVideoOserver.videoTileWasRemoved = (tileId: number) => {
// There are the risk to overwrite new commer who is assgined same tileid, but tile id is generally incremented one by one
// so, the probability to have this problem is very low: TODO: fix
this.meetingSession?.audioVideo.unbindVideoElement(tileId)
console.log("[AudioVideoObserver] videoTileWasRemoved", tileId)
const removedAttendeeId = Object.values(this.videoTileStates).find(x => { return x.tileId === tileId })?.boundAttendeeId
console.log("[AudioVideoObserver] removedAttendeeId", removedAttendeeId)
if (removedAttendeeId) {
delete this.videoTileStates[removedAttendeeId]
this._videoTileStates = this.videoTileStates
}
}
this.meetingSession.audioVideo.addObserver(audioVideoOserver)
// (2) DeviceSetting
this.audioInputDeviceSetting = new AudioInputDeviceSetting(this.meetingSession)
this.videoInputDeviceSetting = new VideoInputDeviceSetting(this.meetingSession)
this.audioOutputDeviceSetting = new AudioOutputDeviceSetting(this.meetingSession)
// (3) List devices
//// chooseAudioOutputDevice uses the internal cache
//// so beforehand, we must get thses information. (auidoinput, videoinput are maybe optional)
await this.meetingSession?.audioVideo.listAudioInputDevices()
await this.meetingSession?.audioVideo.listVideoInputDevices()
await this.meetingSession?.audioVideo.listAudioOutputDevices()
}
/**
* Enter Meeting Room
*/
enterMeeting = async () => {
if (!this.meetingSession) {
console.log("meetingsession is null?", this.meetingSession)
throw new Error("meetingsession is null?")
}
// (1) prepair
//// https://github.com/aws/amazon-chime-sdk-js/issues/502#issuecomment-652665492
//// When stop preview, camera stream is terminated!!? So when enter meeting I rechoose Devices as workaround. (2)
this.videoInputDeviceSetting?.stopPreview()
// (2) subscribe AtttendeeId presence
this.meetingSession.audioVideo.realtimeSubscribeToAttendeeIdPresence(async (attendeeId: string, present: boolean) => {
console.log(`[AttendeeIdPresenceSubscriber] ${attendeeId} present = ${present}`);
if (present) {
if (attendeeId in this.attendees === false) {
let userName = ""
if(attendeeId.indexOf("#")>0){
userName = attendeeId
}else{
try{
const result = await api.getUserNameByAttendeeId(this.meetingName!, attendeeId, this.idToken!, this.accessToken!, this.refreshToken!)
userName = result.result === "success" ? result.name : attendeeId
}catch{
userName = attendeeId
}
}
// Add to Attendee List
const new_attendee: AttendeeState = {
attendeeId: attendeeId,
name: userName,
active: false,
score: 0,
volume: 0,
muted: false,
paused: false,
signalStrength: 0,
isSharedContent: false,
ownerId: "",
isVideoPaused:false,
}
if (attendeeId.split("#").length === 2) {
new_attendee.isSharedContent = true
new_attendee.ownerId = attendeeId.split("#")[0]
}
this.attendees[attendeeId] = new_attendee
this._attendees = this.attendees
// Add Subscribe volume Indicator
this.meetingSession!.audioVideo.realtimeSubscribeToVolumeIndicator(attendeeId,
async (
attendeeId: string,
volume: number | null,
muted: boolean | null,
signalStrength: number | null
) => {
this.attendees[attendeeId].volume = volume || 0
this.attendees[attendeeId].muted = muted || false
this.attendees[attendeeId].signalStrength = signalStrength || 0
this._attendees = this.attendees
}
)
} else {
console.log(`[AttendeeIdPresenceSubscriber] ${attendeeId} is already in attendees`);
}
return;
} else {
// Delete Subscribe volume Indicator
this.meetingSession!.audioVideo.realtimeUnsubscribeFromVolumeIndicator(attendeeId)
delete this.attendees[attendeeId]
this._attendees = this.attendees
return;
}
})
// (3) subscribe ActiveSpeakerDetector
this.meetingSession.audioVideo.subscribeToActiveSpeakerDetector(
new DefaultActiveSpeakerPolicy(),
(activeSpeakers: string[]) => {
console.log("Active Speaker::::::::::::::::::::", activeSpeakers)
let activeSpeakerId:string|null = null
for (const attendeeId in this.attendees) {
this.attendees[attendeeId].active = false;
}
for (const attendeeId of activeSpeakers) {
if (this.attendees[attendeeId]) {
this.attendees[attendeeId].active = true;
activeSpeakerId = attendeeId
break
}
}
this._attendees = this.attendees
if(this.activeSpeakerId !== activeSpeakerId){
this._activeSpeakerId = activeSpeakerId
}
},
(scores: { [attendeeId: string]: number }) => {
for (const attendeeId in scores) {
if (this.attendees[attendeeId]) {
this.attendees[attendeeId].score = scores[attendeeId];
}
}
this._attendees = this.attendees
}, 5000)
// (4) start
this.meetingSession?.audioVideo.start()
await this.videoInputDeviceSetting!.setVideoInputEnable(true)
await this.audioInputDeviceSetting!.setAudioInputEnable(true)
await this.audioOutputDeviceSetting!.setAudioOutputEnable(true)
}
leaveMeeting = async () => {
if (!this.meetingSession) {
console.log("meetingsession is null?", this.meetingSession)
throw new Error("meetingsession is null?")
}
await this.audioInputDeviceSetting!.setAudioInput(null)
await this.videoInputDeviceSetting!.setVideoInput(null)
await this.audioOutputDeviceSetting!.setAudioOutput(null)
this.videoInputDeviceSetting!.stopPreview()
this.meetingSession.audioVideo.stopLocalVideoTile()
this.meetingSession.audioVideo.stop()
this._userName = ""
this._meetingName = ""
this._attendees = {}
this._videoTileStates = {}
}
countAttendees = async() =>{
console.log("countAttendees")
const res = await api.getAttendeeList(this.meetingName!, this.idToken!, this.accessToken!, this.refreshToken!)
console.log("countAttendees",res)
}
setPauseVideo = (attendeeId:string, pause:boolean) =>{
if(this.attendees[attendeeId]){
this.attendees[attendeeId].isVideoPaused = pause
if(pause){
this.meetingSession!.audioVideo.unbindVideoElement(this.videoTileStates[attendeeId].tileId!)
this.meetingSession!.audioVideo.pauseVideoTile(this.videoTileStates[attendeeId].tileId!)
}else{
this.meetingSession!.audioVideo.unpauseVideoTile(this.videoTileStates[attendeeId].tileId!)
}
this.attendeesUpdated(this.attendees)
}else{
}
}
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/BGMPanel.tsx | import React, { useMemo, useState } from 'react';
import { Button, IconButton, Slider } from '@material-ui/core';
import { PlayArrow, Stop, VolumeDown, VolumeUp } from '@material-ui/icons'
import { useAppState } from '../../../../providers/AppStateProvider';
import { RS_SE } from '../../../../resources';
import { useStyles } from './css';
export const BGMPanel = () => {
const classes = useStyles();
const [ isPlaying, setIsPlaying ] = useState(false)
const { audioInputDeviceSetting } = useAppState()
const [ volume, setVolume] = React.useState(30);
const playBGM = (path:string) => {
const elem = document.getElementById("bgm_panel_audio") as HTMLAudioElement
elem.pause()
elem.srcObject = null
elem.src = path
elem.onended = () =>{
setIsPlaying(false)
}
elem.onloadeddata = async (e) =>{
// @ts-ignore
const mediaStream = elem.captureStream() as MediaStream
audioInputDeviceSetting?.setBackgroundMusic(mediaStream)
elem.play()
setIsPlaying(true)
}
}
const togglePlay = () =>{
const elem = document.getElementById("bgm_panel_audio") as HTMLAudioElement
elem.paused ? setIsPlaying(true):setIsPlaying(false)
elem.paused ? elem.play() : elem.pause()
}
const handleVolumeChange = (event: any, newValue: number | number[]) => {
const elem = document.getElementById("bgm_panel_audio") as HTMLAudioElement
if(typeof(newValue)==="number"){
audioInputDeviceSetting?.setBackgroundMusicVolume(newValue)
elem.volume=newValue
setVolume(newValue);
}else if(Array.isArray(newValue)){
audioInputDeviceSetting?.setBackgroundMusicVolume(newValue[0])
elem.volume=newValue[0]
setVolume(newValue[0]);
}
};
const fileClicked = () =>{
const input = document.createElement("input")
input.type="file"
input.onchange = () =>{
if(!input.files){
return
}
if(input.files.length >0){
const path = URL.createObjectURL(input.files[0]);
const fileType = input.files[0].type
if(fileType.startsWith("audio")){
const elem = document.getElementById("bgm_panel_audio") as HTMLAudioElement
elem.src = path
elem.onloadeddata = () => {
elem.play()
}
}else{
console.log("[App] unknwon file type", fileType)
}
}
}
input.click()
}
const ses = useMemo(()=>{
return RS_SE.map(s=>{
return <Button key={s} size="small" color="primary" className={classes.margin} onClick={() => {
playBGM(s)
}}>
{s.substr("resources/se/".length)}
</Button>
})
},[]) // eslint-disable-line
const controle = useMemo(()=>{
return(
<div className={classes.control}>
<div className={classes.volumeControl}>
<VolumeDown />
<div className={classes.margin} />
<Slider value={volume} onChange={handleVolumeChange} min={0} max={1} step={0.01} />
<div className={classes.margin} />
<VolumeUp />
</div>
<div>
{isPlaying===false?
<IconButton aria-label="play" onClick={togglePlay}>
<PlayArrow />
</IconButton>
:
<IconButton aria-label="stop" onClick={togglePlay}>
<Stop />
</IconButton>
}
</div>
<Button onClick={fileClicked}>File</Button>
</div>
)
},[volume, isPlaying]) // eslint-disable-line
return (
<div className={classes.root}>
<div className={classes.seList}>
{ses}
</div>
<audio id="bgm_panel_audio"/>
<div className={classes.margin} />
{controle}
</div>
);
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/MeetingRoom.tsx | <gh_stars>0
import React, { useEffect, useMemo, useState } from "react"
import clsx from 'clsx';
import { CssBaseline, AppBar, Drawer, Toolbar } from '@material-ui/core'
import { createMuiTheme, ThemeProvider} from '@material-ui/core/styles';
import { DrawerOpener } from "./components/appbars/DrawerOpener";
import { Title } from "./components/appbars/Title";
import { useAppState } from "../../providers/AppStateProvider";
import { bufferHeight, useStyles } from "./css";
import { DeviceEnabler } from "./components/appbars/DeviceEnabler";
import { DialogOpener } from "./components/appbars/DialogOpener";
import { FeatureEnabler } from "./components/appbars/FeatureEnabler";
import { ScreenType, SwitchButtons } from "./components/appbars/SwitchButtons";
import { SettingDialog } from "./components/dialog/SettingDialog";
import { LeaveMeetingDialog } from "./components/dialog/LeaveMeetingDialog";
import { CustomAccordion } from "./components/sidebars/CustomAccordion";
import { AttendeesTable } from "./components/sidebars/AttendeesTable";
import { ChatArea } from "./components/sidebars/ChatArea";
import { WhiteboardPanel } from "./components/sidebars/WhiteboardPanel";
import { CreditPanel } from "./components/sidebars/CreditPanel";
import { FullScreenView } from "./components/ScreenView/FullScreenView";
import { FeatureView } from "./components/ScreenView/FeatureView";
import { GridView } from "./components/ScreenView/GridView";
import { OnetimeCodePanel } from "./components/sidebars/OnetimeCodePanel";
import { ManagerControllerPanel } from "./components/sidebars/ManagerControllerPanel";
const toolbarHeight = 20
const drawerWidth = 240;
const theme = createMuiTheme({
mixins: {
toolbar: {
minHeight: toolbarHeight,
}
},
});
export const MeetingRoom = () => {
const classes = useStyles()
const [drawerOpen, setDrawerOpen] = useState(false)
const { screenHeight, screenWidth, meetingName,
audioInputDeviceSetting, videoInputDeviceSetting, audioOutputDeviceSetting, isShareContent,
startShareScreen, stopShareScreen,} = useAppState()
const [guiCounter, setGuiCounter] = useState(0)
const [settingDialogOpen, setSettingDialogOpen] = useState(false);
const [leaveDialogOpen, setLeaveDialogOpen] = useState(false);
const [screenType, setScreenType] = useState<ScreenType>("FeatureView");
const setAudioInputEnable = async() =>{
await audioInputDeviceSetting!.setAudioInputEnable(!audioInputDeviceSetting!.audioInputEnable)
setGuiCounter(guiCounter+1)
}
const setVideoInputEnable = async() =>{
const enable = !videoInputDeviceSetting!.videoInputEnable
await videoInputDeviceSetting!.setVideoInputEnable(enable)
if(enable){
videoInputDeviceSetting!.startLocalVideoTile()
}else{
videoInputDeviceSetting!.stopLocalVideoTile()
}
setGuiCounter(guiCounter+1)
}
const setAudioOutputEnable = async() =>{
await audioOutputDeviceSetting!.setAudioOutputEnable(!audioOutputDeviceSetting!.audioOutputEnable)
setGuiCounter(guiCounter+1)
}
const enableShareScreen = (val:boolean) =>{
if(val){
startShareScreen()
}else{
stopShareScreen()
}
}
const mainView = useMemo(()=>{
switch(screenType){
case "FullView":
return <FullScreenView height={screenHeight-toolbarHeight-bufferHeight} width={drawerOpen?screenWidth-drawerWidth:screenWidth} pictureInPicture={"None"} focusTarget={"SharedContent"}/>
case "FeatureView":
return <FeatureView height={screenHeight-toolbarHeight-bufferHeight} width={drawerOpen?screenWidth-drawerWidth:screenWidth} pictureInPicture={"None"} focusTarget={"SharedContent"}/>
case "GridView":
return <GridView height={screenHeight-toolbarHeight-bufferHeight} width={drawerOpen?screenWidth-drawerWidth:screenWidth} excludeSharedContent={false}/>
default:
return (<>Not found screen type:{screenType}</>)
}
},[screenType, screenHeight, screenWidth]) // eslint-disable-line
useEffect(()=>{
const audioElement = document.getElementById("for-speaker")! as HTMLAudioElement
audioElement.autoplay=false
audioOutputDeviceSetting!.setOutputAudioElement(audioElement)
},[]) // eslint-disable-line
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<div className={classes.root}>
<AppBar position="absolute" className={clsx(classes.appBar)}>
<Toolbar className={classes.toolbar}>
<div className={classes.toolbarInnnerBox}>
<DrawerOpener open={drawerOpen} setOpen={setDrawerOpen} />
</div>
<div className={classes.toolbarInnnerBox}>
<Title title={meetingName||""} />
</div>
<div className={classes.toolbarInnnerBox}>
<div className={classes.toolbarInnnerBox}>
<DeviceEnabler type="Mic" enable={audioInputDeviceSetting!.audioInputEnable} setEnable={setAudioInputEnable}/>
<DeviceEnabler type="Camera" enable={videoInputDeviceSetting!.videoInputEnable} setEnable={setVideoInputEnable}/>
<DeviceEnabler type="Speaker" enable={audioOutputDeviceSetting!.audioOutputEnable} setEnable={setAudioOutputEnable}/>
<DialogOpener type="Setting" onClick={()=>setSettingDialogOpen(true)}/>
<span className={clsx(classes.menuSpacer)}> </span>
<FeatureEnabler type="ShareScreen" enable={isShareContent} setEnable={(val:boolean)=>{enableShareScreen(val)}}/>
<span className={clsx(classes.menuSpacer)}> </span>
<span className={clsx(classes.menuSpacer)}> </span>
<SwitchButtons type="ScreenView" selected={screenType} onClick={(val)=>{setScreenType(val as ScreenType)}}/>
<span className={clsx(classes.menuSpacer)}> </span>
<span className={clsx(classes.menuSpacer)}> </span>
<DialogOpener type="LeaveMeeting" onClick={()=>setLeaveDialogOpen(true)}/>
</div>
<div className={classes.toolbarInnnerBox}>
</div>
</div>
</Toolbar>
</AppBar>
<SettingDialog open={settingDialogOpen} onClose={()=>setSettingDialogOpen(false)} />
<LeaveMeetingDialog open={leaveDialogOpen} onClose={()=>setLeaveDialogOpen(false)} />
<div style={{marginTop:toolbarHeight, position:"absolute", display:"flex"}}>
<Drawer
variant="permanent"
classes={{
paper: clsx(classes.drawerPaper, !drawerOpen && classes.drawerPaperClose),
}}
open={drawerOpen}
>
<CustomAccordion title="Member">
<AttendeesTable />
</CustomAccordion>
<CustomAccordion title="Chat">
<ChatArea/>
</CustomAccordion>
<CustomAccordion title="Whiteboard">
<WhiteboardPanel/>
</CustomAccordion>
{/* <CustomAccordion title="RecordMeeting (exp.)">
<RecorderPanel />
</CustomAccordion> */}
{/* <CustomAccordion title="BGM/SE">
<BGMPanel />
</CustomAccordion> */}
<CustomAccordion title="About">
<CreditPanel />
</CustomAccordion>
<CustomAccordion title="OnetimeCode">
<OnetimeCodePanel />
</CustomAccordion>
<CustomAccordion title="StartManagerPanel">
<ManagerControllerPanel />
</CustomAccordion>
</Drawer>
<main style={{height:`${screenHeight - toolbarHeight - bufferHeight}px`}}>
{mainView}
</main>
</div>
</div>
{/* ************************************** */}
{/* ***** Hidden Elements ***** */}
{/* ************************************** */}
<div>
<audio id="for-speaker" style={{display:"none"}}/>
</div>
</ThemeProvider>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/components/AudienceList.tsx | <filename>frontend3/src/pages/024_meetingRoomAmongUs/components/AudienceList.tsx<gh_stars>0
import { IconButton, Tooltip } from "@material-ui/core"
import React, { useMemo } from "react"
import { useAppState } from "../../../providers/AppStateProvider"
import VideocamIcon from '@material-ui/icons/Videocam';
import VideocamOffIcon from '@material-ui/icons/VideocamOff';
type VideoState = "ENABLED" | "PAUSED" | "NOT_SHARE"
export const AudienceList = () => {
const {attendees, videoTileStates, setPauseVideo} = useAppState()
const targetIds = Object.values(videoTileStates).reduce<string>((ids,cur)=>{return `${ids}_${cur.boundAttendeeId}`},"")
const targetNames = Object.values(attendees).reduce<string>((names,cur)=>{return `${names}_${cur.name}`},"")
const targetVideoStates:VideoState[] = Object.values(attendees).map(x=>{
if(!videoTileStates[x.attendeeId]){
return "NOT_SHARE"
}
if(x.isVideoPaused){
return "PAUSED"
}else{
return "ENABLED"
}
})
const targetVideoStatesString = targetVideoStates.reduce<string>((states, cur)=>{return `${states}_${cur}`}, "")
// const audienceList = useMemo(()=>{
// const l = Object.values(attendees).map((x)=>{
// return(
// <>
// <Tooltip title={`${x.attendeeId}`}>
// <div>
// {x.name}
// </div>
// </Tooltip>
// </>
// )
// })
// return(
// <div style={{display:"flex", flexDirection:"column"}}>
// {l}
// </div>
// )
// },[attendees])
const audienceList = useMemo(()=>{
const l = Object.values(attendees).map((x, index)=>{
let videoStateComp
switch(targetVideoStates[index]){
case "ENABLED":
videoStateComp = (
<Tooltip title={`click to pause`}>
<IconButton style={{width: "20px", height:"20px"}} onClick={ ()=>{setPauseVideo(x.attendeeId, true)} } >
<VideocamIcon></VideocamIcon>
</IconButton>
</Tooltip>
)
break
case "PAUSED":
videoStateComp = (
<Tooltip title={`click to play`}>
<IconButton style={{width: "20px", height:"20px"}} onClick={ ()=>{setPauseVideo(x.attendeeId, false)} } >
<VideocamOffIcon ></VideocamOffIcon>
</IconButton>
</Tooltip>
)
break
case "NOT_SHARE":
videoStateComp = <></>
break
}
return(
<>
<div style={{display:"flex", flexDirection:"row"}}>
<Tooltip title={`${x.attendeeId}`}>
<div>
{x.name}
</div>
</Tooltip>
<div>
{videoStateComp}
</div>
</div>
</>
)
})
return(
<div style={{display:"flex", flexDirection:"column"}}>
{l}
</div>
)
},[targetIds, targetNames, targetVideoStatesString])
return(
<>
<div style={{color:"burlywood"}}>
Spacemen
</div>
<div style={{marginLeft:"15pt"}}>
{audienceList}
</div>
</>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/utils/index.ts |
export type DeviceInfo={
deviceId:string,
groupId:string,
kind:string,
label:string,
}
export type DeviceInfoList = {
audioinput: DeviceInfo[] | null,
videoinput: DeviceInfo[] | null,
audiooutput: DeviceInfo[] | null,
}
export const getDeviceLists = async ():Promise<DeviceInfoList> => {
const list = await navigator.mediaDevices.enumerateDevices()
const audioInputDevices:DeviceInfo[] = list.filter((x: InputDeviceInfo | MediaDeviceInfo) => {
return x.kind === "audioinput"
}).map(x=>{
return {
deviceId:x.deviceId,
groupId:x.groupId,
kind:x.kind,
label:x.label
}
})
const videoInputDevices:DeviceInfo[] = list.filter((x: InputDeviceInfo | MediaDeviceInfo) => {
return x.kind === "videoinput"
}).map(x=>{
return {
deviceId:x.deviceId,
groupId:x.groupId,
kind:x.kind,
label:x.label
}
})
const audioOutputDevices:DeviceInfo[] = list.filter((x: InputDeviceInfo | MediaDeviceInfo) => {
return x.kind === "audiooutput"
}).map(x=>{
return {
deviceId:x.deviceId,
groupId:x.groupId,
kind:x.kind,
label:x.label
}
})
return {
audioinput: audioInputDevices,
videoinput: videoInputDevices,
audiooutput: audioOutputDevices,
}
}
export function showDiff<T>(before:T, after:T){
const pre_map:{[key:string]:any}={}
Object.entries(before).forEach(p=>{
const key = p[0]
const value = p[1]
pre_map[key]=value
})
const cur_map:{[key:string]:any}={}
Object.entries(after).forEach(p=>{
const key = p[0]
const value = p[1]
cur_map[key] =value
})
const diffs:{[key:string]:any}={}
Object.keys(cur_map).forEach(k=>{
if(pre_map[k] !== cur_map[k]){
if(!diffs['diffs']){
diffs['diffs'] =[]
}
diffs['diffs'][k]=[pre_map[k], cur_map[k]]
}else{
if(!diffs['same']){
diffs['same'] =[]
}
diffs['same'][k]=[pre_map[k], cur_map[k]]
}
})
// console.log("DIFFS!GENERICS!!",diffs)
}
export const getDateString = (unixtime?:number):string => {
let dt
if(unixtime){
dt = new Date(unixtime)
}else{
dt = new Date()
}
var y = dt.getFullYear();
var m = ("00" + (dt.getMonth()+1)).slice(-2);
var d = ("00" + dt.getDate()).slice(-2);
var h = ("00" + dt.getHours()).slice(-2);
var min = ("00" + dt.getMinutes()).slice(-2);
var sec = ("00" + dt.getSeconds()).slice(-2);
var result = y + "_" + m + "_" + d + "_" + h + "_" + min + "_" + sec;
return result
} |
utilitywarehouse/customer-tracking-sdk | js/packages/for-server/src/index.ts | <filename>js/packages/for-server/src/index.ts<gh_stars>1-10
export {
Tracker
} from "@utilitywarehouse/customer-tracking-core"
export * from "@utilitywarehouse/customer-tracking-types"
export {MixpanelBackend} from "./mixpanel_backend" |
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/index.ts | export * from "./tracker";
export * from "./ui_tracker";
export * from "./backend";
export * from "./ui_backend";
|
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/ui_backend.ts | <gh_stars>1-10
import {Backend} from "./backend";
import {Actor} from "@utilitywarehouse/customer-tracking-types";
export interface UIBackend extends Backend {
enable(): Promise<void>
disable(): Promise<void>
identify(actor: Actor): Promise<void>
reset(): Promise<void>
} |
utilitywarehouse/customer-tracking-sdk | js/packages/for-server/src/mixpanel_backend.ts | <filename>js/packages/for-server/src/mixpanel_backend.ts
import {Backend} from "@utilitywarehouse/customer-tracking-core";
import * as mixpanel from "mixpanel";
export class MixpanelBackend implements Backend {
private mixpanel: mixpanel.Mixpanel;
constructor(apiKey: string, config?: mixpanel.InitConfig) {
this.mixpanel = mixpanel.init(apiKey, {
host: "api-eu.mixpanel.com", // EU by default
...config
});
}
alias(from: string, to: string): Promise<void> {
return new Promise((resolve, reject) => {
this.mixpanel.alias(from, to, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
})
})
}
track(eventName: string, distinctId?: string, eventAttributes?: { [p: string]: string }): Promise<void> {
const filteredAttributes: { [p: string]: string } = {};
for (const key in eventAttributes) {
if (eventAttributes[key]) {
filteredAttributes[key] = eventAttributes[key];
}
}
if (distinctId) {
filteredAttributes['distinct_id'] = distinctId;
}
return new Promise((resolve, reject) => {
this.mixpanel.track(eventName, filteredAttributes, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
})
})
}
} |
utilitywarehouse/customer-tracking-sdk | js/packages/for-native/src/mixpanel_backend.ts | <filename>js/packages/for-native/src/mixpanel_backend.ts
import Mixpanel from "react-native-mixpanel"
import { UIBackend } from "@utilitywarehouse/customer-tracking-core"
import { Actor } from "@utilitywarehouse/customer-tracking-types"
export class MixpanelBackend implements UIBackend {
constructor(token: string, options: {[k: string]: string | number | boolean} = {}) {
const {
optOutTrackingByDefault,
trackCrashes,
automaticPushTracking,
launchOptions,
} = options
Mixpanel.sharedInstanceWithToken(
token,
optOutTrackingByDefault == undefined ? undefined : !!optOutTrackingByDefault,
trackCrashes == undefined ? undefined : !!trackCrashes,
automaticPushTracking == undefined ? undefined : !!automaticPushTracking,
launchOptions
)
}
alias(from: string, to: string): Promise<void> {
return Promise.resolve(Mixpanel.createAlias(from, to))
}
track(eventName: string, distinctId?: string, eventAttributes?: { [p: string]: string }): Promise<void> {
// ignoring distinctId, it's here because of the backend interface
const filteredAttributes: { [p: string]: string } = {};
for (const key in eventAttributes) {
if (eventAttributes[key]) {
filteredAttributes[key] = eventAttributes[key];
}
}
return Promise.resolve(Mixpanel.trackWithProperties(eventName, filteredAttributes))
}
disable(): Promise<void> {
return Promise.resolve(Mixpanel.optOutTracking())
}
enable(): Promise<void> {
return Promise.resolve(Mixpanel.optInTracking())
}
identify(actor: Actor): Promise<void> {
return Promise.resolve(Mixpanel.identify(actor.id))
}
reset(): Promise<void> {
return Promise.resolve(Mixpanel.reset())
}
} |
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/backend.ts | <reponame>utilitywarehouse/customer-tracking-sdk
export interface Backend {
/**
* track sends a tracking event to chosen backend
*
* @param eventName - name of the event
* @param actorId - the unique identifier of the actor
* @param eventAttributes - map of atrributes to attach
*/
track(eventName: string, actorId?: string, eventAttributes?: {[k: string]: string}): Promise<void>
alias(from: string, to: string): Promise<void>
} |
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/ui_tracker.ts | import {EventAttributes, Tracker as BaseTracker} from "./tracker";
import {UIBackend} from "./ui_backend";
import {
Actor, Application, Intent, Stage, Subject, Interaction, InteractionChannel,
} from "@utilitywarehouse/customer-tracking-types";
interface StageArguments {
subject: Subject;
intent: Intent;
stage: Stage;
attributes?: EventAttributes;
}
interface InteractionArguments {
subject: Subject;
intent: Intent;
interaction: Interaction;
channel: InteractionChannel;
attributes?: EventAttributes;
}
interface ClickArguments {
target: string;
attributes?: EventAttributes;
}
interface VisitArguments {
location: string;
attributes?: EventAttributes;
}
export class UITracker {
private actor!: Actor;
private baseTracker: BaseTracker;
constructor(private readonly backend: UIBackend, private readonly application: Application) {
this.baseTracker = new BaseTracker(backend);
}
onError(fn: (err: Error) => void): void {
this.baseTracker.onError(fn);
}
async identify(actor: Actor): Promise<void> {
this.actor = actor;
return this.backend.identify(actor);
}
async reset(): Promise<void> {
this.actor = {id: "", attributes: {}};
return this.backend.reset()
}
async disable(): Promise<void> {
return this.backend.disable()
}
async enable(): Promise<void> {
return this.backend.enable()
}
async trackStage(event: StageArguments): Promise<void> {
return this.baseTracker.trackStage({
actor: this.actor,
application: this.application,
...event
})
}
async trackInteraction(event: InteractionArguments): Promise<void> {
return this.baseTracker.trackInteraction({
actor: this.actor,
application: this.application,
...event
})
}
async trackClick(event: ClickArguments): Promise<void> {
return this.baseTracker.trackClick({
actor: this.actor,
application: this.application,
...event
})
}
async trackVisit(event: VisitArguments): Promise<void> {
return this.baseTracker.trackVisit({
actor: this.actor,
application: this.application,
...event
})
}
async alias(from: string, to: string): Promise<void> {
return this.baseTracker.alias(from, to)
}
} |
utilitywarehouse/customer-tracking-sdk | examples/js/for-server/index.ts | <gh_stars>1-10
import {
Tracker, MixpanelBackend, Subject, Stage, Intent, Interaction, InteractionChannel
} from "@utilitywarehouse/customer-tracking-for-server"
const tracker = new Tracker(
new MixpanelBackend("apiToken", {debug: true}),
)
tracker.onError((err: Error) => {
console.error("onError -> ", err.message)
})
const getAttributes = (): Promise<{ [k: string]: string }> => {
return new Promise(r => r({timeOfLastRead: "2020-06-01"}));
}
const failAttributes = (): Promise<{ [k: string]: string }> => {
return new Promise((_,r) => r(new Error("failed to obtain event context")));
}
tracker.trackStage({
actor: {id: "3002098", attributes: {account_number: "3002098"}},
// application, where appropriate should indicate the subject the user token was issued to
// ie. a graphql tracking should use the react app ID in this place because the react app is
// what triggered the action, this helps understanding where the action originated if many
// different frontends are using the same backend
application: {id: "ds-meter-reads"},
subject: Subject.SUBJECT_METER_READING,
intent: Intent.INTENT_METER_READING_SUBMIT,
stage: Stage.STAGE_COMPLETED,
attributes: getAttributes() // note how attributes can be a promise
})
tracker.trackInteraction({
actor: {id: "3002098", attributes: {account_number: "3002098"}},
application: {id: "ds-meter-reads"},
subject: Subject.SUBJECT_METER_READING,
intent: Intent.INTENT_METER_READING_SUBMIT,
interaction: Interaction.INTERACTION_CLICKED,
channel: InteractionChannel.INTERACTION_CHANNEL_EMAIL,
// note how the failure to resolve the promise will result in an onError event
// trigger rather than the tracker.trackInteraction promise rejection
attributes: failAttributes()
}) |
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/tracker.test.ts | import {Tracker} from "./tracker";
import {Backend} from "./backend";
import {
Actor, Application, Intent, Interaction, InteractionChannel, Stage, Subject,
} from "@utilitywarehouse/customer-tracking-types";
function mockBackend(): Backend {
return {
track: jest.fn(),
alias: jest.fn(),
}
}
test("stage event tracking", async () => {
const backend = mockBackend();
const tracker = new Tracker(backend);
const eventName = "submitted.meter-reading-submit";
const actor: Actor = {attributes: {"account-number": "acc-123", "account-id": "acc-id"}, id: "acc-id"};
const application: Application = {id: "acc-123"};
const subject: Subject = Subject.SUBJECT_METER_READING;
const intent: Intent = Intent.INTENT_METER_READING_SUBMIT;
const stage: Stage = Stage.STAGE_SUBMITTED;
const attributes = {"a-a": "b", c: 'd'};
const expectedAttributes = {"a_a": "b", c: 'd'};
await tracker.trackStage({
actor,
application,
subject,
intent,
stage,
attributes: new Promise(r => r(attributes)),
}
)
expect(backend.track).toBeCalledWith(eventName, actor.id, {
"account_number": actor.attributes["account-number"],
"account_id": actor.id,
client_id: application.id,
subject: "meter-reading",
intent: "meter-reading-submit",
stage: "submitted",
...expectedAttributes
});
})
test("interaction event tracking", async () => {
const backend = mockBackend();
const tracker = new Tracker(backend);
const eventName = "email.clicked";
const actor: Actor = {attributes: {"account-number": "acc-123", "account-id": "acc-id"}, id: "acc-id"};
const application: Application = {id: "acc-123"};
const subject: Subject = Subject.SUBJECT_METER_READING;
const intent: Intent = Intent.INTENT_METER_READING_SUBMIT;
const interaction: Interaction = Interaction.INTERACTION_CLICKED;
const channel: InteractionChannel = InteractionChannel.INTERACTION_CHANNEL_EMAIL;
const attributes = {"a-a": "b", c: 'd'};
const expectedAttributes = {"a_a": "b", c: 'd'};
await tracker.trackInteraction({
actor,
application,
subject,
intent,
interaction,
channel,
attributes: new Promise(r => r(attributes)),
}
)
expect(backend.track).toBeCalledWith(eventName, actor.id, {
"account_number": actor.attributes["account-number"],
"account_id": actor.id,
client_id: application.id,
subject: "meter-reading",
intent: "meter-reading-submit",
interaction: "clicked",
interaction_channel: "email",
...expectedAttributes
});
})
test("visit event tracking", async () => {
const backend = mockBackend();
const tracker = new Tracker(backend);
const eventName = "visit";
const actor: Actor = {attributes: {"account-number": "acc-123", "account-id": "acc-id"}, id: "acc-id"};
const application: Application = {id: "acc-123"};
const location = "location";
const attributes = {"a-a": "b", c: 'd'};
const expectedAttributes = {"a_a": "b", c: 'd'};
await tracker.trackVisit({
actor,
application,
location,
attributes: new Promise(r => r(attributes)),
}
)
expect(backend.track).toBeCalledWith(eventName, actor.id, {
"account_number": actor.attributes["account-number"],
"account_id": actor.id,
client_id: application.id,
location, ...expectedAttributes
});
})
test("click event tracking", async () => {
const backend = mockBackend();
const tracker = new Tracker(backend);
const eventName = "click";
const actor: Actor = {attributes: {"account-number": "acc-123", "account-id": "acc-id"}, id: "acc-id"};
const application: Application = {id: "acc-123"};
const target = "target";
const attributes = {"a-a": "b", c: 'd'};
const expectedAttributes = {"a_a": "b", c: 'd'};
await tracker.trackClick({
actor,
application,
target,
attributes: new Promise(r => r(attributes)),
}
)
expect(backend.track).toBeCalledWith(eventName, actor.id, {
"account_number": actor.attributes["account-number"],
"account_id": actor.id,
client_id: application.id,
target,
...expectedAttributes
});
})
test("click event tracking", async () => {
const backend = mockBackend();
const tracker = new Tracker(backend);
const eventName = "click";
const actor: Actor = {attributes: {"account-number": "acc-123", "account-id": "acc-id"}, id: "acc-id"};
const application: Application = {id: "acc-123"};
const target = "target";
const attributes = {"a-a": "b", c: 'd'};
const expectedAttributes = {"a_a": "b", c: 'd'};
await tracker.trackClick({
actor,
application,
target,
attributes: new Promise(r => r(attributes)),
}
)
expect(backend.track).toBeCalledWith(eventName, actor.id, {
"account_number": actor.attributes["account-number"],
"account_id": actor.id,
client_id: application.id,
target,
...expectedAttributes
});
}) |
utilitywarehouse/customer-tracking-sdk | js/packages/types/src/index.ts | /* eslint-disable */
export interface Actor {
/**
* used as the main identifier in tracking backend (ie
* distinct_id in mixpanel)
*/
id: string;
/**
* map to attach actor attributes to each event, can be used for
* account_number etc.
*/
attributes: { [key: string]: string };
}
export interface Actor_AttributesEntry {
key: string;
value: string;
}
export interface Application {
id: string;
/**
* map to attach application attributes to each event, can be used for
* build version etc.
*/
attributes: { [key: string]: string };
}
export interface Application_AttributesEntry {
key: string;
value: string;
}
export interface StageEvent {
actor: Actor | undefined;
application: Application | undefined;
subject: Subject;
intent: Intent;
stage: Stage;
attributes: { [key: string]: string };
}
export interface StageEvent_AttributesEntry {
key: string;
value: string;
}
export interface InteractionEvent {
actor: Actor | undefined;
application: Application | undefined;
subject: Subject;
intent: Intent;
interaction: Interaction;
channel: InteractionChannel;
attributes: { [key: string]: string };
}
export interface InteractionEvent_AttributesEntry {
key: string;
value: string;
}
export interface VisitEvent {
actor: Actor | undefined;
application: Application | undefined;
location: string;
attributes: { [key: string]: string };
}
export interface VisitEvent_AttributesEntry {
key: string;
value: string;
}
export interface ClickEvent {
actor: Actor | undefined;
application: Application | undefined;
target: string;
attributes: { [key: string]: string };
}
export interface ClickEvent_AttributesEntry {
key: string;
value: string;
}
const baseActor: object = {
id: "",
};
const baseActor_AttributesEntry: object = {
key: "",
value: "",
};
const baseApplication: object = {
id: "",
};
const baseApplication_AttributesEntry: object = {
key: "",
value: "",
};
const baseStageEvent: object = {
subject: 0,
intent: 0,
stage: 0,
};
const baseStageEvent_AttributesEntry: object = {
key: "",
value: "",
};
const baseInteractionEvent: object = {
subject: 0,
intent: 0,
interaction: 0,
channel: 0,
};
const baseInteractionEvent_AttributesEntry: object = {
key: "",
value: "",
};
const baseVisitEvent: object = {
location: "",
};
const baseVisitEvent_AttributesEntry: object = {
key: "",
value: "",
};
const baseClickEvent: object = {
target: "",
};
const baseClickEvent_AttributesEntry: object = {
key: "",
value: "",
};
export const Subject = {
SUBJECT_NONE: 0 as const,
SUBJECT_METER_READING: 1 as const,
SUBJECT_CUSTOMER_REFERRAL: 2 as const,
SUBJECT_BILL: 3 as const,
SUBJECT_ENERGY_PREFERENCES: 4 as const,
SUBJECT_HELP: 5 as const,
SUBJECT_CUSTOMER_AUTH: 6 as const,
SUBJECT_MOBILE_SIM: 7 as const,
SUBJECT_SMART_METER_INSTALLATION: 8 as const,
SUBJECT_CUSTOMER_OVERDUE_BALANCE: 9 as const,
SUBJECT_INSURANCE_QUOTE: 10 as const,
UNRECOGNIZED: -1 as const,
fromJSON(object: any): Subject {
switch (object) {
case 0:
case "SUBJECT_NONE":
return Subject.SUBJECT_NONE;
case 1:
case "SUBJECT_METER_READING":
return Subject.SUBJECT_METER_READING;
case 2:
case "SUBJECT_CUSTOMER_REFERRAL":
return Subject.SUBJECT_CUSTOMER_REFERRAL;
case 3:
case "SUBJECT_BILL":
return Subject.SUBJECT_BILL;
case 4:
case "SUBJECT_ENERGY_PREFERENCES":
return Subject.SUBJECT_ENERGY_PREFERENCES;
case 5:
case "SUBJECT_HELP":
return Subject.SUBJECT_HELP;
case 6:
case "SUBJECT_CUSTOMER_AUTH":
return Subject.SUBJECT_CUSTOMER_AUTH;
case 7:
case "SUBJECT_MOBILE_SIM":
return Subject.SUBJECT_MOBILE_SIM;
case 8:
case "SUBJECT_SMART_METER_INSTALLATION":
return Subject.SUBJECT_SMART_METER_INSTALLATION;
case 9:
case "SUBJECT_CUSTOMER_OVERDUE_BALANCE":
return Subject.SUBJECT_CUSTOMER_OVERDUE_BALANCE;
case 10:
case "SUBJECT_INSURANCE_QUOTE":
return Subject.SUBJECT_INSURANCE_QUOTE;
case -1:
case "UNRECOGNIZED":
default:
return Subject.UNRECOGNIZED;
}
},
toJSON(object: Subject): string {
switch (object) {
case Subject.SUBJECT_NONE:
return "SUBJECT_NONE";
case Subject.SUBJECT_METER_READING:
return "SUBJECT_METER_READING";
case Subject.SUBJECT_CUSTOMER_REFERRAL:
return "SUBJECT_CUSTOMER_REFERRAL";
case Subject.SUBJECT_BILL:
return "SUBJECT_BILL";
case Subject.SUBJECT_ENERGY_PREFERENCES:
return "SUBJECT_ENERGY_PREFERENCES";
case Subject.SUBJECT_HELP:
return "SUBJECT_HELP";
case Subject.SUBJECT_CUSTOMER_AUTH:
return "SUBJECT_CUSTOMER_AUTH";
case Subject.SUBJECT_MOBILE_SIM:
return "SUBJECT_MOBILE_SIM";
case Subject.SUBJECT_SMART_METER_INSTALLATION:
return "SUBJECT_SMART_METER_INSTALLATION";
case Subject.SUBJECT_CUSTOMER_OVERDUE_BALANCE:
return "SUBJECT_CUSTOMER_OVERDUE_BALANCE";
case Subject.SUBJECT_INSURANCE_QUOTE:
return "SUBJECT_INSURANCE_QUOTE";
default:
return "UNKNOWN";
}
},
}
export type Subject = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -1;
export const Intent = {
INTENT_NONE: 0 as const,
INTENT_METER_READING_SUBMIT: 1 as const,
INTENT_LEAD_CAPTURE: 2 as const,
INTENT_PAYMENT: 3 as const,
INTENT_FRIEND_REFERRAL_LINK_SHARE: 4 as const,
INTENT_PREFERENCES_UPDATE: 5 as const,
INTENT_CONTACT_SUPPORT: 6 as const,
INTENT_LEAVE_FEEDBACK: 7 as const,
INTENT_LOGIN: 8 as const,
INTENT_MOBILE_SIM_UPGRADE: 9 as const,
INTENT_APPOINTMENT_BOOKING: 10 as const,
INTENT_FIND_HELP: 11 as const,
INTENT_APPOINTMENT_RESCHEDULE: 12 as const,
INTENT_CREATE_INSURANCE_QUOTE: 13 as const,
UNRECOGNIZED: -1 as const,
fromJSON(object: any): Intent {
switch (object) {
case 0:
case "INTENT_NONE":
return Intent.INTENT_NONE;
case 1:
case "INTENT_METER_READING_SUBMIT":
return Intent.INTENT_METER_READING_SUBMIT;
case 2:
case "INTENT_LEAD_CAPTURE":
return Intent.INTENT_LEAD_CAPTURE;
case 3:
case "INTENT_PAYMENT":
return Intent.INTENT_PAYMENT;
case 4:
case "INTENT_FRIEND_REFERRAL_LINK_SHARE":
return Intent.INTENT_FRIEND_REFERRAL_LINK_SHARE;
case 5:
case "INTENT_PREFERENCES_UPDATE":
return Intent.INTENT_PREFERENCES_UPDATE;
case 6:
case "INTENT_CONTACT_SUPPORT":
return Intent.INTENT_CONTACT_SUPPORT;
case 7:
case "INTENT_LEAVE_FEEDBACK":
return Intent.INTENT_LEAVE_FEEDBACK;
case 8:
case "INTENT_LOGIN":
return Intent.INTENT_LOGIN;
case 9:
case "INTENT_MOBILE_SIM_UPGRADE":
return Intent.INTENT_MOBILE_SIM_UPGRADE;
case 10:
case "INTENT_APPOINTMENT_BOOKING":
return Intent.INTENT_APPOINTMENT_BOOKING;
case 11:
case "INTENT_FIND_HELP":
return Intent.INTENT_FIND_HELP;
case 12:
case "INTENT_APPOINTMENT_RESCHEDULE":
return Intent.INTENT_APPOINTMENT_RESCHEDULE;
case 13:
case "INTENT_CREATE_INSURANCE_QUOTE":
return Intent.INTENT_CREATE_INSURANCE_QUOTE;
case -1:
case "UNRECOGNIZED":
default:
return Intent.UNRECOGNIZED;
}
},
toJSON(object: Intent): string {
switch (object) {
case Intent.INTENT_NONE:
return "INTENT_NONE";
case Intent.INTENT_METER_READING_SUBMIT:
return "INTENT_METER_READING_SUBMIT";
case Intent.INTENT_LEAD_CAPTURE:
return "INTENT_LEAD_CAPTURE";
case Intent.INTENT_PAYMENT:
return "INTENT_PAYMENT";
case Intent.INTENT_FRIEND_REFERRAL_LINK_SHARE:
return "INTENT_FRIEND_REFERRAL_LINK_SHARE";
case Intent.INTENT_PREFERENCES_UPDATE:
return "INTENT_PREFERENCES_UPDATE";
case Intent.INTENT_CONTACT_SUPPORT:
return "INTENT_CONTACT_SUPPORT";
case Intent.INTENT_LEAVE_FEEDBACK:
return "INTENT_LEAVE_FEEDBACK";
case Intent.INTENT_LOGIN:
return "INTENT_LOGIN";
case Intent.INTENT_MOBILE_SIM_UPGRADE:
return "INTENT_MOBILE_SIM_UPGRADE";
case Intent.INTENT_APPOINTMENT_BOOKING:
return "INTENT_APPOINTMENT_BOOKING";
case Intent.INTENT_FIND_HELP:
return "INTENT_FIND_HELP";
case Intent.INTENT_APPOINTMENT_RESCHEDULE:
return "INTENT_APPOINTMENT_RESCHEDULE";
case Intent.INTENT_CREATE_INSURANCE_QUOTE:
return "INTENT_CREATE_INSURANCE_QUOTE";
default:
return "UNKNOWN";
}
},
}
export type Intent = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -1;
export const Stage = {
STAGE_NONE: 0 as const,
STAGE_SUBMITTED: 1 as const,
STAGE_RECEIVED_REQUEST_FOR_AMEND: 2 as const,
STAGE_COMPLETED: 3 as const,
STAGE_REJECTED: 4 as const,
STAGE_ENTERED: 5 as const,
STAGE_STARTED: 6 as const,
STAGE_FAILED: 7 as const,
UNRECOGNIZED: -1 as const,
fromJSON(object: any): Stage {
switch (object) {
case 0:
case "STAGE_NONE":
return Stage.STAGE_NONE;
case 1:
case "STAGE_SUBMITTED":
return Stage.STAGE_SUBMITTED;
case 2:
case "STAGE_RECEIVED_REQUEST_FOR_AMEND":
return Stage.STAGE_RECEIVED_REQUEST_FOR_AMEND;
case 3:
case "STAGE_COMPLETED":
return Stage.STAGE_COMPLETED;
case 4:
case "STAGE_REJECTED":
return Stage.STAGE_REJECTED;
case 5:
case "STAGE_ENTERED":
return Stage.STAGE_ENTERED;
case 6:
case "STAGE_STARTED":
return Stage.STAGE_STARTED;
case 7:
case "STAGE_FAILED":
return Stage.STAGE_FAILED;
case -1:
case "UNRECOGNIZED":
default:
return Stage.UNRECOGNIZED;
}
},
toJSON(object: Stage): string {
switch (object) {
case Stage.STAGE_NONE:
return "STAGE_NONE";
case Stage.STAGE_SUBMITTED:
return "STAGE_SUBMITTED";
case Stage.STAGE_RECEIVED_REQUEST_FOR_AMEND:
return "STAGE_RECEIVED_REQUEST_FOR_AMEND";
case Stage.STAGE_COMPLETED:
return "STAGE_COMPLETED";
case Stage.STAGE_REJECTED:
return "STAGE_REJECTED";
case Stage.STAGE_ENTERED:
return "STAGE_ENTERED";
case Stage.STAGE_STARTED:
return "STAGE_STARTED";
case Stage.STAGE_FAILED:
return "STAGE_FAILED";
default:
return "UNKNOWN";
}
},
}
export type Stage = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -1;
export const Interaction = {
INTERACTION_NONE: 0 as const,
INTERACTION_CLICKED: 1 as const,
INTERACTION_VIEWED: 2 as const,
INTERACTION_SEARCHED: 3 as const,
UNRECOGNIZED: -1 as const,
fromJSON(object: any): Interaction {
switch (object) {
case 0:
case "INTERACTION_NONE":
return Interaction.INTERACTION_NONE;
case 1:
case "INTERACTION_CLICKED":
return Interaction.INTERACTION_CLICKED;
case 2:
case "INTERACTION_VIEWED":
return Interaction.INTERACTION_VIEWED;
case 3:
case "INTERACTION_SEARCHED":
return Interaction.INTERACTION_SEARCHED;
case -1:
case "UNRECOGNIZED":
default:
return Interaction.UNRECOGNIZED;
}
},
toJSON(object: Interaction): string {
switch (object) {
case Interaction.INTERACTION_NONE:
return "INTERACTION_NONE";
case Interaction.INTERACTION_CLICKED:
return "INTERACTION_CLICKED";
case Interaction.INTERACTION_VIEWED:
return "INTERACTION_VIEWED";
case Interaction.INTERACTION_SEARCHED:
return "INTERACTION_SEARCHED";
default:
return "UNKNOWN";
}
},
}
export type Interaction = 0 | 1 | 2 | 3 | -1;
export const InteractionChannel = {
INTERACTION_CHANNEL_NONE: 0 as const,
INTERACTION_CHANNEL_EMAIL: 1 as const,
INTERACTION_CHANNEL_WILLIAM: 2 as const,
INTERACTION_CHANNEL_RESIDENTIAL_MOBILE_APP: 3 as const,
INTERACTION_CHANNEL_RESIDENTIAL_WEB_APP: 5 as const,
INTERACTION_CHANNEL_HELP_CENTRE_WEB: 6 as const,
UNRECOGNIZED: -1 as const,
fromJSON(object: any): InteractionChannel {
switch (object) {
case 0:
case "INTERACTION_CHANNEL_NONE":
return InteractionChannel.INTERACTION_CHANNEL_NONE;
case 1:
case "INTERACTION_CHANNEL_EMAIL":
return InteractionChannel.INTERACTION_CHANNEL_EMAIL;
case 2:
case "INTERACTION_CHANNEL_WILLIAM":
return InteractionChannel.INTERACTION_CHANNEL_WILLIAM;
case 3:
case "INTERACTION_CHANNEL_RESIDENTIAL_MOBILE_APP":
return InteractionChannel.INTERACTION_CHANNEL_RESIDENTIAL_MOBILE_APP;
case 5:
case "INTERACTION_CHANNEL_RESIDENTIAL_WEB_APP":
return InteractionChannel.INTERACTION_CHANNEL_RESIDENTIAL_WEB_APP;
case 6:
case "INTERACTION_CHANNEL_HELP_CENTRE_WEB":
return InteractionChannel.INTERACTION_CHANNEL_HELP_CENTRE_WEB;
case -1:
case "UNRECOGNIZED":
default:
return InteractionChannel.UNRECOGNIZED;
}
},
toJSON(object: InteractionChannel): string {
switch (object) {
case InteractionChannel.INTERACTION_CHANNEL_NONE:
return "INTERACTION_CHANNEL_NONE";
case InteractionChannel.INTERACTION_CHANNEL_EMAIL:
return "INTERACTION_CHANNEL_EMAIL";
case InteractionChannel.INTERACTION_CHANNEL_WILLIAM:
return "INTERACTION_CHANNEL_WILLIAM";
case InteractionChannel.INTERACTION_CHANNEL_RESIDENTIAL_MOBILE_APP:
return "INTERACTION_CHANNEL_RESIDENTIAL_MOBILE_APP";
case InteractionChannel.INTERACTION_CHANNEL_RESIDENTIAL_WEB_APP:
return "INTERACTION_CHANNEL_RESIDENTIAL_WEB_APP";
case InteractionChannel.INTERACTION_CHANNEL_HELP_CENTRE_WEB:
return "INTERACTION_CHANNEL_HELP_CENTRE_WEB";
default:
return "UNKNOWN";
}
},
}
export type InteractionChannel = 0 | 1 | 2 | 3 | 5 | 6 | -1;
export const Actor = {
fromJSON(object: any): Actor {
const message = { ...baseActor } as Actor;
message.attributes = {};
if (object.id !== undefined && object.id !== null) {
message.id = String(object.id);
} else {
message.id = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<Actor>): Actor {
const message = { ...baseActor } as Actor;
message.attributes = {};
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
} else {
message.id = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: Actor): unknown {
const obj: any = {};
obj.id = message.id || "";
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const Actor_AttributesEntry = {
fromJSON(object: any): Actor_AttributesEntry {
const message = { ...baseActor_AttributesEntry } as Actor_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<Actor_AttributesEntry>): Actor_AttributesEntry {
const message = { ...baseActor_AttributesEntry } as Actor_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: Actor_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
export const Application = {
fromJSON(object: any): Application {
const message = { ...baseApplication } as Application;
message.attributes = {};
if (object.id !== undefined && object.id !== null) {
message.id = String(object.id);
} else {
message.id = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<Application>): Application {
const message = { ...baseApplication } as Application;
message.attributes = {};
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
} else {
message.id = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: Application): unknown {
const obj: any = {};
obj.id = message.id || "";
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const Application_AttributesEntry = {
fromJSON(object: any): Application_AttributesEntry {
const message = { ...baseApplication_AttributesEntry } as Application_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<Application_AttributesEntry>): Application_AttributesEntry {
const message = { ...baseApplication_AttributesEntry } as Application_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: Application_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
export const StageEvent = {
fromJSON(object: any): StageEvent {
const message = { ...baseStageEvent } as StageEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromJSON(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromJSON(object.application);
} else {
message.application = undefined;
}
if (object.subject !== undefined && object.subject !== null) {
message.subject = Subject.fromJSON(object.subject);
} else {
message.subject = 0;
}
if (object.intent !== undefined && object.intent !== null) {
message.intent = Intent.fromJSON(object.intent);
} else {
message.intent = 0;
}
if (object.stage !== undefined && object.stage !== null) {
message.stage = Stage.fromJSON(object.stage);
} else {
message.stage = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<StageEvent>): StageEvent {
const message = { ...baseStageEvent } as StageEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromPartial(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromPartial(object.application);
} else {
message.application = undefined;
}
if (object.subject !== undefined && object.subject !== null) {
message.subject = object.subject;
} else {
message.subject = 0;
}
if (object.intent !== undefined && object.intent !== null) {
message.intent = object.intent;
} else {
message.intent = 0;
}
if (object.stage !== undefined && object.stage !== null) {
message.stage = object.stage;
} else {
message.stage = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: StageEvent): unknown {
const obj: any = {};
obj.actor = message.actor ? Actor.toJSON(message.actor) : undefined;
obj.application = message.application ? Application.toJSON(message.application) : undefined;
obj.subject = Subject.toJSON(message.subject);
obj.intent = Intent.toJSON(message.intent);
obj.stage = Stage.toJSON(message.stage);
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const StageEvent_AttributesEntry = {
fromJSON(object: any): StageEvent_AttributesEntry {
const message = { ...baseStageEvent_AttributesEntry } as StageEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<StageEvent_AttributesEntry>): StageEvent_AttributesEntry {
const message = { ...baseStageEvent_AttributesEntry } as StageEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: StageEvent_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
export const InteractionEvent = {
fromJSON(object: any): InteractionEvent {
const message = { ...baseInteractionEvent } as InteractionEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromJSON(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromJSON(object.application);
} else {
message.application = undefined;
}
if (object.subject !== undefined && object.subject !== null) {
message.subject = Subject.fromJSON(object.subject);
} else {
message.subject = 0;
}
if (object.intent !== undefined && object.intent !== null) {
message.intent = Intent.fromJSON(object.intent);
} else {
message.intent = 0;
}
if (object.interaction !== undefined && object.interaction !== null) {
message.interaction = Interaction.fromJSON(object.interaction);
} else {
message.interaction = 0;
}
if (object.channel !== undefined && object.channel !== null) {
message.channel = InteractionChannel.fromJSON(object.channel);
} else {
message.channel = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<InteractionEvent>): InteractionEvent {
const message = { ...baseInteractionEvent } as InteractionEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromPartial(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromPartial(object.application);
} else {
message.application = undefined;
}
if (object.subject !== undefined && object.subject !== null) {
message.subject = object.subject;
} else {
message.subject = 0;
}
if (object.intent !== undefined && object.intent !== null) {
message.intent = object.intent;
} else {
message.intent = 0;
}
if (object.interaction !== undefined && object.interaction !== null) {
message.interaction = object.interaction;
} else {
message.interaction = 0;
}
if (object.channel !== undefined && object.channel !== null) {
message.channel = object.channel;
} else {
message.channel = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: InteractionEvent): unknown {
const obj: any = {};
obj.actor = message.actor ? Actor.toJSON(message.actor) : undefined;
obj.application = message.application ? Application.toJSON(message.application) : undefined;
obj.subject = Subject.toJSON(message.subject);
obj.intent = Intent.toJSON(message.intent);
obj.interaction = Interaction.toJSON(message.interaction);
obj.channel = InteractionChannel.toJSON(message.channel);
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const InteractionEvent_AttributesEntry = {
fromJSON(object: any): InteractionEvent_AttributesEntry {
const message = { ...baseInteractionEvent_AttributesEntry } as InteractionEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<InteractionEvent_AttributesEntry>): InteractionEvent_AttributesEntry {
const message = { ...baseInteractionEvent_AttributesEntry } as InteractionEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: InteractionEvent_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
export const VisitEvent = {
fromJSON(object: any): VisitEvent {
const message = { ...baseVisitEvent } as VisitEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromJSON(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromJSON(object.application);
} else {
message.application = undefined;
}
if (object.location !== undefined && object.location !== null) {
message.location = String(object.location);
} else {
message.location = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<VisitEvent>): VisitEvent {
const message = { ...baseVisitEvent } as VisitEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromPartial(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromPartial(object.application);
} else {
message.application = undefined;
}
if (object.location !== undefined && object.location !== null) {
message.location = object.location;
} else {
message.location = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: VisitEvent): unknown {
const obj: any = {};
obj.actor = message.actor ? Actor.toJSON(message.actor) : undefined;
obj.application = message.application ? Application.toJSON(message.application) : undefined;
obj.location = message.location || "";
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const VisitEvent_AttributesEntry = {
fromJSON(object: any): VisitEvent_AttributesEntry {
const message = { ...baseVisitEvent_AttributesEntry } as VisitEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<VisitEvent_AttributesEntry>): VisitEvent_AttributesEntry {
const message = { ...baseVisitEvent_AttributesEntry } as VisitEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: VisitEvent_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
export const ClickEvent = {
fromJSON(object: any): ClickEvent {
const message = { ...baseClickEvent } as ClickEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromJSON(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromJSON(object.application);
} else {
message.application = undefined;
}
if (object.target !== undefined && object.target !== null) {
message.target = String(object.target);
} else {
message.target = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
message.attributes[key] = String(value);
})
}
return message;
},
fromPartial(object: DeepPartial<ClickEvent>): ClickEvent {
const message = { ...baseClickEvent } as ClickEvent;
message.attributes = {};
if (object.actor !== undefined && object.actor !== null) {
message.actor = Actor.fromPartial(object.actor);
} else {
message.actor = undefined;
}
if (object.application !== undefined && object.application !== null) {
message.application = Application.fromPartial(object.application);
} else {
message.application = undefined;
}
if (object.target !== undefined && object.target !== null) {
message.target = object.target;
} else {
message.target = "";
}
if (object.attributes !== undefined && object.attributes !== null) {
Object.entries(object.attributes).forEach(([key, value]) => {
if (value !== undefined) {
message.attributes[key] = String(value);
}
})
}
return message;
},
toJSON(message: ClickEvent): unknown {
const obj: any = {};
obj.actor = message.actor ? Actor.toJSON(message.actor) : undefined;
obj.application = message.application ? Application.toJSON(message.application) : undefined;
obj.target = message.target || "";
obj.attributes = message.attributes || undefined;
return obj;
},
};
export const ClickEvent_AttributesEntry = {
fromJSON(object: any): ClickEvent_AttributesEntry {
const message = { ...baseClickEvent_AttributesEntry } as ClickEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
fromPartial(object: DeepPartial<ClickEvent_AttributesEntry>): ClickEvent_AttributesEntry {
const message = { ...baseClickEvent_AttributesEntry } as ClickEvent_AttributesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
toJSON(message: ClickEvent_AttributesEntry): unknown {
const obj: any = {};
obj.key = message.key || "";
obj.value = message.value || "";
return obj;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>; |
utilitywarehouse/customer-tracking-sdk | js/packages/core/src/tracker.ts | <gh_stars>1-10
import {
Actor,
Application,
ClickEvent,
Intent,
Interaction,
InteractionChannel,
InteractionEvent,
Stage,
StageEvent,
Subject, VisitEvent,
} from "@utilitywarehouse/customer-tracking-types";
import {EventEmitter} from "events";
import {Backend} from "./backend";
export type EventAttributes = Promise<{[k: string]: string }> | { [k: string]: string }
interface StageArguments {
actor: Actor;
application: Application;
subject: Subject;
intent: Intent;
stage: Stage;
attributes?: EventAttributes;
}
interface InteractionArguments {
actor: Actor;
application: Application;
subject: Subject;
intent: Intent;
interaction: Interaction;
channel: InteractionChannel;
attributes?: EventAttributes;
}
interface ClickArguments {
actor: Actor;
application: Application;
target: string;
attributes?: EventAttributes;
}
interface VisitArguments {
actor: Actor;
application: Application;
location: string;
attributes?: EventAttributes;
}
export class Tracker {
private emitter: EventEmitter;
constructor(private readonly backend: Backend) {
this.emitter = new EventEmitter();
}
private stageValue(m: Stage): string {
return Stage.toJSON(m)
.toLowerCase()
.replace(/^stage_/, "")
.replace(/[^a-z]/g, "-")
}
private subjectValue(m: Subject): string {
return Subject.toJSON(m)
.toLowerCase()
.replace(/^subject_/, "")
.replace(/[^a-z]/g, "-")
}
private intentValue(m: Intent): string {
return Intent.toJSON(m)
.toLowerCase()
.replace(/^intent_/, "")
.replace(/[^a-z]/g, "-")
}
private interactionValue(m: Interaction): string {
return Interaction.toJSON(m)
.toLowerCase()
.replace(/^interaction_/, "")
.replace(/[^a-z]/g, "-")
}
private interactionChannelValue(m: InteractionChannel): string {
return InteractionChannel.toJSON(m)
.toLowerCase()
.replace(/^interaction_channel_/, "")
.replace(/[^a-z]/g, "-")
}
private stageEventName(event: StageEvent): string {
return this.stageValue(event.stage) + "." + this.intentValue(event.intent)
}
private interactionEventName(event: InteractionEvent): string {
return this.interactionChannelValue(event.channel) + "." + this.interactionValue(event.interaction)
}
private attributes(attributes: {[k: string]: string}): {[k: string]: string} {
const mapped: EventAttributes = {};
for (const k in attributes) {
mapped[k.toLowerCase().replace(/[^a-z0-9]/g, "_")] = attributes[k];
}
return mapped;
}
onError(fn: (err: Error) => void): void {
this.emitter.on("error", fn);
}
async trackStage(
inEvent: StageArguments,
): Promise<void> {
try {
const event: StageEvent = {
actor: inEvent.actor,
application: inEvent.application,
subject: inEvent.subject,
intent: inEvent.intent,
stage: inEvent.stage,
attributes: inEvent.attributes && await inEvent.attributes || {},
}
return this.backend.track(
this.stageEventName(event),
event.actor && event.actor.id || undefined,
{
client_id: event.application && event.application.id || "",
subject: this.subjectValue(event.subject),
intent: this.intentValue(event.intent),
stage: this.stageValue(event.stage),
...this.attributes(event.actor && event.actor.attributes || {}),
...this.attributes(event.attributes),
},
)
} catch (e) {
this.emitter.emit("error", e);
}
}
async trackInteraction(
inEvent: InteractionArguments,
): Promise<void> {
try {
const event: InteractionEvent = {
actor: inEvent.actor,
application: inEvent.application,
subject: inEvent.subject,
intent: inEvent.intent,
interaction: inEvent.interaction,
channel: inEvent.channel,
attributes: inEvent.attributes && await inEvent.attributes || {},
}
return this.backend.track(
this.interactionEventName(event),
event.actor && event.actor.id || undefined,
{
client_id: event.application && event.application.id || "",
subject: this.subjectValue(event.subject),
intent: this.intentValue(event.intent),
interaction: this.interactionValue(event.interaction),
interaction_channel: this.interactionChannelValue(event.channel),
...this.attributes(event.actor && event.actor.attributes || {}),
...this.attributes(event.attributes),
},
)
} catch (e) {
this.emitter.emit("error", e);
}
}
async trackClick(
inEvent: ClickArguments,
): Promise<void> {
try {
const event: ClickEvent = {
actor: inEvent.actor,
application: inEvent.application,
target: inEvent.target,
attributes: inEvent.attributes && await inEvent.attributes || {},
}
return this.backend.track(
"click",
event.actor && event.actor.id || undefined,
{
client_id: event.application && event.application.id || "",
target: event.target,
...this.attributes(event.actor && event.actor.attributes || {}),
...this.attributes(event.attributes),
},
)
} catch (e) {
this.emitter.emit("error", e);
}
}
async trackVisit(
inEvent: VisitArguments,
): Promise<void> {
try {
const event: VisitEvent = {
actor: inEvent.actor,
application: inEvent.application,
location: inEvent.location,
attributes: inEvent.attributes && await inEvent.attributes || {},
}
return this.backend.track(
"visit",
event.actor && event.actor.id || undefined,
{
client_id: event.application && event.application.id || "",
location: event.location,
...this.attributes(event.actor && event.actor.attributes || {}),
...this.attributes(event.attributes),
},
)
} catch (e) {
this.emitter.emit("error", e);
}
}
async alias(from: string, to: string): Promise<void> {
try {
return this.backend.alias(
from, to
)
} catch (e) {
this.emitter.emit("error", e);
}
}
} |
utilitywarehouse/customer-tracking-sdk | js/packages/for-browser/src/mixpanel_backend.ts | import mixpanel, {Response, VerboseResponse} from "mixpanel-browser";
import {UIBackend} from "@utilitywarehouse/customer-tracking-core";
import {Actor} from "@utilitywarehouse/customer-tracking-types";
function isMixpanelVerboseResponse(response: Response | number): response is VerboseResponse {
return (response as VerboseResponse).status !== undefined;
}
export class MixpanelBackend implements UIBackend {
constructor(token: string, options?: {[k: string]: string | number}) {
mixpanel.init(token, {
api_host: "https://api-eu.mixpanel.com", // EU by default
...options,
});
}
alias(from: string, to: string): Promise<void> {
return Promise.resolve(mixpanel.alias(from, to));
}
track(eventName: string, distinctId?: string, eventAttributes?: { [p: string]: string }): Promise<void> {
// ignoring distinctId, it's here because of the backend interface
const filteredAttributes: { [p: string]: string } = {};
for (const key in eventAttributes) {
if (eventAttributes[key]) {
filteredAttributes[key] = eventAttributes[key];
}
}
return new Promise((resolve, reject) => {
mixpanel.track(eventName, filteredAttributes, (response: Response | number) => {
if ((response as number) === 1) {
resolve();
return;
}
if (isMixpanelVerboseResponse(response)) {
if (response.status && response.status === 1) {
resolve();
return;
}
if (response.error) {
reject(new Error(response.error));
return;
}
}
reject(new Error("mixpanel response unsuccessful"));
return
})
})
}
disable(): Promise<void> {
return Promise.resolve(mixpanel.opt_out_tracking())
}
enable(): Promise<void> {
return Promise.resolve(mixpanel.opt_in_tracking());
}
identify(actor: Actor): Promise<void> {
return Promise.resolve(mixpanel.identify(actor.id));
}
reset(): Promise<void> {
return Promise.resolve(mixpanel.reset());
}
} |
vininet17/catalog-miwsm | server/src/routes.ts | import express, { request } from 'express';
import ItemsController from './controllers/ItemsController';
const routes = express.Router();
const itemsController = new ItemsController;
routes.get('/items', itemsController.index);
export default routes; |
vininet17/catalog-miwsm | server/src/database/seeds/create_items.ts | import Knex from 'knex';
export async function seed(knex: Knex){
await knex('items').insert([
{ title: 'Tag', image: 'TAG.png' },
]);
}; |
giovannicruz97/controlador-de-carteira | src/entities/FinancialAsset.ts | <gh_stars>1-10
import { Type } from './Type'
export default class FinancialAsset {
private name: string;
private ticker: string;
private type: Type;
private price: number;
public constructor({ name, ticker, type, price }: { name: string; ticker: string; type: Type; price: number }) {
this.name = name;
this.ticker = ticker;
this.type = type;
this.price = price;
}
public getName(): string {
return this.name;
}
public setName(name: string): void {
this.name = name;
}
public getTicker(): string {
return this.ticker;
}
public setTicker(ticker: string): void {
this.ticker = ticker;
}
public getType(): Type {
return this.type;
}
public setType(type: Type): void {
this.type = type;
}
public getPrice(): number {
return this.price;
}
public setPrice(price: number): void {
this.price = price;
}
} |
giovannicruz97/controlador-de-carteira | src/repositories/FinancialAssetRepository.ts | <gh_stars>1-10
import FinancialAsset from "../entities/FinancialAsset";
import { Type } from "../entities/Type";
export default interface FinancialAssetRepository {
getByTicker({ ticker, url }: { ticker: string; url: string; }): Promise<FinancialAsset>
}; |
giovannicruz97/controlador-de-carteira | src/interface_adapters/repositories/web/FinancialAssetRepositoryWeb.test.ts | <filename>src/interface_adapters/repositories/web/FinancialAssetRepositoryWeb.test.ts
import Axios from "../../../drivers/Axios";
import Cheerio from '../../../drivers/Cheerio';
import FinancialAsset from "../../../entities/FinancialAsset";
import { Type } from "../../../entities/Type";
import FinancialAssetRepositoryWeb from "./FinancialAssetRepositoryWeb";
let financialAssetRepositoryWeb: FinancialAssetRepositoryWeb;
beforeAll(() => {
financialAssetRepositoryWeb = new FinancialAssetRepositoryWeb({
httpClient: Axios,
scraper: Cheerio,
})
});
test('Get ETF from Status Invest', async () => {
const expected = new FinancialAsset({
name: 'ISHARES S&P 500 FDO INV COTAS FDO INDICE',
ticker: 'ivvb11',
price: 260.80,
type: Type.ETF,
});
const ivvb11 = await financialAssetRepositoryWeb.getByTicker({
ticker: 'ivvb11',
url: 'etfs/ivvb11'
});
expect(ivvb11.getName()).toBe(expected.getName());
expect(ivvb11.getPrice()).toBe(expected.getPrice());
expect(ivvb11.getType()).toBe(expected.getType());
});
test('Get Real Estate Investment fund from Status Invest', async () => {
const expected = new FinancialAsset({
name: 'FII UBSOFFIC',
ticker: 'rect11',
price: 71.93,
type: Type.REAL_ESTATE_INVESTIMENT_FUND,
});
const rect11 = await financialAssetRepositoryWeb.getByTicker({
ticker: 'rect11',
url: 'fundos-imobiliarios/rect11'
});
expect(rect11.getName()).toBe(expected.getName());
expect(rect11.getPrice()).toBe(expected.getPrice());
expect(rect11.getType()).toBe(expected.getType());
});
test('Get Stock Investment Fund from Status Invest', async () => {
const expected = new FinancialAsset({
name: 'CLUBEDOVALOR DEEP VALUE INVESTING FIC FIA',
ticker: 'cdv',
price: 1,
type: Type.STOCK_INVESTIMENT_FUND,
});
const cdv = await financialAssetRepositoryWeb.getByTicker({
ticker: 'cdv',
url: 'fundos-de-investimento/clubedovalor-deep-value-investing-fic-fia'
});
expect(cdv.getName()).toBe(expected.getName());
expect(cdv.getPrice()).toBe(expected.getPrice());
expect(cdv.getType()).toBe(expected.getType());
});
test('Get Stock from Status Invest', async () => {
const expected = new FinancialAsset({
name: 'ITAUSA INVESTIMENTOS ITAU S.A.',
ticker: 'itsa4',
price: 9.56,
type: Type.STOCK,
});
const itsa4 = await financialAssetRepositoryWeb.getByTicker({
ticker: 'itsa4',
url: 'acoes/itsa4'
});
expect(itsa4.getName()).toBe(expected.getName());
expect(itsa4.getPrice()).toBe(expected.getPrice());
expect(itsa4.getType()).toBe(expected.getType());
}); |
giovannicruz97/controlador-de-carteira | src/entities/Type.ts | export enum Type {
STOCK = 'stock',
ETF = 'ETF',
REAL_ESTATE_INVESTIMENT_FUND = 'real estate investiment fund',
STOCK_INVESTIMENT_FUND = 'stock investiment fund',
CRYPTOCURRENCY = 'cryptocurrency'
} |
giovannicruz97/controlador-de-carteira | src/use_cases/RebalancePortfolio.ts | import { Operation } from '../entities/Operation';
import Portfolio from '../entities/Portfolio';
import Product from '../entities/Product';
import FinancialAssetRepository from '../repositories/FinancialAssetRepository';
import RebalancePortfolioInput from './dto/RebalancePortfolioInput';
import RebalancePortfolioOutput from './dto/RebalancePortfolioOutput';
export default class RebalancePortfolio {
private financialAssetRepository: FinancialAssetRepository;
public constructor({ financialAssetRepository }: { financialAssetRepository: FinancialAssetRepository }) {
this.financialAssetRepository = financialAssetRepository;
}
public async execute({ assets, contribution }: RebalancePortfolioInput): Promise<RebalancePortfolioOutput[]> {
const products = await Promise.all(assets.map(async product => new Product({
financialAsset: await this.financialAssetRepository.getByTicker({ ticker: product.ticker, url: product.url }),
currentQuantity: product.currentQuantity,
targetAllocationPercentage: product.targetAllocationPercentage
})));
const portfolio = new Portfolio({ products });
return portfolio.calculateRebalancing({ contribution });
}
} |
giovannicruz97/controlador-de-carteira | src/drivers/Cheerio.ts | <reponame>giovannicruz97/controlador-de-carteira
import cheerio from 'cheerio';
import Scraper from "./adapters/Scraper";
class Cheerio implements Scraper {
private scraper: any;
public constructor() {
this.scraper = cheerio;
}
public load(html: string): any {
return this.scraper.load(html);
}
}
export default new Cheerio(); |
giovannicruz97/controlador-de-carteira | src/interface_adapters/controllers/RebalancePortfolioController.ts | import RebalancePortfolioInput from "../../use_cases/dto/RebalancePortfolioInput";
import RebalancePortfolio from "../../use_cases/RebalancePortfolio";
export default class RebalancePortfolioController {
private useCase: RebalancePortfolio;
public constructor({ useCase }: { useCase: RebalancePortfolio }) {
this.useCase = useCase;
}
public async handle(payload: any) {
try {
const rebalancePortfolioInput = new RebalancePortfolioInput({ assets: payload.assets, contribution: payload.contribution });
return this.useCase.execute(rebalancePortfolioInput);
} catch (error) {
console.error(error);
}
}
} |
giovannicruz97/controlador-de-carteira | src/drivers/adapters/HttpClient.ts | export default interface HttpClient {
get(url: string): Promise<any>;
} |
giovannicruz97/controlador-de-carteira | src/entities/Portfolio.ts | <reponame>giovannicruz97/controlador-de-carteira<filename>src/entities/Portfolio.ts
import { Operation } from './Operation';
import Product from "./Product";
import { Type } from './Type';
export default class Portfolio {
private products: Product[];
private totalValue: number;
public constructor({ products }: { products: Product[] }) {
this.products = products;
this.validateProductsTotalPercentage();
this.totalValue = 0;
products.forEach(product => this.totalValue += product.getTotalPrice());
}
public getTotalValue(): number {
return this.totalValue;
}
public getProducts(): Product[] {
return this.products;
}
public setProducts(products: Product[]): void {
this.products = products;
}
public validateProductsTotalPercentage(): void {
let totalPercentage = 0;
this.products.forEach(product => totalPercentage += product.getTargetAllocationPercentage());
totalPercentage = Math.floor(totalPercentage);
if (totalPercentage !== 100) throw new Error('The sum of the percentages of the products in the portfolio is greater than 100%')
}
public calculateRebalancing({ contribution }: { contribution: number }): { name: string; ticker: string; currentAllocationPercentage: number; targetAllocationPercentage: number; quantity: number; operation: Operation, operationCost: number }[] {
return this.products
.map(product => {
const name = product.getFinancialAsset().getName();
const ticker = product.getFinancialAsset().getTicker();
const portfolioTotalValue = this.getTotalValue() + contribution;
const targetAllocationPercentage = product.getTargetAllocationPercentage();
const targetAllocationInValue = portfolioTotalValue * (targetAllocationPercentage / 100);
const financialAssetPrice = product.getFinancialAsset().getPrice();
const currentQuantity = product.getCurrentQuantity();
let targetQuantity = targetAllocationInValue / product.getTotalPrice();
if (currentQuantity === 0) targetQuantity = targetAllocationInValue / financialAssetPrice;
let quantityNeededToTarget = Math.floor(Math.abs(currentQuantity - targetQuantity));
if (product.getFinancialAsset().getType() === Type.STOCK_INVESTIMENT_FUND) quantityNeededToTarget = targetAllocationInValue - currentQuantity;
if (currentQuantity === 0) quantityNeededToTarget = Math.floor(targetQuantity);
const operationCost = quantityNeededToTarget * financialAssetPrice;
const currentAllocationPercentage = (product.getTotalPrice() / portfolioTotalValue) * 100;
const operation = currentAllocationPercentage <= targetAllocationPercentage ? Operation.BUY : Operation.SELL;
return {
name,
ticker,
targetAllocationPercentage,
currentAllocationPercentage,
quantity: quantityNeededToTarget,
operation,
operationCost
};
})
.sort((a, b) => {
return a.currentAllocationPercentage - b.currentAllocationPercentage;
});
}
} |
giovannicruz97/controlador-de-carteira | src/use_cases/dto/RebalancePortfolioInput.ts | <reponame>giovannicruz97/controlador-de-carteira<filename>src/use_cases/dto/RebalancePortfolioInput.ts
interface Asset {
ticker: string;
currentQuantity: number;
targetAllocationPercentage: number;
url: string;
};
export default class RebalancePortfolioInput {
public assets: Asset[];
public contribution: number;
public constructor({ assets, contribution = 0 }: { assets: Asset[]; contribution?: number }) {
this.assets = assets;
this.contribution = contribution;
}
} |
giovannicruz97/controlador-de-carteira | src/use_cases/RebalancePortfolio.test.ts | import RebalancePortfolio from "./RebalancePortfolio";
import FinancialAssetRepository from "../repositories/FinancialAssetRepository";
import FinancialAssetRepositoryInMemory from "../interface_adapters/repositories/memory/FinancialAssetRepositoryInMemory";
import { Operation } from '../entities/Operation';
let financialAssetRepository: FinancialAssetRepository;
beforeAll(() => {
financialAssetRepository = new FinancialAssetRepositoryInMemory();
})
test('Calculate currentAllocationPercentage between products and return rebalance list', async () => {
const useCase = new RebalancePortfolio({ financialAssetRepository });
const response = await useCase.execute({
assets: [{
ticker: "ivvb11",
currentQuantity: 10,
targetAllocationPercentage: 50,
url: 'mock'
},
{
ticker: 'bova11',
currentQuantity: 10,
targetAllocationPercentage: 50,
url: 'mock'
}],
contribution: 0,
});
const expected = [
{
name: 'BOVA11',
ticker: 'bova11',
currentAllocationPercentage: 26.449750721595382,
operation: Operation.BUY,
quantity: 8,
operationCost: 806.4,
targetAllocationPercentage: 50
},
{
name: 'IVVB11',
ticker: 'ivvb11',
currentAllocationPercentage: 73.55024927840462,
operation: Operation.SELL,
quantity: 9,
operationCost: 2522.7000000000003,
targetAllocationPercentage: 50,
}
];
expect(response).toEqual(expected);
});
test('Calculate rebalacing for products with quantity 0 (zero)', async () => {
const useCase = new RebalancePortfolio({ financialAssetRepository });
const response = await useCase.execute({
assets: [{
ticker: "ivvb11",
currentQuantity: 0,
targetAllocationPercentage: 50,
url: 'mock'
},
{
ticker: 'bova11',
currentQuantity: 0,
targetAllocationPercentage: 50,
url: 'mock'
}],
contribution: 1000,
});
const [ivvb11, bova11] = response;
expect(ivvb11.quantity).toBe(1);
expect(bova11.quantity).toBe(4);
}); |
giovannicruz97/controlador-de-carteira | src/use_cases/dto/RebalancePortfolioOutput.ts | export default class RebalancePortfolioOutput {
public name: string;
public ticker: string;
public currentAllocationPercentage: number;
public targetAllocationPercentage: number;
public operation: string;
public quantity: number;
public operationCost: number;
public constructor({ name, ticker, currentAllocationPercentage, targetAllocationPercentage, operation, quantity, operationCost }: { name: string; ticker: string; currentAllocationPercentage: number; targetAllocationPercentage: number; operation: string; quantity: number; operationCost: number }) {
this.name = name;
this.ticker = ticker;
this.currentAllocationPercentage = currentAllocationPercentage;
this.operation = operation;
this.targetAllocationPercentage = targetAllocationPercentage;
this.quantity = quantity;
this.operationCost = operationCost;
}
} |
giovannicruz97/controlador-de-carteira | src/drivers/adapters/Scraper.ts | <filename>src/drivers/adapters/Scraper.ts
export default interface Scraper {
load(html: string): any;
} |
giovannicruz97/controlador-de-carteira | src/drivers/Axios.ts | import axios, { AxiosInstance } from 'axios';
import HttpClient from './adapters/HttpClient';
class Axios implements HttpClient {
private client: AxiosInstance;
public constructor() {
this.client = axios.create({
baseURL: 'https://statusinvest.com.br/',
});
}
public get(url: string): Promise<any> {
return this.client.get(url);
}
}
export default new Axios(); |
giovannicruz97/controlador-de-carteira | src/interface_adapters/repositories/web/FinancialAssetRepositoryWeb.ts | <filename>src/interface_adapters/repositories/web/FinancialAssetRepositoryWeb.ts
import HttpClient from "../../../drivers/adapters/HttpClient";
import Scraper from "../../../drivers/adapters/Scraper";
import FinancialAsset from "../../../entities/FinancialAsset";
import { Type } from "../../../entities/Type";
import FinancialAssetRepository from "../../../repositories/FinancialAssetRepository";
export default class FinancialAssetRepositoryWeb implements FinancialAssetRepository {
private httpClient: HttpClient;
private scraper: Scraper;
private assetsDictionary: any;
public constructor({
httpClient,
scraper
}: { httpClient: HttpClient; scraper: Scraper }) {
this.httpClient = httpClient;
this.scraper = scraper;
this.assetsDictionary = {
'acoes': Type.STOCK,
'etfs': Type.ETF,
'fundos-imobiliarios': Type.REAL_ESTATE_INVESTIMENT_FUND,
'fundos-de-investimento': Type.STOCK_INVESTIMENT_FUND,
};
}
private getTypeFromUrl({ url }: { url: string }): Type {
const [type] = url.split('/');
return this.assetsDictionary[type];
}
private getNameFromPage({ selector }: { selector: any }): string {
const name =
selector("#company-section").find(".mb-2.mt-0.fs-4.fs-xl-5.lh-5.lh-xl-5.d-block span.d-block.fw-600.text-main-green-dark").text() ||
selector('#fund-section > div > div > div:nth-child(2) > div > div:nth-child(2) > div > div > div > strong').html() ||
selector('#company-section > div > div.d-block.d-md-flex.mb-5.img-lazy-group > div > div > div:nth-child(1) > h4 > span').html() ||
selector('#company-section > div:nth-child(1) > div > div.d-block.d-md-flex.mb-5.img-lazy-group > div.company-description.w-100.w-md-70.ml-md-5 > h4 > span').html();
return name;
}
public async getByTicker({ ticker, url }: { ticker: string; url: string; }): Promise<FinancialAsset> {
try {
const { data } = await this.httpClient.get(url);
const selector = this.scraper.load(data);
const name = this.getNameFromPage({ selector });
const type = this.getTypeFromUrl({ url });
let price = 1;
if (type !== Type.STOCK_INVESTIMENT_FUND) price = Number(selector("#main-2").find("div strong.value").html().replace(',', '.'));
return new FinancialAsset({ name, ticker, price, type });
} catch (error: any) {
throw new Error(`FinancialAssetRepositoryWeb: ${error.message}`)
}
}
} |
giovannicruz97/controlador-de-carteira | src/main/cli.ts | import Table from 'cli-table';
import Axios from '../drivers/Axios';
import Cheerio from '../drivers/Cheerio';
import RebalancePortfolioController from '../interface_adapters/controllers/RebalancePortfolioController';
import FinancialAssetRepositoryWeb from '../interface_adapters/repositories/web/FinancialAssetRepositoryWeb';
// import FinancialAssetRepositoryInMemory from '../interface_adapters/repositories/memory/FinancialAssetRepositoryInMemory';
import products from '../products.json';
import RebalancePortfolio from '../use_cases/RebalancePortfolio';
(async () => {
const table = new Table({
head: ['Name', 'Ticker', 'Target (%)', 'Current (%)', 'Quantity', 'Operation', 'Operation Cost']
});
const contribution = Number(process.argv[2]);
// const financialAssetRepository = new FinancialAssetRepositoryInMemory();
const financialAssetRepository = new FinancialAssetRepositoryWeb({ httpClient: Axios, scraper: Cheerio });
const useCase = new RebalancePortfolio({ financialAssetRepository });
const rebalancePortfolio = new RebalancePortfolioController({ useCase });
const rebalancing = await rebalancePortfolio.handle({ assets: products, contribution });
rebalancing?.forEach(product => {
const values = Object.values(product);
values[1] = values[1].toUpperCase();
values[6] = `R$${values[6]}`;
table.push(values);
});
console.log(table.toString());
})()
|
giovannicruz97/controlador-de-carteira | src/interface_adapters/repositories/memory/FinancialAssetRepositoryInMemory.ts | <filename>src/interface_adapters/repositories/memory/FinancialAssetRepositoryInMemory.ts
import { Type } from '../../../entities/Type';
import FinancialAsset from "../../../entities/FinancialAsset";
import FinancialAssetRepository from "../../../repositories/FinancialAssetRepository";
export default class FinancialAssetRepositoryInMemory implements FinancialAssetRepository {
private financialAssets: FinancialAsset[];
public constructor() {
this.financialAssets = [
new FinancialAsset({ name: 'IVVB11', ticker: 'ivvb11', price: 280.30, type: Type.ETF }),
new FinancialAsset({ name: 'BOVA11', ticker: 'bova11', price: 100.8, type: Type.ETF }),
new FinancialAsset({
name: 'CLUBEDOVALOR DEEP VALUE INVESTING FICFIA', ticker: 'cdv', price: 1, type: Type.STOCK_INVESTIMENT_FUND
}),
new FinancialAsset({ name: 'MXRF11', ticker: 'mxrf11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 10.01 }),
new FinancialAsset({ name: 'IBFF11', ticker: 'ibff11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 59.76 }),
new FinancialAsset({ name: 'CVBI11', ticker: 'cvbi11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 102.25 }),
new FinancialAsset({ name: 'RBVA11 ', ticker: 'rbva11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 102.49 }),
new FinancialAsset({ name: 'RBRY11 ', ticker: 'rbry11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 104.60 }),
new FinancialAsset({ name: 'RNGO11', ticker: 'rngo11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 52.97 }),
new FinancialAsset({ name: 'XPCM11', ticker: 'xpcm11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 22.23 }),
new FinancialAsset({ name: 'XPPR11', ticker: 'xppr11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 66.60 }),
new FinancialAsset({ name: 'OULG11', ticker: 'oulg11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 57.80 }),
new FinancialAsset({ name: 'FEXC11', ticker: 'fexc11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 89 }),
new FinancialAsset({ name: 'OUFF11', ticker: 'ouff11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 72.25 }),
new FinancialAsset({ name: 'BRCR11', ticker: 'brcr11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 72.69 }),
new FinancialAsset({ name: 'RECT11', ticker: 'rect11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 70.38 }),
new FinancialAsset({ name: 'XPCI11', ticker: 'xpci11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 96.81 }),
new FinancialAsset({ name: 'VGIR11', ticker: 'vgir11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 98.70 }),
new FinancialAsset({ name: 'RBCO11', ticker: 'rbco11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 57.00 }),
new FinancialAsset({ name: 'QAGR11', ticker: 'qagr11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 51.25 }),
new FinancialAsset({ name: 'MORE11', ticker: 'more11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 76.14 }),
new FinancialAsset({ name: 'RBHG11', ticker: 'rbhg11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 87.70 }),
new FinancialAsset({ name: 'CPFF11', ticker: 'cpff11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 69.87 }),
new FinancialAsset({ name: 'PATL11', ticker: 'patl11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 74.95 }),
new FinancialAsset({ name: 'AIEC11', ticker: 'aiec11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 76.34 }),
new FinancialAsset({ name: 'EQIN11', ticker: 'eqin11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 93.39 }),
new FinancialAsset({ name: 'GGRC11', ticker: 'ggrc11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 114.90 }),
new FinancialAsset({ name: 'HBRH11', ticker: 'hbrh11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 87.98 }),
new FinancialAsset({ name: 'SARE11', ticker: 'sare11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 69.99 }),
new FinancialAsset({ name: 'OUJP11', ticker: 'oujp11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 88.22 }),
new FinancialAsset({ name: 'NEWL11', ticker: 'newl11', type: Type.REAL_ESTATE_INVESTIMENT_FUND, price: 102.40 }),
new FinancialAsset({ name: 'HASH11', ticker: 'hash11', type: Type.ETF, price: 43.25 })
];
}
public async getByTicker({ ticker, url }: { ticker: string; url: string }): Promise<FinancialAsset> {
const financialAsset = this.financialAssets.find(financialAsset => financialAsset.getTicker() === ticker);
if (!financialAsset) throw new Error(`Financial asset not find by ticker ${ticker}`);
return financialAsset;
}
} |
giovannicruz97/controlador-de-carteira | src/entities/Product.ts | import FinancialAsset from "./FinancialAsset";
export default class Product {
private financialAsset: FinancialAsset;
private targetAllocationPercentage: number;
private currentQuantity: number;
public constructor({ financialAsset, targetAllocationPercentage, currentQuantity }: { financialAsset: FinancialAsset; targetAllocationPercentage: number; currentQuantity: number }) {
this.financialAsset = financialAsset;
this.targetAllocationPercentage = targetAllocationPercentage;
this.currentQuantity = currentQuantity;
}
public getFinancialAsset(): FinancialAsset {
return this.financialAsset;
}
public setFinancialAsset(financialAsset: FinancialAsset): void {
this.financialAsset = financialAsset;
}
public getTargetAllocationPercentage(): number {
return this.targetAllocationPercentage;
}
public setTargetAllocationPercentage(targetAllocationPercentage: number): void {
this.targetAllocationPercentage = targetAllocationPercentage;
}
public getCurrentQuantity(): number {
return this.currentQuantity;
}
public setCurrentQuantity(currentQuantity: number): void {
this.currentQuantity = currentQuantity;
}
public getTotalPrice(): number {
return this.getCurrentQuantity() * this.getFinancialAsset().getPrice();
}
} |
nfroidure/strict-qs | src/index.d.ts | type QSOptions = {
allowEmptySearch: boolean;
allowUnknownParams: boolean;
allowDefault: boolean;
allowUnorderedParams: boolean;
};
type QSValue = string | number | boolean;
type QSParamValue = QSValue;
type QSParamType = 'string' | 'number' | 'boolean';
type QSUniqueParameter = {
name: string;
in: 'query';
pattern?: string;
enum?: QSParamValue[];
type: QSParamType;
};
type QSArrayParameter = {
name: string;
in: 'query';
type: 'array';
ordered: boolean;
items: {
pattern?: string;
enum?: QSParamValue[];
type: QSParamType;
};
};
type QSParameter = QSUniqueParameter | QSArrayParameter;
declare function qsStrict(
options: QSOptions,
definitions: QSParameter[],
search: string,
): {
[name: string]: QSValue | QSValue[];
};
export default qsStrict;
export function parseReentrantNumber(str: string): number;
export function parseBoolean(str: string): boolean;
export function decodeQueryComponent(value: string): string;
|
Subsets and Splits