index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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,playNotificationWithoutPermission } 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 myVideoRef = useRef<any>(null);
  158. const companionVideoRef = useRef<any>(null);
  159. const companionAudioRef = useRef<any>(null);
  160. const [audioRing,setAudioRing] = useState<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<string>('')
  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 [conversationLast, cetConversationLast] = useState<string>('')
  173. const [fullScreen, setFullScreen] = useState<boolean>(false)
  174. const [alert, setAlert] = useState<string>('')
  175. const handleConversationLast = (e: any) =>
  176. cetConversationLast(getTimeBySeconds(e.target.currentTime))
  177. const handleMuteVideo = () => {
  178. if (myStream&&myStream.getVideoTracks()[0]) {
  179. setMutedMyVideo(!mutedMyVideo)
  180. myStream.getVideoTracks()[0].enabled = !myStream.getVideoTracks()[0].enabled
  181. } else {
  182. setAlert(`You can not ${mutedMyVideo?'enable':'disable'} Video before stream started`)
  183. }
  184. }
  185. const handleMuteAudio = () => {
  186. if (myStream&&myStream.getAudioTracks()[0]) {
  187. setMutedMyAudio(!mutedMyAudio)
  188. myStream.getAudioTracks()[0].enabled = !myStream.getAudioTracks()[0].enabled
  189. } else {
  190. setAlert(`You can not ${mutedMyAudio?'enable':'disable'} Audio before stream started`)
  191. }
  192. }
  193. const handleLeaveCall = () => {
  194. setCallStatus('hanging up...')
  195. if (connectionRef.current) {
  196. connectionRef.current.destroy();
  197. }
  198. setCallStatus('')
  199. };
  200. const handleStartCall = useCallback(async () => {
  201. setCallStatus('waiting...')
  202. const mediaDevices: any = navigator.mediaDevices
  203. const stream = await mediaDevices.getDisplayMedia({
  204. video: true,
  205. audio: true
  206. })
  207. setMyStream(stream)
  208. myVideoRef.current.srcObject = stream;
  209. const peer = new Peer({
  210. initiator: true,
  211. trickle: false,
  212. stream
  213. });
  214. setCallStatus('ringing...')
  215. setAlert('')
  216. setAudioRing(playNotification(`${prodBaseURL}/calling.mp3`))
  217. peer.on("signal", (data: any) => {
  218. socket.emit("callTo", {
  219. to: socketId,
  220. signalData: data,
  221. from: mySocket,
  222. userId: _id,
  223. companionId
  224. })
  225. });
  226. peer.on("stream", (companionStream: any) => {
  227. companionVideoRef.current.srcObject = companionStream;
  228. companionAudioRef.current.srcObject = companionStream;
  229. });
  230. socket.on("acceptedCall", ({ signal }: any) => {
  231. setCallStatus('connection')
  232. audioRing.pause()
  233. peer.signal(signal)
  234. setCallStatus('conversation')
  235. });
  236. connectionRef.current = peer;
  237. },[socketId,companionId,_id,mySocket,myVideoRef,setCallStatus,audioRing])
  238. const handleAnswerCall = useCallback(async () => {
  239. setCallStatus('connection')
  240. audioRing.pause()
  241. const stream = await navigator.mediaDevices.getUserMedia({
  242. video: true,
  243. audio: true
  244. })
  245. setMyStream(stream)
  246. myVideoRef.current.srcObject = stream;
  247. const peer = new Peer({
  248. initiator: false,
  249. trickle: false,
  250. stream,
  251. });
  252. peer.on("signal", (data: any) => {
  253. socket.emit("answerCall", {
  254. signal: data,
  255. to: companionSocket,
  256. });
  257. setCallStatus('conversation')
  258. setAlert('')
  259. });
  260. peer.on("stream", (companionStream: any) => {
  261. companionVideoRef.current.srcObject = companionStream;
  262. companionAudioRef.current.srcObject = companionStream;
  263. });
  264. peer.signal(companionSignal);
  265. connectionRef.current = peer;
  266. },[companionSocket,companionSignal,setCallStatus,audioRing])
  267. useEffect(() => {
  268. socket.on("me", (id: string) => {
  269. setMySocket(id)
  270. socketIdChat(id)
  271. })
  272. socket.on('incomeCall', ({ name, lastName, avatarUrl, color, number, from, signal }: any) => {
  273. if (connectionRef.current === null) {
  274. setCallStatus('is calling you')
  275. setName(name)
  276. setLastName(lastName)
  277. setAvatarUrl(avatarUrl)
  278. setColor(color)
  279. setNumber(number)
  280. setCompanionSocket(from)
  281. setCompanionSignal(signal)
  282. setAudioRing(playNotificationWithoutPermission(`${prodBaseURL}/ringing.mp3`))
  283. }
  284. })
  285. }, [setCallStatus])
  286. useEffect(() => {
  287. if(callStatus === 'requesting...') handleStartCall()
  288. }, [callStatus, handleStartCall])
  289. useEffect(() => {
  290. if (callStatus === '') {
  291. setName(chat.name)
  292. setLastName(chat.lastName)
  293. setAvatarUrl(chat.avatarUrl)
  294. setColor(chat.color)
  295. setNumber(chat.number)
  296. }
  297. }, [callStatus, chat])
  298. return (
  299. <div className={classes.container} style={{ top: callStatus ? 0 : '-100%'}}>
  300. <video className={classes.myVideo} style={{width: !myStream || mutedMyVideo?0:250,height: !myStream || mutedMyVideo?0:'auto'}}
  301. ref={myVideoRef} playsInline autoPlay muted controls={false} />
  302. <Moveable
  303. target={myVideoRef.current}
  304. draggable={true}
  305. throttleDrag={0}
  306. hideDefaultLines={true}
  307. renderDirections={[]}
  308. rotationPosition="none"
  309. origin={false}
  310. onDrag={({ target, transform }: OnDrag) =>
  311. target!.style.transform = transform }
  312. />
  313. <div className={classes.modalCall} style={{width: fullScreen?'100vw':'34vw',height:fullScreen?'100vh':'auto'}}>
  314. <div className={classes.rightIcons}>
  315. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(false)}
  316. style={{backgroundColor:fullScreen?'rgb(36, 36, 36)':'rgb(70, 70, 70)'}}>
  317. <MinimizeIcon fontSize='small' />
  318. </div>
  319. <div className={classes.rightIconWrapper} onClick={() => setFullScreen(true)}
  320. style={{backgroundColor:fullScreen?'rgb(70, 70, 70)':'rgb(36, 36, 36)'}}>
  321. <CropLandscapeIcon fontSize='small' />
  322. </div>
  323. <div className={classes.rightIconWrapperClose} onClick={handleLeaveCall}>
  324. <CloseIcon fontSize='small' />
  325. </div>
  326. </div>
  327. <div style={{ width: '100%', position: "relative" }}>
  328. {alert && <Alert variant="filled" severity="info" sx={{ backgroundColor: "rgb(70, 70, 70)" }}
  329. style={{ width: fullScreen?'auto':"100%", position: 'absolute', left: 0, bottom: -48 }}>{alert}</Alert>}
  330. {!fullScreen && <>
  331. <ListItemAvatar style={{margin:'25px 0px 5px 0px'}}>
  332. <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
  333. sx={{ background: color, width: 120, height: 120, marginRight: 2, fontSize:30,zIndex:0,margin:'0 auto'}}>
  334. {`${firstLetter(name)}${firstLetter(lastName)}`}
  335. </Avatar>
  336. </ListItemAvatar>
  337. <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
  338. ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
  339. primaryTypographyProps={{ color: '#dfdfdf', fontSize: 20, fontWeight: 500,textAlign: "center" }}/>
  340. <ListItemText primary={number} primaryTypographyProps={{ color: '#ffffff', fontSize: 15, fontWeight: 500, textAlign: "center" }} />
  341. <ListItemText secondary={callStatus} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  342. <ListItemText secondary={conversationLast} secondaryTypographyProps={{ color: "#dfdfdf", textAlign: "center" }} />
  343. </>}
  344. </div>
  345. <video ref={companionVideoRef} playsInline muted autoPlay controls={false}
  346. style={{width: '100%',height:fullScreen?'100vh': 'auto',objectFit: 'cover',backgroundColor:'rgb(36, 36, 36)'}} onTimeUpdate={handleConversationLast} />
  347. <audio ref={companionAudioRef} autoPlay />
  348. <div className={classes.bottomWrapper}>
  349. <div className={classes.bottomItem} onClick={handleMuteVideo}>
  350. <Avatar className={classes.bottomIcon}
  351. sx={{backgroundColor: mutedMyVideo?'#ffffff':'rgb(88, 88, 88)',color: mutedMyVideo?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  352. {mutedMyVideo?<VideocamOffIcon fontSize="medium" />:<VideocamIcon fontSize="medium" />}
  353. </Avatar>
  354. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyVideo?'Start Video':'Stop Video'}</Typography>
  355. </div>
  356. <div className={classes.bottomItem}>
  357. <Avatar className={classes.bottomIconEndAccept} onClick={handleLeaveCall}
  358. sx={{backgroundColor: '#f02a2a',color: '#ffffff', width: 44, height: 44,zIndex:0}}>
  359. <CallEndIcon fontSize="medium" />
  360. </Avatar>
  361. <Typography variant="h6" className={classes.titleIconBottom}>
  362. {callStatus === 'is calling you' ? 'Decline' : 'End Call'}
  363. </Typography>
  364. </div>
  365. {callStatus === 'is calling you' &&
  366. <div className={classes.bottomItem} style={{position:"relative"}}>
  367. <div className={classes.ringPulsate}></div>
  368. <Avatar className={classes.bottomIconEndAccept} onClick={handleAnswerCall}
  369. sx={{ backgroundColor: '#21f519', color: '#ffffff', width: 44, height: 44, zIndex: 0 }}>
  370. <PhoneIcon fontSize="medium" />
  371. </Avatar>
  372. <Typography variant="h6" className={classes.titleIconBottom}>
  373. Accept
  374. </Typography>
  375. </div>}
  376. <div className={classes.bottomItem}>
  377. <Avatar className={classes.bottomIcon} onClick={handleMuteAudio}
  378. sx={{backgroundColor: mutedMyAudio?'#ffffff':'rgb(88, 88, 88)',color: mutedMyAudio?'rgb(36, 36, 36)':'#ffffff', width: 44, height: 44,zIndex:0}}>
  379. {mutedMyAudio?<MicOffIcon fontSize="medium" />:<MicIcon fontSize="medium" />}
  380. </Avatar>
  381. <Typography variant="h6" className={classes.titleIconBottom}>{mutedMyAudio?'Unmute':'Mute'}</Typography>
  382. </div>
  383. </div>
  384. </div>
  385. </div>
  386. )
  387. }
  388. export default CallBar