Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect, useRef } from 'react';
- import userServices from '../services/userServices';
- const ChatAdmin = () => {
- const [socket, setSocket] = useState(null);
- const [messages, setMessages] = useState({});
- const [messageInputs, setMessageInputs] = useState({});
- const [typingStatus, setTypingStatus] = useState({});
- const { getAllUsers } = userServices;
- const [allUsers, setAllUsers] = useState([]);
- const typingTimeout = useRef({});
- useEffect(() => {
- const jwt = localStorage.getItem('token');
- const ws = new WebSocket(`ws://localhost:8003/ws/chat/?token=${jwt}`);
- // Quando la connessione è aperta, settiamo il socket nello stato
- ws.onopen = () => {
- setSocket(ws);
- };
- ws.onmessage = (event) => {
- const data = JSON.parse(event.data);
- switch (data.type) {
- case 'message_read':
- setMessages((prev) => ({
- ...prev,
- [data.user_id]: [
- ...(prev[data.user_id] || []),
- { message: "Message read", sender_role: "system" },
- ],
- }));
- break;
- case 'message':
- setMessages((prev) => ({
- ...prev,
- [data.user_id]: [...(prev[data.user_id] || []), data],
- }));
- // Invia una notifica di lettura al client solo se il socket è ancora aperto
- if (ws && ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({
- type: 'message_read',
- client_id: data.user_id,
- }));
- } else {
- console.log('errore message_read send');
- }
- break;
- case 'typing':
- setTypingStatus((prev) => ({
- ...prev,
- [data.user_id]: 'Client is typing...',
- }));
- if (typingTimeout.current[data.user_id]) {
- clearTimeout(typingTimeout.current[data.user_id]);
- }
- typingTimeout.current[data.user_id] = setTimeout(() => {
- setTypingStatus((prev) => ({
- ...prev,
- [data.user_id]: '',
- }));
- }, 3000);
- break;
- default:
- console.error("Unknown message type:", data.type);
- }
- };
- // Non impostiamo più qui setSocket(ws), lo facciamo in onopen
- return () => ws.close();
- }, [getAllUsers]);
- useEffect(() => {
- const fetchData = async () => {
- try {
- const response = await getAllUsers();
- const clients = response.filter((user) => user.role === 'client');
- setAllUsers(clients);
- const initialInputs = {};
- clients.forEach((client) => {
- initialInputs[client.id] = '';
- });
- setMessageInputs(initialInputs);
- } catch (error) {
- console.error("Error fetching users:", error);
- }
- };
- fetchData();
- }, [getAllUsers]);
- const sendMessage = (clientId) => {
- // Controllo se il socket è aperto prima di inviare
- if (socket && socket.readyState === WebSocket.OPEN && messageInputs[clientId].trim()) {
- socket.send(
- JSON.stringify({
- type: 'message',
- message: messageInputs[clientId],
- client_id: clientId,
- })
- );
- setMessages((prev) => ({
- ...prev,
- [clientId]: [
- ...(prev[clientId] || []),
- { message: messageInputs[clientId], sender_role: 'admin' },
- ],
- }));
- setMessageInputs((prev) => ({ ...prev, [clientId]: '' }));
- }
- };
- const handleInputChange = (clientId, value) => {
- setMessageInputs((prev) => ({ ...prev, [clientId]: value }));
- // Controllo se il socket è aperto prima di inviare "typing"
- if (socket && socket.readyState === WebSocket.OPEN) {
- socket.send(
- JSON.stringify({
- type: 'typing',
- client_id: clientId,
- })
- );
- }
- };
- return (
- <div>
- <h1>Admin Chat</h1>
- <div>
- {allUsers.map((user) => (
- <div
- key={user.id}
- className="chat-box"
- style={{ border: '1px solid #ccc', margin: '10px', padding: '10px' }}
- >
- <h4>{`Chat with Client ${user.username}`}</h4>
- <div className="messages" style={{ height: '150px', overflowY: 'auto' }}>
- {messages[user.id]?.map((msg, index) => (
- <p key={index}>
- {msg.sender_role === "system" ? (
- <span style={{ fontStyle: "italic", color: "gray" }}>
- {msg.message}
- </span>
- ) : (
- <strong>
- {msg.sender_role === "client" ? "Client" : "You"}: {msg.message}
- </strong>
- )}
- </p>
- ))}
- {typingStatus[user.id] && (
- <p style={{ fontStyle: "italic", color: "blue" }}>
- {typingStatus[user.id]}
- </p>
- )}
- </div>
- <input
- type="text"
- value={messageInputs[user.id] || ''}
- onChange={(e) => handleInputChange(user.id, e.target.value)}
- placeholder="Type your message"
- style={{ width: '80%', marginRight: '5px' }}
- />
- <button onClick={() => sendMessage(user.id)}>Send</button>
- </div>
- ))}
- </div>
- </div>
- );
- };
- export default ChatAdmin;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement