index.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 } 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 idAudioIntervalRef = useRef<any>(null);
  158. const myVideoRef = useRef<any>(null);
  159. const companionVideoRef = useRef<any>(null);
  160. const companionAudioRef = useRef<any>(null);
  161. const [mySocket, setMySocket] = useState<string>('')
  162. const [mutedMyVideo,setMutedMyVideo] = useState<boolean>(false)
  163. const [mutedMyAudio,setMutedMyAudio] = useState<boolean>(false)
  164. const [companionSocket, setCompanionSocket] = useState<string>('')
  165. const [myStream, setMyStream] = useState<any>(null)
  166. const [myShareStream, setMyShareStream] = useState<any>(null)
  167. const [companionSignal, setCompanionSignal] = useState<any>(null)
  168. const [name, setName] = useState<string>('')
  169. const [lastName, setLastName] = useState<string>('')
  170. const [avatarUrl, setAvatarUrl] = useState<string>('')
  171. const [color, setColor] = useState<string>('')
  172. const [number, setNumber] = useState<string>('')
  173. const [callLast, setCallLast] = useState<number>(0)
  174. const [conversationLast, cetConversationLast] = useState<string>('')
  175. const [fullScreen, setFullScreen] = useState<boolean>(false)
  176. const [alert, setAlert] = useState<string>('')
  177. const [audioHtml, setAudioHtml] = useState<any>(null)
  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 ringing`)
  235. setTimeout(() => setAlert(''),2000)
  236. }
  237. } catch (e: any) {
  238. setAlert(`Permission fro 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 ringing`)
  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 ringing`)
  257. setTimeout(() => setAlert(''),2000)
  258. }
  259. }
  260. const handleStartCall = useCallback(async () => {
  261. try {
  262. setCallStatus('waiting...')
  263. const stream = await navigator.mediaDevices.getUserMedia({
  264. video: true,
  265. audio: true
  266. })
  267. setMyStream(stream)
  268. myVideoRef.current.srcObject = stream;
  269. const peer = new Peer({
  270. initiator: true,
  271. trickle: false,
  272. stream
  273. });
  274. setCallStatus('ringing...')
  275. const audioRing = playNotification(`${prodBaseURL}/calling.mp3`)
  276. audioRing.loop = true
  277. setAudioHtml(audioRing)
  278. idAudioIntervalRef.current = setInterval(() =>
  279. setCallLast(prevState => prevState + 1), 1000)
  280. peer.on("signal", (data: any) => {
  281. socket.emit("callTo", {
  282. to: socketId,
  283. signalData: data,
  284. from: mySocket,
  285. userId: _id,
  286. companionId,
  287. peer
  288. })
  289. });
  290. peer.on("stream", (companionStream: any) => {
  291. companionVideoRef.current.srcObject = companionStream;
  292. companionAudioRef.current.srcObject = companionStream;
  293. });
  294. peer.on('connect', () => {
  295. audioRing.pause()
  296. setCallStatus('connection')
  297. clearInterval(idAudioIntervalRef.current)
  298. setTimeout(() => setCallStatus('conversation'),500)
  299. })
  300. peer.on("close", handleLeaveCall);
  301. peer.on('error', handleLeaveCall)
  302. socket.on("acceptedCall", ({ signal }: any) => peer.signal(signal));
  303. connectionRef.current = peer;
  304. } catch (e:any) {
  305. handleLeaveCall()
  306. }
  307. },[socketId,companionId,_id,mySocket,myVideoRef,setCallStatus,handleLeaveCall])
  308. const handleAnswerCall = useCallback(async () => {
  309. try {
  310. audioHtml.pause()
  311. setCallStatus('waiting...')
  312. // const stream = await navigator.mediaDevices.getUserMedia({
  313. // video: true,
  314. // audio: true
  315. // })
  316. // setMyStream(stream)
  317. // myVideoRef.current.srcObject = stream;
  318. const peer = new Peer({
  319. initiator: false,
  320. trickle: false,
  321. stream: false,
  322. });
  323. peer.on("signal", (data: any) => {
  324. socket.emit("answerCall", {
  325. signal: data,
  326. to: companionSocket,
  327. });
  328. });
  329. peer.on("stream", (companionStream: any) => {
  330. companionVideoRef.current.srcObject = companionStream;
  331. companionAudioRef.current.srcObject = companionStream;
  332. });
  333. peer.on('connect', () => {
  334. setCallStatus('connection')
  335. setTimeout(() => setCallStatus('conversation'),500)
  336. })
  337. peer.on("close", handleLeaveCall);
  338. peer.on('error', handleLeaveCall)
  339. peer.signal(companionSignal);
  340. connectionRef.current = peer;
  341. } catch (e:any) {
  342. handleLeaveCall()
  343. }
  344. }, [companionSocket, companionSignal, setCallStatus,audioHtml,handleLeaveCall])
  345. useEffect(() => {
  346. socket.on("me", (id: string) => {
  347. setMySocket(id)
  348. socketIdChat(id)
  349. })
  350. },[])
  351. useEffect(() => {
  352. socket.on('incomeCall', ({ name, lastName, avatarUrl, color, number, from, signal }: any) => {
  353. if (connectionRef.current === null) {
  354. setName(name)
  355. setLastName(lastName)
  356. setAvatarUrl(avatarUrl)
  357. setColor(color)
  358. setNumber(number)
  359. setCompanionSocket(from)
  360. setCompanionSignal(signal)
  361. const audioRing = playNotification(`${prodBaseURL}/ringing.mp3`)
  362. audioRing.loop = true
  363. setAudioHtml(audioRing)
  364. setCallStatus('is calling you')
  365. }
  366. })
  367. }, [setCallStatus,companionSocket])
  368. useEffect(() => {
  369. if (callStatus === 'requesting...') {
  370. setName(_name)
  371. setLastName(_lastName)
  372. setAvatarUrl(_avatarUrl)
  373. setColor(_color)
  374. setNumber(_number)
  375. setTimeout(handleStartCall,500)
  376. }
  377. }, [callStatus,_name,_lastName,_avatarUrl,_color,_number, handleStartCall])
  378. useEffect(() => {
  379. if (callLast === 60) handleLeaveCall()
  380. }, [callLast, handleLeaveCall])
  381. return (
  382. <div className={classes.container} style={{ top: callStatus ? 0 : '-100%'}}>
  383. <video className={classes.myVideo} style={{width: !myStream || mutedMyVideo?0:250,height: !myStream || mutedMyVideo?0:'auto'}}
  384. ref={myVideoRef} playsInline autoPlay muted controls={false} />
  385. <Moveable
  386. target={myVideoRef.current}
  387. draggable={true}
  388. throttleDrag={0}
  389. hideDefaultLines={true}
  390. renderDirections={[]}
  391. rotationPosition="none"
  392. origin={false}
  393. onDrag={({ target, transform }: OnDrag) =>
  394. target!.style.transform = transform }
  395. />
  396. <div className={classes.modalCall} style={{width: fullScreen?'100vw':'34vw',height:fullScreen?'100vh':'auto'}}>
  397. <div className={classes.rightIcons}>
  398. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(false)}
  399. style={{backgroundColor:fullScreen?'rgb(36, 36, 36)':'rgb(70, 70, 70)'}}>
  400. <MinimizeIcon fontSize='small' />
  401. </div>
  402. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(true)}
  403. style={{backgroundColor:fullScreen?'rgb(70, 70, 70)':'rgb(36, 36, 36)'}}>
  404. <CropLandscapeIcon fontSize='small' />
  405. </div>
  406. <div className={classes.rightIconWrapperClose} onClick={handleLeaveCall}>
  407. <CloseIcon fontSize='small' />
  408. </div>
  409. </div>
  410. <div style={{ width: '100%', position: "relative" }}>
  411. {alert && <Alert variant="filled" severity="info" sx={{ backgroundColor: "rgb(70, 70, 70)" }}
  412. style={{ width: fullScreen?'auto':"100%", position: 'absolute', left: 0, bottom: -48 }}>{alert}</Alert>}
  413. {!fullScreen && <>
  414. <ListItemAvatar style={{margin:'25px 0px 5px 0px'}}>
  415. <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
  416. sx={{ background: color, width: 120, height: 120, marginRight: 2, fontSize:30,zIndex:0,margin:'0 auto'}}>
  417. {`${firstLetter(name)}${firstLetter(lastName)}`}
  418. </Avatar>
  419. </ListItemAvatar>
  420. <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
  421. ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
  422. primaryTypographyProps={{ color: '#dfdfdf', fontSize: 20, fontWeight: 500,textAlign: "center" }}/>
  423. <ListItemText primary={number} primaryTypographyProps={{ color: '#ffffff', fontSize: 15, fontWeight: 500, textAlign: "center" }} />
  424. <ListItemText secondary={callStatus} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  425. <ListItemText secondary={conversationLast} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  426. </>}
  427. </div>
  428. <video ref={companionVideoRef} playsInline muted autoPlay controls={false}
  429. style={{width: '100%',height:fullScreen?'100vh': 'auto',objectFit: 'cover',
  430. backgroundColor:'rgb(36, 36, 36)'}} onTimeUpdate={handleConversationLast} />
  431. <audio ref={companionAudioRef} autoPlay />
  432. <div className={classes.bottomWrapper}>
  433. {!myShareStream&&<div className={classes.bottomItem} onClick={handleMuteShare}>
  434. <Avatar className={classes.bottomIcon}
  435. sx={{backgroundColor: '#ffffff',color: 'rgb(36, 36, 36)', width: 44, height: 44,zIndex:0}}>
  436. {<StopScreenShareIcon fontSize="medium" />}
  437. </Avatar>
  438. <Typography variant="h6" className={classes.titleIconBottom}>StartShare</Typography>
  439. </div>}
  440. <div className={classes.bottomItem} onClick={handleMuteVideo}>
  441. <Avatar className={classes.bottomIcon}
  442. sx={{backgroundColor: mutedMyVideo?'#ffffff':'rgb(88, 88, 88)',color: mutedMyVideo?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  443. {mutedMyVideo?<VideocamOffIcon fontSize="medium" />:<VideocamIcon fontSize="medium" />}
  444. </Avatar>
  445. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyVideo?'Start Video':'Stop Video'}</Typography>
  446. </div>
  447. <div className={classes.bottomItem}>
  448. <Avatar className={classes.bottomIconEndAccept} onClick={handleLeaveCall}
  449. sx={{backgroundColor: '#f02a2a',color: '#ffffff', width: 44, height: 44,zIndex:0}}>
  450. <CallEndIcon fontSize="medium" />
  451. </Avatar>
  452. <Typography variant="h6" className={classes.titleIconBottom}>
  453. {callStatus === 'is calling you' ? 'Decline' : 'End Call'}
  454. </Typography>
  455. </div>
  456. {callStatus === 'is calling you' &&
  457. <div className={classes.bottomItem} style={{position:"relative"}}>
  458. <div className={classes.ringPulsate}></div>
  459. <Avatar className={classes.bottomIconEndAccept} onClick={handleAnswerCall}
  460. sx={{ backgroundColor: '#21f519', color: '#ffffff', width: 44, height: 44, zIndex: 0 }}>
  461. <PhoneIcon fontSize="medium" />
  462. </Avatar>
  463. <Typography variant="h6" className={classes.titleIconBottom}>
  464. Accept
  465. </Typography>
  466. </div>}
  467. <div className={classes.bottomItem}>
  468. <Avatar className={classes.bottomIcon} onClick={handleMuteAudio}
  469. sx={{backgroundColor: mutedMyAudio?'#ffffff':'rgb(88, 88, 88)',color: mutedMyAudio?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  470. {mutedMyAudio?<MicOffIcon fontSize="medium" />:<MicIcon fontSize="medium" />}
  471. </Avatar>
  472. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyAudio?'Unmute':'Mute'}</Typography>
  473. </div>
  474. </div>
  475. </div>
  476. </div>
  477. )
  478. }
  479. export default CallBar