index.tsx 16 KB

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