YorKnEz

Untitled

Apr 26th, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.22 KB | None | 0 0
  1. /* eslint-disable react-hooks/exhaustive-deps */
  2. import React, { useEffect, useLayoutEffect, useState } from 'react'
  3. import { useSelector } from 'react-redux'
  4. import { Button, ButtonGroup, Dropdown, Form, Spinner } from 'react-bootstrap'
  5. import { useParams } from 'react-router'
  6.  
  7. import axios from 'axios'
  8. import jwt_decode from 'jwt-decode'
  9. import Pusher from 'pusher-js'
  10. import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
  11. import * as Icons from '@fortawesome/free-solid-svg-icons'
  12.  
  13. import './Chatroom.css'
  14. import ChatroomHeader from '../../components/ChatroomHeader'
  15. import Message from '../../components/Message'
  16. import CategoriesList from '../../components/CategoriesList'
  17.  
  18. const ip = process.env.REACT_APP_IP
  19. const serverlessIP = process.env.REACT_APP_KEYMANAGERIP
  20. var CryptoJS = require('crypto-js')
  21.  
  22. let arr = []
  23.  
  24. export default function Chatroom() {
  25. const { category } = useParams()
  26. const [messages, setMessages] = useState([])
  27. const [message, setMessage] = useState('')
  28. const [key, setKey] = useState('')
  29. const chatroom = JSON.parse(localStorage.getItem('category'))
  30. const [isLoading, setIsLoading] = useState(true)
  31.  
  32. async function decryptmessage(message, decryptkey) {
  33. var bytes = await CryptoJS.AES.decrypt(message, decryptkey)
  34. var originalMessage = await bytes.toString(CryptoJS.enc.Utf8)
  35. return originalMessage
  36. }
  37.  
  38. const apidata = { category: category }
  39. useEffect(() => {
  40. let pusher
  41. console.log('1')
  42. axios
  43. .post(serverlessIP, { category: category })
  44. .then(responsekey => {
  45. console.log('2')
  46. setKey(responsekey.data)
  47. axios
  48. .post(ip + '/getMessages', apidata)
  49. .then(response => {
  50. console.log('3')
  51. if (response.status === 200) {
  52. arr = response.data
  53. arr.forEach(element => {
  54. console.log('4')
  55. axios
  56. .get(process.env.REACT_APP_IP + '/profile/' + element.author)
  57. .then(response => {
  58. console.log('5')
  59. element.authorName =
  60. response.data.firstName + ' ' + response.data.lastName
  61. })
  62. if (responsekey.data) {
  63. try {
  64. var bytes = CryptoJS.AES.decrypt(
  65. element.message,
  66. responsekey.data
  67. )
  68. var originalMessage = bytes.toString(CryptoJS.enc.Utf8)
  69. element.message = originalMessage
  70. } catch (e) {
  71. console.log(e)
  72. }
  73. }
  74. console.log('6')
  75. })
  76. setMessages(response.data)
  77. console.log('7')
  78. }
  79. })
  80. .catch(e => console.log(e))
  81. console.log('8')
  82. setIsLoading(false)
  83. pusher = new Pusher(process.env.REACT_APP_KEY, {
  84. cluster: process.env.REACT_APP_CLUSTER,
  85. })
  86.  
  87. var channel = pusher.subscribe(category)
  88. channel.bind('message', async function (data) {
  89. if (data.message.type === 'msgDelete') {
  90. let arr2 = [...arr]
  91. const position = arr2.findIndex(
  92. message => message._id === data.message._id
  93. )
  94. if (position > -1) {
  95. arr2.splice(position, 1)
  96. }
  97. arr = [...arr2]
  98. setMessages(arr)
  99. } else {
  100. try {
  101. data.message.message = await decryptmessage(
  102. data.message.message,
  103. responsekey.data
  104. )
  105. } catch (e) {
  106. console.log(e)
  107. }
  108. arr = [data.message, ...arr]
  109. setMessages(arr)
  110. }
  111. })
  112. })
  113. .catch(e => console.log(e))
  114. console.log('9')
  115.  
  116. return () => {
  117. pusher.unsubscribe(category)
  118. }
  119. }, [category])
  120.  
  121. const jwt = useSelector(state => state?.jwt?.jwt)
  122. const jwtDecoded = jwt_decode(jwt)
  123. const userID = jwtDecoded.userID
  124.  
  125. const sendMessage = event => {
  126. if (message) {
  127. var EncryptedMessage = CryptoJS.AES.encrypt(message, key).toString()
  128.  
  129. const apidata2 = {
  130. messageData: {
  131. message: EncryptedMessage,
  132. type: 'msg',
  133. category: category,
  134. },
  135. userID: userID,
  136. jwt: jwt,
  137. }
  138.  
  139. axios.post(ip + '/sendMessage', apidata2)
  140.  
  141. setMessage('')
  142. }
  143. event.preventDefault()
  144. }
  145.  
  146. const sendImage = event => {
  147. const formData = new FormData()
  148.  
  149. formData.append('image', event.target.files[0])
  150. formData.append('type', 'img')
  151. formData.append('category', category)
  152. formData.append('userID', userID)
  153. formData.append('jwt', jwt)
  154.  
  155. axios.post(process.env.REACT_APP_IP + '/sendPicture', formData)
  156. }
  157.  
  158. const sendFile = event => {
  159. const formData = new FormData()
  160.  
  161. formData.append('file', event.target.files[0])
  162. formData.append('type', 'file')
  163. formData.append('category', category)
  164. formData.append('userID', userID)
  165. formData.append('jwt', jwt)
  166.  
  167. axios.post(process.env.REACT_APP_IP + '/sendFile', formData)
  168. }
  169.  
  170. const handleScroll = event => {
  171. const target = event.target
  172.  
  173. if (target.scrollHeight + target.scrollTop === target.clientHeight) {
  174. const apidata = {
  175. category,
  176. index: arr.length,
  177. }
  178. axios
  179. .post(ip + '/getMessages', apidata)
  180. .then(response => {
  181. if (response.status === 200) {
  182. let tempArr = response.data
  183. tempArr.forEach(element => {
  184. if (key) {
  185. try {
  186. var bytes = CryptoJS.AES.decrypt(element.message, key)
  187. var originalMessage = bytes.toString(CryptoJS.enc.Utf8)
  188. element.message = originalMessage
  189. } catch (e) {
  190. console.log(e)
  191. }
  192. }
  193. })
  194. arr = [...arr, ...tempArr]
  195. setMessages(arr)
  196. }
  197. })
  198. .catch(e => console.log(e))
  199. }
  200. }
  201.  
  202. // const messageList = messages.map(message => {
  203. // return <Message message={message} key={message._id} />
  204. // })
  205.  
  206. return (
  207. <div className='chatroom-page'>
  208. {!isLoading ? (
  209. <>
  210. <div className='categories-left'>
  211. <CategoriesList />
  212. </div>
  213. <div className='chatroom-container'>
  214. <ChatroomHeader chatroom={chatroom} />
  215. <div onScroll={handleScroll} className='message-list'>
  216. {messages.map(message => (
  217. <Message message={message} key={message._id} />
  218. ))}
  219. </div>
  220. <Form className='send-box'>
  221. <Dropdown as={ButtonGroup}>
  222. <Dropdown.Toggle
  223. className='button button-round dropdown-toggle'
  224. title='Attachments'>
  225. <FontAwesomeIcon
  226. style={{ paddingRight: '2px' }}
  227. color='#fff'
  228. icon={Icons.faPaperclip}
  229. />
  230. </Dropdown.Toggle>
  231. <Dropdown.Menu className='dropdown-menu'>
  232. <div className='dropdown-item'>
  233. <label
  234. style={{ marginBottom: '0px' }}
  235. htmlFor='image-upload-button'>
  236. <div
  237. className='button button-round'
  238. style={{
  239. cursor: 'pointer',
  240. display: 'flex',
  241. justifyContent: 'center',
  242. alignItems: 'center',
  243. }}
  244. variant='light'>
  245. <FontAwesomeIcon
  246. style={{ paddingRight: '2px' }}
  247. color='#fff'
  248. icon={Icons.faImage}
  249. />
  250. </div>
  251. </label>
  252. <input
  253. type='file'
  254. accept='image/*'
  255. id='image-upload-button'
  256. style={{ display: 'none' }}
  257. onChange={sendImage}
  258. />
  259. </div>
  260. <div className='dropdown-item'>
  261. <label
  262. style={{ marginBottom: '0px' }}
  263. htmlFor='file-upload-button'>
  264. <div
  265. className='button button-round'
  266. style={{
  267. cursor: 'pointer',
  268. display: 'flex',
  269. justifyContent: 'center',
  270. alignItems: 'center',
  271. }}
  272. variant='light'>
  273. <FontAwesomeIcon
  274. style={{ paddingRight: '2px' }}
  275. color='#fff'
  276. icon={Icons.faFile}
  277. />
  278. </div>
  279. </label>
  280. <input
  281. type='file'
  282. id='file-upload-button'
  283. style={{ display: 'none' }}
  284. onChange={sendFile}
  285. />
  286. </div>
  287. </Dropdown.Menu>
  288. </Dropdown>
  289. <Form.Control
  290. className='textbox message-input'
  291. placeholder='Send a message'
  292. aria-label='message'
  293. value={message}
  294. onChange={data => setMessage(data.target.value)}
  295. />
  296. <Button
  297. className='button button-green button-round'
  298. type='submit'
  299. onClick={sendMessage}>
  300. <FontAwesomeIcon color='#fff' icon={Icons.faPaperPlane} />
  301. </Button>
  302. </Form>
  303. </div>
  304. </>
  305. ) : (
  306. <div className='loading-box'>
  307. <Spinner animation='border' />
  308. </div>
  309. )}
  310. </div>
  311. )
  312. }
  313.  
Advertisement
Add Comment
Please, Sign In to add comment