index.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import { makeStyles, Typography } from '@material-ui/core'
  2. import { useState,useEffect,useCallback,useRef } from 'react';
  3. import { useSelector } from 'react-redux';
  4. import io from 'socket.io-client';
  5. import Moveable from "react-moveable";
  6. import { OnDrag } from "react-moveable";
  7. import ListItemText from '@mui/material/ListItemText';
  8. import ListItemAvatar from '@mui/material/ListItemAvatar';
  9. import Avatar from '@mui/material/Avatar';
  10. import PhoneIcon from '@mui/icons-material/Phone';
  11. import MinimizeIcon from '@mui/icons-material/Minimize';
  12. import CropLandscapeIcon from '@mui/icons-material/CropLandscape';
  13. import CloseIcon from '@mui/icons-material/Close';
  14. import VideocamIcon from '@mui/icons-material/Videocam';
  15. import VideocamOffIcon from '@mui/icons-material/VideocamOff';
  16. import MicIcon from '@mui/icons-material/Mic';
  17. import MicOffIcon from '@mui/icons-material/MicOff';
  18. import CallEndIcon from '@mui/icons-material/CallEnd';
  19. import StopScreenShareIcon from '@mui/icons-material/StopScreenShare';
  20. import Alert from '@mui/material/Alert';
  21. import { getChat } from '../../../redux/chat/selector';
  22. import { getAuthorizationState } from '../../../redux/authorization/selector';
  23. import { prodAwsS3,prodBaseURL,prodSocketURL, firstLetter, slicedWord,getTimeBySeconds,playNotification } from '../../../helpers'
  24. import { socketIdChat,sentMessageCallById } from '../../../api-data';
  25. const Peer = require('simple-peer')
  26. const socket = io(prodSocketURL)
  27. const useStyles = makeStyles({
  28. container: {
  29. position: 'absolute',
  30. left: 0,
  31. top: 0,
  32. width: '100vw',
  33. height:'100vh',
  34. overflow: 'hidden',
  35. zIndex:100,
  36. display: 'flex',
  37. justifyContent: 'center',
  38. alignItems: 'center',
  39. alignContent: "center",
  40. backgroundColor: 'rgba(104, 105, 104, 0.6)',
  41. },
  42. modalCall: {
  43. background: 'rgb(36, 36, 36)',
  44. position:'relative',
  45. display: 'flex',
  46. flexDirection: 'column',
  47. justifyContent: 'start',
  48. alignItems: 'center',
  49. justifyItems:"center",
  50. borderRadius: 7,
  51. },
  52. rightIcons: {
  53. display: 'flex',
  54. justifyContent: 'end',
  55. alignContent: 'center',
  56. alignItems: 'center',
  57. width: '100%',
  58. position: 'absolute',
  59. left: 0,
  60. top: 0,
  61. zIndex:1
  62. },
  63. rightIconWrapper: {
  64. color: '#ffffff',
  65. cursor: 'pointer',
  66. padding:'3px 10px 3px 10px',
  67. },
  68. rightIconWrapperClose: {
  69. color: '#ffffff',
  70. cursor: 'pointer',
  71. padding: '3px 10px 3px 10px',
  72. backgroundColor:'rgb(36, 36, 36)',
  73. borderTopRightRadius:7,
  74. '&:hover': {
  75. backgroundColor:'#f02a2a'
  76. }
  77. },
  78. bottomWrapper: {
  79. display: 'flex',
  80. justifyContent: 'center',
  81. padding: 5,
  82. position: "absolute",
  83. left: 0,
  84. bottom: 0,
  85. width:'100%'
  86. },
  87. bottomItem: {
  88. display: 'flex',
  89. flexDirection: 'column',
  90. justifyContent: 'center',
  91. alignContent: 'center',
  92. alignItems: 'center',
  93. cursor:'pointer',
  94. width: 80,
  95. },
  96. bottomIcon: {
  97. cursor:'pointer',
  98. },
  99. bottomIconEndAccept: {
  100. cursor: 'pointer',
  101. '&:hover': {
  102. animation: `$shake 1s`,
  103. animationIterationCount:'infinite',
  104. }
  105. },
  106. ringPulsate: {
  107. backgroundColor:"rgb(80, 80, 80)",
  108. borderRadius: '50%',
  109. height: 60,
  110. width: 60,
  111. position: 'absolute',
  112. left: 10,
  113. top: -8,
  114. animation: `$pulsate 1.5s ease-out`,
  115. animationIterationCount: 'infinite',
  116. opacity: 0,
  117. },
  118. titleIconBottom: {
  119. color: '#ffffff',
  120. fontSize: 13,
  121. paddingTop:7
  122. },
  123. myVideo: {
  124. cursor: 'pointer',
  125. position: 'absolute',
  126. top: 0,
  127. left: 0,
  128. zIndex: 150,
  129. },
  130. '@keyframes pulsate': {
  131. '0%': {transform: 'scale(1, 1)', opacity: 0},
  132. '50%': { opacity: 1},
  133. '100%': {transform: 'scale(1.2, 1.2)', opacity: 0},
  134. },
  135. '@keyframes shake': {
  136. '0%': { transform: 'rotate(0deg)'},
  137. '11%': { transform: 'rotate(10deg)'},
  138. '22%': { transform: 'rotate(20deg)'},
  139. '33%': { transform: 'rotate(30deg)'},
  140. '44%': { transform: 'rotate(20deg)'},
  141. '55%': { transform: 'rotate(10deg)'},
  142. '66%': { transform: 'rotate(0deg)'},
  143. '77%': { transform: 'rotate(-10deg)'},
  144. '88%': { transform: 'rotate(-20deg)'},
  145. '100%': { transform: 'rotate(-30deg)'},
  146. },
  147. })
  148. interface ICallBar {
  149. callStatus:any,
  150. setCallStatus: any,
  151. }
  152. const CallBar = ({callStatus,setCallStatus}:ICallBar) => {
  153. const classes = useStyles()
  154. const { _id } = useSelector(getAuthorizationState)
  155. const { socketId, companionId, name:_name,lastName:_lastName,avatarUrl:_avatarUrl,color:_color,number:_number } = useSelector(getChat)
  156. const connectionRef = useRef<any>(null);
  157. const myVideoRef = useRef<any>(null);
  158. const companionVideoRef = useRef<any>(null);
  159. const companionAudioRef = useRef<any>(null);
  160. const idAudioIntervalRef = useRef<any>(null);
  161. const [mySocket, setMySocket] = useState<string>('')
  162. const [myStream, setMyStream] = useState<any>(null)
  163. const [myShareStream, setMyShareStream] = useState<any>(null)
  164. const [mutedMyVideo,setMutedMyVideo] = useState<boolean>(true)
  165. const [mutedMyAudio,setMutedMyAudio] = useState<boolean>(false)
  166. const [companionSocket, setCompanionSocket] = useState<string>('')
  167. const [companionSignal, setCompanionSignal] = useState<any>(null)
  168. const [audioHtml, setAudioHtml] = useState<any>(null)
  169. const [callLast, setCallLast] = useState<number>(0)
  170. const [conversationLast, cetConversationLast] = useState<string>('')
  171. const [fullScreen, setFullScreen] = useState<boolean>(false)
  172. const [alert, setAlert] = useState<string>('')
  173. const [name, setName] = useState<string>('')
  174. const [lastName, setLastName] = useState<string>('')
  175. const [avatarUrl, setAvatarUrl] = useState<string>('')
  176. const [color, setColor] = useState<string>('')
  177. const [number, setNumber] = useState<string>('')
  178. const handleLeaveCall = useCallback(() => {
  179. setCallStatus('hanging up...')
  180. if (connectionRef.current) {
  181. connectionRef.current.destroy()
  182. connectionRef.current = null
  183. }
  184. if(idAudioIntervalRef.current) clearInterval(idAudioIntervalRef.current)
  185. myVideoRef.current.srcObject = null
  186. companionVideoRef.current.srcObject = null
  187. companionAudioRef.current.srcObject = null
  188. if (audioHtml) {
  189. audioHtml.pause()
  190. setAudioHtml(null)
  191. }
  192. if(myStream) myStream.getTracks().forEach((track:any) => track.stop())
  193. setMyShareStream(null)
  194. setMutedMyVideo(false)
  195. setMutedMyAudio(false)
  196. setCompanionSocket('')
  197. setMyStream(null)
  198. setCompanionSignal(null)
  199. setCallLast(0)
  200. cetConversationLast('')
  201. setFullScreen(false)
  202. setAlert('')
  203. setTimeout(() => {
  204. setCallStatus('')
  205. setName('')
  206. setLastName('')
  207. setAvatarUrl('')
  208. setColor('')
  209. setNumber('')
  210. },500)
  211. }, [setCallStatus, audioHtml, myStream])
  212. const handleConversationLast = (e: any) =>
  213. cetConversationLast(getTimeBySeconds(e.target.currentTime))
  214. const handleMuteShare = async () => {
  215. try {
  216. if (myStream) {
  217. const mediaDevices: any = navigator.mediaDevices;
  218. const stream = await mediaDevices.getDisplayMedia({
  219. video: true,
  220. audio: true
  221. })
  222. setMyShareStream(stream)
  223. const shareTrack = stream.getVideoTracks()[0]
  224. const videoTrack = myStream.getVideoTracks()[0]
  225. const senders = connectionRef.current._pc.getSenders()
  226. const replaceStream = (track:any) => senders.forEach((sender: any) => sender.track.kind === "video" &&
  227. sender.replaceTrack(track))
  228. shareTrack.onended = () => {
  229. setMyShareStream(null)
  230. replaceStream(videoTrack)
  231. }
  232. replaceStream(shareTrack)
  233. } else {
  234. setAlert(`Can not start Share before stream`)
  235. setTimeout(() => setAlert(''),2000)
  236. }
  237. } catch (e: any) {
  238. setAlert(`Permission for getDisplayMedia is required!`)
  239. setTimeout(() => setAlert(''),2000)
  240. }
  241. }
  242. const handleMuteVideo = () => {
  243. if (myStream&&myStream.getVideoTracks()[0]) {
  244. setMutedMyVideo(!mutedMyVideo)
  245. myStream.getVideoTracks()[0].enabled = !myStream.getVideoTracks()[0].enabled
  246. } else {
  247. setAlert(`Can not ${mutedMyVideo ? 'start' : 'stop'} Video before stream`)
  248. setTimeout(() => setAlert(''),2000)
  249. }
  250. }
  251. const handleMuteAudio = () => {
  252. if (myStream&&myStream.getAudioTracks()[0]) {
  253. setMutedMyAudio(!mutedMyAudio)
  254. myStream.getAudioTracks()[0].enabled = !myStream.getAudioTracks()[0].enabled
  255. } else {
  256. setAlert(`Can not start ${mutedMyAudio ? 'start' : 'stop'} Audio before stream`)
  257. setTimeout(() => setAlert(''),2000)
  258. }
  259. }
  260. const handleStartCall = useCallback(async () => {
  261. try {
  262. sentMessageCallById(companionId,false,0)
  263. setCallStatus('waiting...')
  264. const stream = await navigator.mediaDevices.getUserMedia({
  265. video: true,
  266. audio: true
  267. })
  268. stream.getVideoTracks()[0].enabled = false
  269. setMyStream(stream)
  270. myVideoRef.current.srcObject = stream;
  271. const peer = new Peer({
  272. initiator: true,
  273. trickle: false,
  274. stream
  275. });
  276. setCallStatus('ringing...')
  277. const audioRing = playNotification(`${prodBaseURL}/calling.mp3`)
  278. audioRing.loop = true
  279. setAudioHtml(audioRing)
  280. idAudioIntervalRef.current = setInterval(() =>
  281. setCallLast(prevState => prevState + 1), 1000)
  282. peer.on("signal", (data: any) => {
  283. socket.emit("callTo", {
  284. to: socketId,
  285. signalData: data,
  286. from: mySocket,
  287. userId: _id,
  288. companionId,
  289. peer
  290. })
  291. });
  292. peer.on("stream", (companionStream: any) => {
  293. companionVideoRef.current.srcObject = companionStream;
  294. companionAudioRef.current.srcObject = companionStream;
  295. });
  296. peer.on('connect', () => {
  297. audioRing.pause()
  298. setCallStatus('connection')
  299. clearInterval(idAudioIntervalRef.current)
  300. setTimeout(() => setCallStatus('conversation'),500)
  301. })
  302. peer.on("close", handleLeaveCall);
  303. peer.on('error', handleLeaveCall)
  304. socket.on("acceptedCall", ({ signal }: any) => peer.signal(signal));
  305. connectionRef.current = peer;
  306. } catch (e: any) {
  307. setAlert(`Permission for getUserMedia is required!`)
  308. setTimeout(handleLeaveCall,2000)
  309. }
  310. },[socketId,companionId,_id,mySocket,myVideoRef,setCallStatus,handleLeaveCall])
  311. const handleAnswerCall = useCallback(async () => {
  312. try {
  313. audioHtml.pause()
  314. setCallStatus('waiting...')
  315. // const stream = await navigator.mediaDevices.getUserMedia({
  316. // video: true,
  317. // audio: true
  318. // })
  319. //stream.getVideoTracks()[0].enabled = false
  320. // setMyStream(stream)
  321. // myVideoRef.current.srcObject = stream;
  322. const peer = new Peer({
  323. initiator: false,
  324. trickle: false,
  325. stream: false,
  326. });
  327. peer.on("signal", (data: any) => {
  328. socket.emit("answerCall", {
  329. signal: data,
  330. to: companionSocket,
  331. });
  332. });
  333. peer.on("stream", (companionStream: any) => {
  334. companionVideoRef.current.srcObject = companionStream;
  335. companionAudioRef.current.srcObject = companionStream;
  336. });
  337. peer.on('connect', () => {
  338. setCallStatus('connection')
  339. clearInterval(idAudioIntervalRef.current)
  340. setTimeout(() => setCallStatus('conversation'),500)
  341. })
  342. peer.on("close", handleLeaveCall);
  343. peer.on('error', handleLeaveCall)
  344. peer.signal(companionSignal);
  345. connectionRef.current = peer;
  346. } catch (e:any) {
  347. setAlert(`Permission for getUserMedia is required!`)
  348. setTimeout(handleLeaveCall,2000)
  349. }
  350. }, [companionSocket, companionSignal, setCallStatus,audioHtml,handleLeaveCall])
  351. useEffect(() => {
  352. socket.on("me", (id: string) => {
  353. setMySocket(id)
  354. socketIdChat(id)
  355. })
  356. },[])
  357. useEffect(() => {
  358. socket.on('incomeCall', ({ name, lastName, avatarUrl, color, number, from, signal }: any) => {
  359. if (connectionRef.current === null) {
  360. setName(name)
  361. setLastName(lastName)
  362. setAvatarUrl(avatarUrl)
  363. setColor(color)
  364. setNumber(number)
  365. setCompanionSocket(from)
  366. setCompanionSignal(signal)
  367. const audioRing = playNotification(`${prodBaseURL}/ringing.mp3`)
  368. audioRing.loop = true
  369. setAudioHtml(audioRing)
  370. setCallStatus('is calling you')
  371. idAudioIntervalRef.current = setInterval(() =>
  372. setCallLast(prevState => prevState + 1), 1000)
  373. }
  374. })
  375. }, [setCallStatus,companionSocket])
  376. useEffect(() => {
  377. if (callStatus === 'requesting...') {
  378. setName(_name)
  379. setLastName(_lastName)
  380. setAvatarUrl(_avatarUrl)
  381. setColor(_color)
  382. setNumber(_number)
  383. setTimeout(handleStartCall,500)
  384. }
  385. }, [callStatus,_name,_lastName,_avatarUrl,_color,_number, handleStartCall])
  386. useEffect(() => {
  387. if (callLast === 60) handleLeaveCall()
  388. }, [callLast, handleLeaveCall])
  389. return (
  390. <div className={classes.container} style={{ top: callStatus ? 0 : '-100%'}}>
  391. <video className={classes.myVideo} style={{width: !myStream || mutedMyVideo?0:250,height: !myStream || mutedMyVideo?0:'auto'}}
  392. ref={myVideoRef} playsInline autoPlay muted controls={false} />
  393. <Moveable
  394. target={myVideoRef.current}
  395. draggable={true}
  396. throttleDrag={0}
  397. hideDefaultLines={true}
  398. renderDirections={[]}
  399. rotationPosition="none"
  400. origin={false}
  401. onDrag={({ target, transform }: OnDrag) =>
  402. target!.style.transform = transform }
  403. />
  404. <div className={classes.modalCall} style={{width: fullScreen?'100vw':'34vw',height:fullScreen?'100vh':'auto'}}>
  405. <div className={classes.rightIcons}>
  406. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(false)}
  407. style={{backgroundColor:fullScreen?'rgb(36, 36, 36)':'rgb(70, 70, 70)'}}>
  408. <MinimizeIcon fontSize='small' />
  409. </div>
  410. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(true)}
  411. style={{backgroundColor:fullScreen?'rgb(70, 70, 70)':'rgb(36, 36, 36)'}}>
  412. <CropLandscapeIcon fontSize='small' />
  413. </div>
  414. <div className={classes.rightIconWrapperClose} onClick={handleLeaveCall}>
  415. <CloseIcon fontSize='small' />
  416. </div>
  417. </div>
  418. <div style={{ width: '100%', position: "relative" }}>
  419. {alert && <Alert variant="filled" severity="info" sx={{ backgroundColor: "rgb(70, 70, 70)" }}
  420. style={{ width: fullScreen?'auto':"100%", position: 'absolute', left: 0, bottom: -48 }}>{alert}</Alert>}
  421. {!fullScreen && <>
  422. <ListItemAvatar style={{margin:'25px 0px 5px 0px'}}>
  423. <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
  424. sx={{ background: color, width: 120, height: 120, marginRight: 2, fontSize:30,zIndex:0,margin:'0 auto'}}>
  425. {`${firstLetter(name)}${firstLetter(lastName)}`}
  426. </Avatar>
  427. </ListItemAvatar>
  428. <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
  429. ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
  430. primaryTypographyProps={{ color: '#dfdfdf', fontSize: 20, fontWeight: 500,textAlign: "center" }}/>
  431. <ListItemText primary={number} primaryTypographyProps={{ color: '#ffffff', fontSize: 15, fontWeight: 500, textAlign: "center" }} />
  432. <ListItemText secondary={callStatus} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  433. <ListItemText secondary={conversationLast} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  434. </>}
  435. </div>
  436. <video ref={companionVideoRef} playsInline muted autoPlay controls={false}
  437. style={{width: '100%',height:fullScreen?'100vh': 'auto',objectFit: 'cover',
  438. backgroundColor:'rgb(36, 36, 36)'}} onTimeUpdate={handleConversationLast} />
  439. <audio ref={companionAudioRef} autoPlay />
  440. <div className={classes.bottomWrapper}>
  441. {!myShareStream&&<div className={classes.bottomItem} onClick={handleMuteShare}>
  442. <Avatar className={classes.bottomIcon}
  443. sx={{backgroundColor: '#ffffff',color: 'rgb(36, 36, 36)', width: 44, height: 44,zIndex:0}}>
  444. {<StopScreenShareIcon fontSize="medium" />}
  445. </Avatar>
  446. <Typography variant="h6" className={classes.titleIconBottom}>StartShare</Typography>
  447. </div>}
  448. <div className={classes.bottomItem} onClick={handleMuteVideo}>
  449. <Avatar className={classes.bottomIcon}
  450. sx={{backgroundColor: mutedMyVideo?'#ffffff':'rgb(88, 88, 88)',color: mutedMyVideo?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  451. {mutedMyVideo?<VideocamOffIcon fontSize="medium" />:<VideocamIcon fontSize="medium" />}
  452. </Avatar>
  453. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyVideo?'Start Video':'Stop Video'}</Typography>
  454. </div>
  455. <div className={classes.bottomItem}>
  456. <Avatar className={classes.bottomIconEndAccept} onClick={handleLeaveCall}
  457. sx={{backgroundColor: '#f02a2a',color: '#ffffff', width: 44, height: 44,zIndex:0}}>
  458. <CallEndIcon fontSize="medium" />
  459. </Avatar>
  460. <Typography variant="h6" className={classes.titleIconBottom}>
  461. {callStatus === 'is calling you' ? 'Decline' : 'End Call'}
  462. </Typography>
  463. </div>
  464. {callStatus === 'is calling you' &&
  465. <div className={classes.bottomItem} style={{position:"relative"}}>
  466. <div className={classes.ringPulsate}></div>
  467. <Avatar className={classes.bottomIconEndAccept} onClick={handleAnswerCall}
  468. sx={{ backgroundColor: '#21f519', color: '#ffffff', width: 44, height: 44, zIndex: 0 }}>
  469. <PhoneIcon fontSize="medium" />
  470. </Avatar>
  471. <Typography variant="h6" className={classes.titleIconBottom}>
  472. Accept
  473. </Typography>
  474. </div>}
  475. <div className={classes.bottomItem}>
  476. <Avatar className={classes.bottomIcon} onClick={handleMuteAudio}
  477. sx={{backgroundColor: mutedMyAudio?'#ffffff':'rgb(88, 88, 88)',color: mutedMyAudio?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  478. {mutedMyAudio?<MicOffIcon fontSize="medium" />:<MicIcon fontSize="medium" />}
  479. </Avatar>
  480. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyAudio?'Unmute':'Mute'}</Typography>
  481. </div>
  482. </div>
  483. </div>
  484. </div>
  485. )
  486. }
  487. export default CallBar