refactor: criado conexao web socket global e movido alguns listeners para ela

websocket
willian-pessoa 2024-05-08 18:02:31 -03:00
parent 914fde7803
commit a5d3f19e1a
7 changed files with 122 additions and 91 deletions

View File

@ -2,7 +2,8 @@ import React, { useState, useRef, useEffect, useContext } from "react"
import { useHistory } from "react-router-dom" import { useHistory } from "react-router-dom"
import { format } from "date-fns" import { format } from "date-fns"
import openSocket from "socket.io-client" //import openSocket from "socket.io-client"
import { socket } from "../../services/socket"
import useSound from "use-sound" import useSound from "use-sound"
import Popover from "@material-ui/core/Popover" import Popover from "@material-ui/core/Popover"
@ -132,7 +133,7 @@ const NotificationsPopOver = () => {
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on("reload_page", (data) => { socket.on("reload_page", (data) => {
@ -193,7 +194,8 @@ const NotificationsPopOver = () => {
return () => { return () => {
socket.disconnect() socket.removeAllListeners('reload_page');
socket.removeAllListeners('onlineStatus');
} }
}, [user.id, handleLogout, user.profile]) }, [user.id, handleLogout, user.profile])
@ -201,12 +203,17 @@ const NotificationsPopOver = () => {
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on("connect", () => socket.emit("joinNotification")) const onConnectNotifications = () => {
socket.emit("joinNotification")
}
onConnectNotifications()
socket.on("ticket", data => { socket.on("connect", onConnectNotifications)
const onTicketNotifications = data => {
if (data.action === "updateUnread" || data.action === "delete") { if (data.action === "updateUnread" || data.action === "delete") {
@ -232,25 +239,18 @@ const NotificationsPopOver = () => {
return prevState return prevState
}) })
} }
}) }
socket.on("appMessage", data => {
socket.on("ticket", onTicketNotifications)
const onAppMessageNotifications = data => {
if ( if (
data.action === "create" && data.action === "create" &&
!data.message.read && !data.message.read &&
(data.ticket.userId === user?.id || !data.ticket.userId) (data.ticket.userId === user?.id || !data.ticket.userId)
) { ) {
setNotifications(prevState => { setNotifications(prevState => {
// prevState.forEach((e)=>{ // prevState.forEach((e)=>{
// //
// }) // })
@ -265,8 +265,6 @@ const NotificationsPopOver = () => {
return [data.ticket, ...prevState] return [data.ticket, ...prevState]
}) })
const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") || const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== user?.id) || (data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup || !data.ticket.userId data.ticket.isGroup || !data.ticket.userId
@ -275,20 +273,25 @@ const NotificationsPopOver = () => {
handleNotifications(data) handleNotifications(data)
} }
}) }
socket.on('notifyPeding', data =>{ socket.on("appMessage", onAppMessageNotifications)
if(settings?.length > 0 && getSettingValue('notificationTransferQueue') === 'enabled') handleNotifications("", data);
socket.on('notifyPeding', data => {
if (settings?.length > 0 && getSettingValue('notificationTransferQueue') === 'enabled') handleNotifications("", data);
}); });
return () => { return () => {
socket.disconnect() socket.off('connect', onConnectNotifications);
socket.off('ticket', onTicketNotifications);
socket.off('appMessage', onAppMessageNotifications);
socket.removeAllListeners('notifyPeding');
} }
}, [user, settings]) }, [user, settings])
const handleNotifications = (data, notify) => { const handleNotifications = (data, notify) => {
let isQueue = false; let isQueue = false;
if(!notify){ if (!notify) {
const { message, contact, ticket } = data const { message, contact, ticket } = data
const options = { const options = {
@ -319,15 +322,15 @@ const NotificationsPopOver = () => {
} }
return [notification, ...prevState] return [notification, ...prevState]
}) })
}else{ } else {
user.queues.forEach(queue =>{ user.queues.forEach(queue => {
if(queue.id === notify.data?.queue?.id){ if (queue.id === notify.data?.queue?.id) {
isQueue = true; isQueue = true;
} }
}) })
if(!isQueue){ if (!isQueue) {
return; return;
}else { } else {
const notification = new Notification(`${i18n.t("tickets.notification.messagePeding")} ${notify.data?.queue?.name}`); const notification = new Notification(`${i18n.t("tickets.notification.messagePeding")} ${notify.data?.queue?.name}`);
notification.onclick = e => { notification.onclick = e => {
e.preventDefault() e.preventDefault()

View File

@ -22,7 +22,8 @@ import MarkdownWrapper from "../MarkdownWrapper"
import { Tooltip } from "@material-ui/core" import { Tooltip } from "@material-ui/core"
import { AuthContext } from "../../context/Auth/AuthContext" import { AuthContext } from "../../context/Auth/AuthContext"
import toastError from "../../errors/toastError" import toastError from "../../errors/toastError"
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from "../../services/socket"
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
ticket: { ticket: {
@ -151,7 +152,7 @@ const TicketListItem = ({ ticket, remoteTicketsControll, settings }) => {
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('remoteTickesControll', (data) => { socket.on('remoteTickesControll', (data) => {
console.log('REMOTE TICKETS CONTROLL UPDATE2: ', data.tickets) console.log('REMOTE TICKETS CONTROLL UPDATE2: ', data.tickets)
@ -160,8 +161,7 @@ const TicketListItem = ({ ticket, remoteTicketsControll, settings }) => {
} }
}) })
const onSettingsTicketListItem = (data) => {
socket.on('settings', (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -170,11 +170,13 @@ const TicketListItem = ({ ticket, remoteTicketsControll, settings }) => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsTicketListItem)
return () => { return () => {
socket.disconnect() socket.removeAllListeners('remoteTickesControll');
socket.off('settings', onSettingsTicketListItem);
} }
}, []) }, [])

View File

@ -1,7 +1,7 @@
import React, { useState, useEffect, useReducer, useContext } from "react" import React, { useState, useEffect, useReducer, useContext } from "react"
//import openSocket from "socket.io-client"
import openSocket from "socket.io-client" import { socket } from "../../services/socket"
import { makeStyles } from "@material-ui/core/styles" import { makeStyles } from "@material-ui/core/styles"
import List from "@material-ui/core/List" import List from "@material-ui/core/List"
@ -243,7 +243,7 @@ const TicketsList = (props) => {
// if (tab=='search')return // if (tab=='search')return
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
const shouldUpdateTicket = ticket => const shouldUpdateTicket = ticket =>
(!ticket.userId || ticket.userId === user?.id || showAll) && (!ticket.userId || ticket.userId === user?.id || showAll) &&
@ -252,18 +252,19 @@ const TicketsList = (props) => {
const notBelongsToUserQueues = ticket => const notBelongsToUserQueues = ticket =>
ticket.queueId && selectedQueueIds.indexOf(ticket.queueId) === -1 ticket.queueId && selectedQueueIds.indexOf(ticket.queueId) === -1
socket.on("connect", () => { const onConnectTicketList = () => {
if (status) { if (status) {
socket.emit("joinTickets", status) socket.emit("joinTickets", status)
} else { } else {
socket.emit("joinNotification") socket.emit("joinNotification")
} }
}
}) onConnectTicketList()
socket.on("connect", onConnectTicketList)
const onTicketTicketList = data => {
socket.on("ticket", data => {
if (data.action === "updateUnread") { if (data.action === "updateUnread") {
@ -292,10 +293,11 @@ const TicketsList = (props) => {
if (data.action === "delete") { if (data.action === "delete") {
dispatch({ type: "DELETE_TICKET", payload: data.ticketId }) dispatch({ type: "DELETE_TICKET", payload: data.ticketId })
} }
}) }
socket.on("ticket", onTicketTicketList)
socket.on("appMessage", data => { const onAppMessageTicketList = data => {
if (data.action === "create" && shouldUpdateTicket(data.ticket)) { if (data.action === "create" && shouldUpdateTicket(data.ticket)) {
@ -307,7 +309,9 @@ const TicketsList = (props) => {
payload: data, payload: data,
}) })
} }
}) }
socket.on("appMessage", onAppMessageTicketList)
socket.on("contact", data => { socket.on("contact", data => {
if (data.action === "update") { if (data.action === "update") {
@ -326,8 +330,7 @@ const TicketsList = (props) => {
} }
}) })
const onSettingsTicketList = (data) => {
socket.on('settings', (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -336,11 +339,17 @@ const TicketsList = (props) => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsTicketList)
return () => { return () => {
socket.disconnect() socket.off("ticket", onTicketTicketList)
socket.off('appMessage', onAppMessageTicketList);
socket.removeAllListeners("contact")
socket.off('connect', onConnectTicketList);
socket.off('settings', onSettingsTicketList);
socket.removeAllListeners('remoteTickesControll');
} }
}, [status, showAll, user, selectedQueueIds, tab]) }, [status, showAll, user, selectedQueueIds, tab])
@ -349,7 +358,7 @@ const TicketsList = (props) => {
if (typeof updateCount === "function") { if (typeof updateCount === "function") {
updateCount(ticketsList.length) updateCount(ticketsList.length)
} }
if (ticketsList && status === "pending"){ if (ticketsList && status === "pending") {
setTickets(ticketsList) setTickets(ticketsList)
} }
// else{ // else{

View File

@ -1,6 +1,7 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom' import { useHistory } from 'react-router-dom'
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from '../../services/socket'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
@ -62,7 +63,7 @@ const useAuth = () => {
useEffect(() => { useEffect(() => {
const token = localStorage.getItem('token') const token = localStorage.getItem('token')
;(async () => { ; (async () => {
if (token) { if (token) {
try { try {
const { data } = await api.post('/auth/refresh_token') const { data } = await api.post('/auth/refresh_token')
@ -90,7 +91,7 @@ const useAuth = () => {
}, []) }, [])
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('user', (data) => { socket.on('user', (data) => {
if (data.action === 'update' && data.user.id === user.id) { if (data.action === 'update' && data.user.id === user.id) {
@ -98,7 +99,7 @@ const useAuth = () => {
} }
}) })
socket.on('settings', (data) => { const onSettingsAuth = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSetting((prevState) => { setSetting((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -107,10 +108,13 @@ const useAuth = () => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsAuth)
return () => { return () => {
socket.disconnect() socket.removeAllListeners('user');
socket.off('settings', onSettingsAuth);
} }
}, [user]) }, [user])

View File

@ -1,5 +1,7 @@
import { useState, useEffect, useReducer } from "react"; import { useState, useEffect, useReducer } from "react";
import openSocket from "socket.io-client"; //import openSocket from "socket.io-client";
import { socket } from "../../services/socket";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
@ -126,7 +128,7 @@ const useWhatsApps = () => {
}, []); }, []);
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL); //const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("whatsapp", data => { socket.on("whatsapp", data => {
if (data.action === "update") { if (data.action === "update") {
@ -158,7 +160,9 @@ const useWhatsApps = () => {
return () => { return () => {
socket.disconnect(); socket.removeAllListeners('whatsapp');
socket.removeAllListeners('whatsappSession');
socket.removeAllListeners('whatsappSessionMonit');
}; };
}, []); }, []);

View File

@ -32,6 +32,7 @@ import { WhatsAppsContext } from '../context/WhatsApp/WhatsAppsContext'
import { AuthContext } from '../context/Auth/AuthContext' import { AuthContext } from '../context/Auth/AuthContext'
import { Can } from '../components/Can' import { Can } from '../components/Can'
import openSocket from 'socket.io-client' import openSocket from 'socket.io-client'
import { socket } from '../services/socket'
import api from '../services/api' import api from '../services/api'
@ -118,9 +119,9 @@ const MainListItems = (props) => {
} }
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('settings', (data) => { const onSettingsMainListItem = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -129,10 +130,12 @@ const MainListItems = (props) => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsMainListItem)
return () => { return () => {
socket.disconnect() socket.off('settings', onSettingsMainListItem);
} }
}, []) }, [])

View File

@ -0,0 +1,6 @@
import { io } from 'socket.io-client';
// "undefined" means the URL will be computed from the `window.location` object
const URL = process.env.REACT_APP_BACKEND_URL
export const socket = io(URL);