index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 , updateMessageCallById } 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 [callMsgId, setCallMsgId] = useState<string>('')
  162. const [mySocket, setMySocket] = useState<string>('')
  163. const [myStream, setMyStream] = useState<any>(null)
  164. const [myShareStream, setMyShareStream] = useState<any>(null)
  165. const [mutedMyVideo,setMutedMyVideo] = useState<boolean>(true)
  166. const [mutedMyAudio,setMutedMyAudio] = useState<boolean>(false)
  167. const [companionSocket, setCompanionSocket] = useState<string>('')
  168. const [companionSignal, setCompanionSignal] = useState<any>(null)
  169. const [audioHtml, setAudioHtml] = useState<any>(null)
  170. const [callLast, setCallLast] = useState<number>(0)
  171. const [conversationLast, setConversationLast] = useState<number>(0)
  172. const [fullScreen, setFullScreen] = useState<boolean>(false)
  173. const [alert, setAlert] = useState<string>('')
  174. const [name, setName] = useState<string>('')
  175. const [lastName, setLastName] = useState<string>('')
  176. const [avatarUrl, setAvatarUrl] = useState<string>('')
  177. const [color, setColor] = useState<string>('')
  178. const [number, setNumber] = useState<string>('')
  179. const handleLeaveCall = useCallback(() => {
  180. setCallStatus('hanging up...')
  181. if (connectionRef.current) {
  182. connectionRef.current.destroy()
  183. connectionRef.current = null
  184. }
  185. if(idAudioIntervalRef.current) clearInterval(idAudioIntervalRef.current)
  186. myVideoRef.current.srcObject = null
  187. companionVideoRef.current.srcObject = null
  188. companionAudioRef.current.srcObject = null
  189. if (audioHtml) {
  190. audioHtml.pause()
  191. setAudioHtml(null)
  192. }
  193. if (myStream) myStream.getTracks().forEach((track: any) => track.stop())
  194. if (callMsgId) updateMessageCallById(callMsgId, conversationLast)
  195. setCallMsgId('')
  196. setMyShareStream(null)
  197. setMutedMyVideo(false)
  198. setMutedMyAudio(false)
  199. setCompanionSocket('')
  200. setMyStream(null)
  201. setCompanionSignal(null)
  202. setCallLast(0)
  203. setConversationLast(0)
  204. setFullScreen(false)
  205. setAlert('')
  206. setTimeout(() => {
  207. setCallStatus('')
  208. setName('')
  209. setLastName('')
  210. setAvatarUrl('')
  211. setColor('')
  212. setNumber('')
  213. },500)
  214. }, [setCallStatus, audioHtml, myStream,callMsgId,conversationLast])
  215. const handleConversationLast = (e: any) => setConversationLast(e.target.currentTime)
  216. const handleMuteShare = async () => {
  217. try {
  218. if (myStream) {
  219. const mediaDevices: any = navigator.mediaDevices;
  220. const stream = await mediaDevices.getDisplayMedia({
  221. video: true,
  222. audio: true
  223. })
  224. setMyShareStream(stream)
  225. const shareTrack = stream.getVideoTracks()[0]
  226. const videoTrack = myStream.getVideoTracks()[0]
  227. const senders = connectionRef.current._pc.getSenders()
  228. const replaceStream = (track:any) => senders.forEach((sender: any) => sender.track.kind === "video" &&
  229. sender.replaceTrack(track))
  230. shareTrack.onended = () => {
  231. setMyShareStream(null)
  232. replaceStream(videoTrack)
  233. }
  234. replaceStream(shareTrack)
  235. } else {
  236. setAlert(`Can not start Share before stream`)
  237. setTimeout(() => setAlert(''),2000)
  238. }
  239. } catch (e: any) {
  240. setAlert(`Permission for getDisplayMedia is required!`)
  241. setTimeout(() => setAlert(''),2000)
  242. }
  243. }
  244. const handleMuteVideo = () => {
  245. if (myStream&&myStream.getVideoTracks()[0]) {
  246. setMutedMyVideo(!mutedMyVideo)
  247. myStream.getVideoTracks()[0].enabled = !myStream.getVideoTracks()[0].enabled
  248. } else {
  249. setAlert(`Can not ${mutedMyVideo ? 'start' : 'stop'} Video before stream`)
  250. setTimeout(() => setAlert(''),2000)
  251. }
  252. }
  253. const handleMuteAudio = () => {
  254. if (myStream&&myStream.getAudioTracks()[0]) {
  255. setMutedMyAudio(!mutedMyAudio)
  256. myStream.getAudioTracks()[0].enabled = !myStream.getAudioTracks()[0].enabled
  257. } else {
  258. setAlert(`Can not start ${mutedMyAudio ? 'start' : 'stop'} Audio before stream`)
  259. setTimeout(() => setAlert(''),2000)
  260. }
  261. }
  262. const handleStartCall = useCallback(async () => {
  263. try {
  264. setCallStatus('waiting...')
  265. const stream = await navigator.mediaDevices.getUserMedia({
  266. video: true,
  267. audio: true
  268. })
  269. stream.getVideoTracks()[0].enabled = false
  270. setMyStream(stream)
  271. myVideoRef.current.srcObject = stream;
  272. const peer = new Peer({
  273. initiator: true,
  274. trickle: false,
  275. stream,
  276. });
  277. setCallStatus('ringing...')
  278. const audioRing = playNotification(`${prodBaseURL}/calling.mp3`)
  279. audioRing.loop = true
  280. setAudioHtml(audioRing)
  281. idAudioIntervalRef.current = setInterval(() =>
  282. setCallLast(prevState => prevState + 1), 1000)
  283. peer.on("signal", (data: any) => {
  284. socket.emit("callTo", {
  285. to: socketId,
  286. signalData: data,
  287. from: mySocket,
  288. userId: _id,
  289. companionId,
  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,
  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...' && callMsgId === '') {
  378. setName(_name)
  379. setLastName(_lastName)
  380. setAvatarUrl(_avatarUrl)
  381. setColor(_color)
  382. setNumber(_number)
  383. sentMessageCallById(companionId, 0)
  384. .then((data: any) => setCallMsgId(data._id))
  385. setTimeout(handleStartCall, 500)
  386. }
  387. }, [callStatus,callMsgId,_name,_lastName,_avatarUrl,_color,_number,companionId, handleStartCall])
  388. useEffect(() => {
  389. if (callLast === 60) handleLeaveCall()
  390. }, [callLast, handleLeaveCall])
  391. return (
  392. <div className={classes.container} style={{ top: callStatus ? 0 : '-100%'}}>
  393. <video className={classes.myVideo} style={{width: !myStream || mutedMyVideo?0:250,height: !myStream || mutedMyVideo?0:'auto'}}
  394. ref={myVideoRef} playsInline autoPlay muted controls={false} />
  395. <Moveable
  396. target={myVideoRef.current}
  397. draggable={true}
  398. throttleDrag={0}
  399. hideDefaultLines={true}
  400. renderDirections={[]}
  401. rotationPosition="none"
  402. origin={false}
  403. onDrag={({ target, transform }: OnDrag) =>
  404. target!.style.transform = transform }
  405. />
  406. <div className={classes.modalCall} style={{width: fullScreen?'100vw':'34vw',height:fullScreen?'100vh':'auto'}}>
  407. <div className={classes.rightIcons}>
  408. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(false)}
  409. style={{backgroundColor:fullScreen?'rgb(36, 36, 36)':'rgb(70, 70, 70)'}}>
  410. <MinimizeIcon fontSize='small' />
  411. </div>
  412. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(true)}
  413. style={{backgroundColor:fullScreen?'rgb(70, 70, 70)':'rgb(36, 36, 36)'}}>
  414. <CropLandscapeIcon fontSize='small' />
  415. </div>
  416. <div className={classes.rightIconWrapperClose} onClick={handleLeaveCall}>
  417. <CloseIcon fontSize='small' />
  418. </div>
  419. </div>
  420. <div style={{ width: '100%', position: "relative" }}>
  421. {alert && <Alert variant="filled" severity="info" sx={{ backgroundColor: "rgb(70, 70, 70)" }}
  422. style={{ width: fullScreen?'auto':"100%", position: 'absolute', left: 0, bottom: -48 }}>{alert}</Alert>}
  423. {!fullScreen && <>
  424. <ListItemAvatar style={{margin:'25px 0px 5px 0px'}}>
  425. <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
  426. sx={{ background: color, width: 120, height: 120, marginRight: 2, fontSize:30,zIndex:0,margin:'0 auto'}}>
  427. {`${firstLetter(name)}${firstLetter(lastName)}`}
  428. </Avatar>
  429. </ListItemAvatar>
  430. <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
  431. ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
  432. primaryTypographyProps={{ color: '#dfdfdf', fontSize: 20, fontWeight: 500,textAlign: "center" }}/>
  433. <ListItemText primary={number} primaryTypographyProps={{ color: '#ffffff', fontSize: 15, fontWeight: 500, textAlign: "center" }} />
  434. <ListItemText secondary={callStatus} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  435. {conversationLast&&<ListItemText secondary={getTimeBySeconds(conversationLast)} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />}
  436. </>}
  437. </div>
  438. <video ref={companionVideoRef} playsInline muted autoPlay controls={false}
  439. style={{width: '100%',height:fullScreen?'100vh': 'auto',objectFit: 'cover',
  440. backgroundColor:'rgb(36, 36, 36)'}} onTimeUpdate={handleConversationLast} />
  441. <audio ref={companionAudioRef} autoPlay />
  442. <div className={classes.bottomWrapper}>
  443. {!myShareStream&&<div className={classes.bottomItem} onClick={handleMuteShare}>
  444. <Avatar className={classes.bottomIcon}
  445. sx={{backgroundColor: '#ffffff',color: 'rgb(36, 36, 36)', width: 44, height: 44,zIndex:0}}>
  446. {<StopScreenShareIcon fontSize="medium" />}
  447. </Avatar>
  448. <Typography variant="h6" className={classes.titleIconBottom}>StartShare</Typography>
  449. </div>}
  450. <div className={classes.bottomItem} onClick={handleMuteVideo}>
  451. <Avatar className={classes.bottomIcon}
  452. sx={{backgroundColor: mutedMyVideo?'#ffffff':'rgb(88, 88, 88)',color: mutedMyVideo?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  453. {mutedMyVideo?<VideocamOffIcon fontSize="medium" />:<VideocamIcon fontSize="medium" />}
  454. </Avatar>
  455. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyVideo?'Start Video':'Stop Video'}</Typography>
  456. </div>
  457. <div className={classes.bottomItem}>
  458. <Avatar className={classes.bottomIconEndAccept} onClick={handleLeaveCall}
  459. sx={{backgroundColor: '#f02a2a',color: '#ffffff', width: 44, height: 44,zIndex:0}}>
  460. <CallEndIcon fontSize="medium" />
  461. </Avatar>
  462. <Typography variant="h6" className={classes.titleIconBottom}>
  463. {callStatus === 'is calling you' ? 'Decline' : 'End Call'}
  464. </Typography>
  465. </div>
  466. {callStatus === 'is calling you' &&
  467. <div className={classes.bottomItem} style={{position:"relative"}}>
  468. <div className={classes.ringPulsate}></div>
  469. <Avatar className={classes.bottomIconEndAccept} onClick={handleAnswerCall}
  470. sx={{ backgroundColor: '#21f519', color: '#ffffff', width: 44, height: 44, zIndex: 0 }}>
  471. <PhoneIcon fontSize="medium" />
  472. </Avatar>
  473. <Typography variant="h6" className={classes.titleIconBottom}>
  474. Accept
  475. </Typography>
  476. </div>}
  477. <div className={classes.bottomItem}>
  478. <Avatar className={classes.bottomIcon} onClick={handleMuteAudio}
  479. sx={{backgroundColor: mutedMyAudio?'#ffffff':'rgb(88, 88, 88)',color: mutedMyAudio?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  480. {mutedMyAudio?<MicOffIcon fontSize="medium" />:<MicIcon fontSize="medium" />}
  481. </Avatar>
  482. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyAudio?'Unmute':'Mute'}</Typography>
  483. </div>
  484. </div>
  485. </div>
  486. </div>
  487. )
  488. }
  489. export default CallBar